vscode保存时格式化卡顿主因是配置不当而非prettier本身慢:eslint串行冲突、大文件全量解析、node_modules/dist被误格式化、.prettierignore未生效、全局prettier查找耗时、文件监听负担过重。

VSCode 保存时格式化卡顿,基本不是 Prettier 本身太慢,而是它被放在了错误的执行路径上——比如和 ESLint 串行打架、反复解析整个文件、或者对 node_modules 里的 bundle.js 也硬要格式化一把。
为什么 editor.formatOnSave 一开就卡?
VSCode 默认在保存时调用整个文档的格式化服务。对大文件(>1000 行)或生成文件(如 dist/*.js),Prettier 需完整 parse + print,CPU 和 I/O 压力陡增。更糟的是,若同时启用了 eslint.format.enable 或其他格式化扩展,它们可能被串行触发,形成“格式化链”阻塞。
- 检查是否多个格式化工具共存:运行命令面板 → 输入
Format Document With...,看列出几个提供者 - 确认
eslint.format.enable是否为true;建议设为false,改用 ESLint 的保存前 lint(不自动修) -
editor.formatOnSaveMode默认是file,改成modifications可只处理你改过的几行,大幅降低开销
.prettierignore 不只是“忽略”,它是性能开关
很多人建了 .prettierignore 却没生效,原因常是路径没匹配上,或 VS Code 没读到它。Prettier-VSCode 默认会从当前文件路径向上找 .prettierignore,但前提是该文件在工作区根目录下,且没有被 files.watcherExclude 先一步屏蔽。
- 必须放在项目根目录(即
package.json所在层),内容示例:node_modules/ dist/ build/ *.min.js coverage/
- 配合 VS Code 设置:
"prettier.ignorePath": ".prettierignore"(显式声明,避免查找失败) - 注意:VS Code 的
files.watcherExclude也要同步配置,否则编辑器仍在后台监听这些目录,浪费资源
本地安装 Prettier + 关闭全局解析
如果项目里没装 prettier,插件会 fallback 到全局安装或内置版本,而全局模块路径查找、版本兼容判断、甚至跨 Node 版本加载都会拖慢首次格式化速度。更关键的是,prettier.resolveGlobalModules: true(旧版默认)会让插件每次启动都扫描全局 node_modules。
- 确保项目本地安装:
npm install --save-dev prettier(或yarn add -D prettier) - 在
.vscode/settings.json中强制关闭全局解析:"prettier.resolveGlobalModules": false - 顺手关掉 editorconfig 支持:
"prettier.useEditorConfig": false,避免多一层配置文件解析
大型项目别只盯 Prettier,先砍掉文件监控负担
Prettier 卡,常常是因为 VS Code 自己已经快喘不上气了——它正忙着监听 node_modules 里 2 万个文件的变化,或为 dist/ 下的 500 个 bundle 做语义索引。这时候再加一个格式化请求,就是压垮骆驼的最后一根稻草。
- 在
settings.json加入:"files.watcherExclude": { "**/node_modules/**": true, "**/dist/**": true, "**/build/**": true, "**/.git/**": true } - 禁用 TypeScript 的全量自动导入扫描:
"typescript.preferences.includePackageJsonAutoImports": "auto"(而非"always") - 如果不用小地图、空白符提示等 UI 功能,直接关掉:
"editor.minimap.enabled": false、"editor.renderWhitespace": "none"
真正卡住的往往不是格式化逻辑本身,而是 VS Code 在等文件系统通知、等语言服务器响应、等插件初始化完成——这些延迟叠加起来,比 Prettier 多花 200ms 还要命。











