You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置ESLint实现VSCode「整理导入」同款导入排序?

实现VSCode默认导入排序的ESLint配置方案

可以通过ESLint实现和VSCode「整理导入」一致的排序规则,下面提供两种可行方案,你可以根据偏好选择:

方案一:调整eslint-plugin-simple-import-sort的分组规则

既然你已经在用eslint-plugin-simple-import-sort,只需修改它的分组配置,让项目内部@/开头的模块排在最前面,就能匹配VSCode的排序逻辑。

在你的ESLint配置文件(比如.eslintrc.json)中添加或修改以下规则:

{
  "plugins": ["simple-import-sort"],
  "rules": {
    "simple-import-sort/imports": [
      "error",
      {
        "groups": [
          // 优先排项目内部模块(@/开头)
          ["^@/.*$"],
          // 然后是第三方依赖:先next相关包,再react,最后其他第三方包
          ["^next/", "^react$", "^[a-zA-Z-]+$"],
          // 最后是相对路径导入(./或../开头)
          ["^\\./.*$", "^\\.\\./.*$"]
        ]
      }
    ],
    "simple-import-sort/exports": "error"
  }
}

方案二:使用eslint-plugin-import的排序规则

如果你更倾向于用eslint-plugin-import控制排序,可按以下步骤配置:

首先安装依赖:

npm install eslint-plugin-import --save-dev

然后在ESLint配置文件中添加:

{
  "plugins": ["import"],
  "rules": {
    "import/order": [
      "error",
      {
        "groups": ["internal", "external", "builtin", "parent", "sibling", "index"],
        "pathGroups": [
          {
            "pattern": "@/**",
            "group": "internal",
            "position": "before"
          },
          {
            "pattern": "next/**",
            "group": "external",
            "position": "before"
          },
          {
            "pattern": "react",
            "group": "external",
            "position": "after"
          }
        ],
        "pathGroupsExcludedImportTypes": ["builtin"],
        "alphabetize": {
          "order": "asc",
          "caseInsensitive": true
        },
        "newlines-between": "always"
      }
    ]
  }
}

自动修复所有文件

配置完成后,运行以下命令就能自动修复项目中所有文件的导入排序:

npx eslint --fix .

另外,建议开启VSCode的ESLint自动修复功能(在设置中开启editor.codeActionsOnSave里的source.fixAll.eslint),这样每次保存文件时都会自动按规则整理导入,保持代码一致性。

内容的提问来源于stack exchange,提问作者jakelinnzy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:07:39