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

如何配置eslint-plugin-import的import/order实现指定导入排序?

解决eslint-plugin-import的import/order导入排序问题

问题背景

尝试多种方法后,仍无法通过eslint-plugin-import的import/order规则实现预期的导入排序。当前.eslint.js配置如下:

"import/order": [
    "error",
    {
        "groups": ["builtin", "external", "internal", "sibling"],
        "pathGroups": [
            {
                "pattern": "react",
                "group": "external",
                "position": "before"
            }
        ],
    }
],

期望实现的导入顺序:

  1. React相关导入
  2. 第三方包导入
  3. 绝对路径导入
  4. 相对路径导入
  5. 样式文件导入

目标示例:

// import anything react related
import React, { useRef, useState } from "react";

// import third party packages
import _ from "lodash";

// import absolute
import { Component } from "shared/Component";

// import relative
import { utilsFunction } from "./utils";

// import styling
import css from "./Component.module.css";

解决方案

调整import/order配置,通过扩展路径分组、补充规则参数来匹配预期顺序:

"import/order": [
    "error",
    {
        "groups": ["builtin", "external", "internal", "sibling", "index"],
        "pathGroups": [
            // 匹配React核心及相关包,放在最前
            {
                "pattern": "react",
                "group": "external",
                "position": "before"
            },
            {
                "pattern": "react/**",
                "group": "external",
                "position": "before"
            },
            // 匹配所有样式文件,放在最后
            {
                "pattern": "**/*.css",
                "group": "index",
                "position": "after"
            },
            {
                "pattern": "**/*.module.css",
                "group": "index",
                "position": "after"
            }
        ],
        "pathGroupsExcludedImportTypes": ["builtin"],
        "newlines-between": "always",
        "alphabetize": {
            "order": "asc",
            "caseInsensitive": true
        }
    }
]

配置细节说明

  • React相关导入:通过react和react/**的路径匹配,将所有React相关包锁定在external组的最前端
  • 第三方包:由默认的external组处理,自然排在React相关导入之后
  • 绝对路径导入:internal组负责匹配项目内部的绝对路径(需确保你的ESLint导入解析器已配置识别shared/这类自定义路径)
  • 相对路径导入:sibling组处理同级或上级的相对路径导入,排在绝对路径之后
  • 样式文件:通过**/*.css和**/*.module.css匹配所有样式文件,归入index组并放在最后
  • newlines-between:设置为always强制不同组之间添加空行,和目标示例格式一致
  • alphabetize:开启组内按字母升序排序,保持导入列表整洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:50:24