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

如何用eslint-plugin-import配置指定规则的导入排序?

配置eslint-plugin-import实现指定导入顺序

需求说明

我希望导入遵循以下顺序:React优先,其次是外部包、代码库内部模块、当前目录模块,示例如下:

import * as React from "react"
import { css } from "emotion"
import a from "hooks" // 因按包名排序,此导入在emotion之后

import Form from "my/own/component/path" // 注意我希望这些组之间有空行

import Something from "./something" // 当前目录导入

当前已有eslint-plugin-import配置,需要调整以满足上述需求:

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

调整后的最终配置

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

关键改动说明

  • 调整分组顺序:新增internal(内部模块)分组,把整体顺序改成builtin(Node内置模块)→external(外部包)→internal(内部模块)→parent(上级目录)→sibling(同级目录)→index(当前目录索引),完全匹配你的需求层级。
  • 强制组间空行:将newlines-between设为always,自动在不同导入组之间添加空行,和示例格式一致。
  • 优化路径匹配规则:
    • 保留react的前置规则,确保它始终排在所有外部包最前面。
    • 新增内部模块的匹配规则,用my/**匹配你的内部模块路径(如果内部模块前缀不是my,替换成实际前缀即可),让内部模块单独成组。
  • 清理无效规则:删掉原配置里pattern: "**"和pattern: "./**"的无效规则,避免干扰正常分组逻辑。
  • 开启严格分组:添加distinctGroup: true,确保每个分组严格隔离,不会出现跨组混排的情况。

扩展说明

如果你的内部模块有多个前缀(比如@company/*),可以修改pattern为数组形式匹配多个前缀:

{
  "group": "internal",
  "pattern": ["my/**", "@company/**"],
  "position": "after"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:30:29