

新闻资讯
行业动态VSCode 的 formatOnSave 不生效主因是格式化器未绑定或配置冲突:需启用 "editor.formatOnSave": true,安装对应语言扩展,设置 "editor.defaultFormatter",多语言文件需单独配置,Prettier 换行由 printWidth 控制,缩进不一致需统一 editor.insertSpaces 和 .editorconfig,Prettier 与 ESLint 冲突应禁用 ESLint 自动修复而用 eslint-plugin-prettier。
formatOnSave 不生效?常见现象是:保存文件后,代码没自动格式化,或只做了部分调整(比如缩进变了但换行没处理)。根本原因通常是格式化器未正确绑定或配置冲突。
settings.json 中的 "editor.formatOnSave": true 必须存在,且不能被工作区设置覆盖esbenp.pret
tier-vscode 对 JavaScript/TypeScript,ms-python.python 自带 PEP8 格式化)"editor.defaultFormatter" 是否指向了你期望的格式化器,例如:"editor.defaultFormatter": "esbenp.prettier-vscode"
.vue),需额外配置 "[vue]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }
editor.wordWrap 或改用 bounded
editor.wordWrap 控制的是编辑器「视觉换行」,和代码格式化无关,但它常被误认为是「格式化导致换行」。真实影响格式化的,是格式化器自身的换行规则(如 Prettier 的 printWidth)。
"editor.wordWrap": "off" —— 纯文本不折行(滚动条出现)"editor.wordWrap": "bounded" —— 只在视口宽度内折行,不影响保存后的内容printWidth: 80 会把超过 80 字符的表达式自动换行"printWidth": 9999;但注意这可能破坏可读性,尤其对函数链或 JSXeditor.insertSpaces 和 editor.detectIndentation
VSCode 默认用空格缩进,但一旦打开一个已有 Tab 缩进的旧文件,editor.detectIndentation 可能自动切换为 Tab,导致后续输入不一致。
"editor.insertSpaces": true 强制插入空格(推荐保持为 true)"editor.detectIndentation": false 关闭自动检测,避免被单个文件带偏整个工作区习惯.editorconfig,内容示例root = true [*] indent_style = space indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true
EditorConfig for VS Code 扩展才能识别该文件典型表现:保存一次,缩进变 2 空格;再保存一次,又变 4 空格;甚至报错 Expected indentation of 4 spaces but found 2。这是 ESLint 规则(如 indent)和 Prettier 自动格式化在互相覆盖。
fix on save 和 Prettier 的 format on save
eslint-plugin-prettier 将 Prettier 规则转为 ESLint 错误提示"eslint.options": { "plugins": ["prettier"] },
"eslint.validate": ["javascript", "typescript", "vue"],
"prettier.eslintIntegration": falseprettier-eslint 这类包装器,务必确认其版本与 Prettier 兼容(v3+ 已废弃该包).prettierrc、.editorconfig、package.json 中的 eslintConfig 全部提交到仓库,并在 README 里写明「运行 npm run format 统一格式」——否则光靠 VSCode 设置,永远有漏网之鱼。