VSCode 中保存时格式化代码出现反复缩进的问题
背景
vscode 保存项目时,eslint 进行格式化代码后会出现反复缩进的问题
原因
VSCode 同时使用了 ESLint 插件和 Prettier 插件,导致保存时同时进行了 eslint 格式化和 prettier 格式化。
解决方法
- 关闭 Prettier 插件
- 修改 vscode 配置
- 关闭全局的保存格式化配置:
"editor.formatOnSave": false,
- 开启只使用 eslint 格式化
"editor.codeActionsOnSave": { "source.fixAll": false, "source.fixAll.eslint": true, "source.fixAll.stylelint": true, },
- 关闭全局的保存格式化配置:
项目统一配置
为了防止其他项目的开发者出现问题,建议统一项目配置,将配置代码保存到项目的 .vscode/settings.json 文件内,上传到 git
.vscode/settings.json
{
"editor.codeActionsOnSave": {
"source.fixAll": false,
"source.fixAll.eslint": true,
"source.fixAll.stylelint": true,
},
"editor.quickSuggestions": {
"other": true,
"comments": true,
"strings": true
},
"editor.tabSize": 2,
"editor.formatOnSave": false, // 如果开启,保存时的 eslint 无法正常使用
// eslint 保存文件时是否自动修复
"eslint.alwaysShowStatus": true,
"eslint.codeActionsOnSave.mode": "all", // all 一次性修复所有可能的问题,problems 只修复当前的问题(逐个修复)
"eslint.validate": [
"javascript",
"javascriptreact",
"vue-html",
"html",
"vue",
"wpy",
"wxml",
"wxss",
"cjson",
"wxs",
"typescript",
"typescriptreact",
// {
// "language": "vue-html",
// "autoFix": true
// },
// {
// "language": "html",
// "autoFix": true
// },
// {
// "language": "vue", // 保存vue文件时是否自动修复,基于 eslint.autoFixOnSave 设置
// "autoFix": true
// }
],
}