vscode保存时自动排序import依赖eslint的--fix能力及simple-import-sort/imports规则配置,而非原生organizeimports;需设规则为"error"、启用source.fixall.eslint、确保eslint.validate覆盖文件类型且parseroptions.project路径正确。

VSCode 保存时自动排序 import,靠的不是插件本身,而是 ESLint 的 --fix 能力 + 正确配置的 simple-import-sort/imports 规则。 它不提供独立命令或右键菜单,也不依赖 VSCode 原生 organizeImports;一旦配错环节(比如没开修复、规则没生效、解析器失效),就完全静默——既不报错,也不排序。
为什么 editor.codeActionsOnSave: { "source.organizeImports": true } 不起作用
这个设置调用的是 TypeScript 语言服务或 import-sort 的逻辑,和 eslint-plugin-simple-import-sort 无关。它默认只做路径字母序、删未使用项、加空行,不会按插件定义的分组规则重排。两者混用还会导致顺序冲突(比如 ESLint 排完,VSCode 又按自己规则再排一遍)。
- TS 项目启用
source.organizeImports后,VSCode 会忽略 ESLint 的 import 排序修复 - JS 项目若没配
jsconfig.json或typeAcquisition.enable: true,该功能甚至不触发 -
simple-import-sort的分组逻辑(如node:在前、@/居中、./在后)只有 ESLint--fix能执行
simple-import-sort/imports 规则必须设为 "error" 并启用 source.fixAll.eslint
设成 "warn" 或放在 overrides 里但文件匹配不上,规则根本不会参与修复流程。VSCode 的保存修复只响应 "error" 级别且被识别到的规则。
- 在
.eslintrc.js或eslint.config.mjs中写:"simple-import-sort/imports": ["error", { groups: [...] }] - VSCode
settings.json必须包含:"editor.codeActionsOnSave": { "source.fixAll.eslint": true } - 确保
eslint.validate列出了当前文件类型,例如:"eslint.options": { "extensions": [".ts", ".tsx", ".js", ".jsx"] } - TypeScript 项目务必在
parserOptions.project指定tsconfig.json,否则路径解析失败,分组全乱
自定义分组正则容易写错的三个地方
插件通过正则匹配导入路径字符串来分组,但路径字符串不含引号、不带扩展名,且大小写敏感——这些细节直接决定分组是否命中。
-
['^@myorg/']匹配import { foo } from '@myorg/utils',但不匹配import '@myorg/shim'(后者是副作用导入,应归入['^\u0000']组) -
['^\.']匹配./foo和../bar,但import 'utils'(无点开头)会被误判为第三方包——需明确写成['^\w']或['^@?\w'] - TypeScript 类型导入(
import type)默认和值导入混在同一组;要分离,得用['^import\s+type', '^import\s+(?!type)']这类更精确的正则
真正卡住人的往往不是规则怎么写,而是 ESLint 根本没跑起来:文件没被 eslint.validate 覆盖、parserOptions.project 路径错、或者 VSCode 当前工作区没识别到本地 node_modules/eslint。先运行 npx eslint --ext .ts,.tsx src/ --fix 确认命令行能修,再排查编辑器集成问题。











