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

如何配置ESLint使@绝对导入生效且不影响第三方包导入

解决@绝对导入与第三方包导入共存的ESLint配置问题

1. 先配置项目路径别名(Next.js 基础要求)

不管是TypeScript还是JavaScript项目,先在根目录的tsconfig.json或jsconfig.json里配置路径别名,这是Next.js识别@导入的核心基础:

{
  "compilerOptions": {
    "baseUrl": ".", // 以项目根目录为基准路径
    "paths": {
      "@/*": ["./*"] // @/xxx 对应根目录下的xxx文件,若源码在src文件夹下,改为["./src/*"]即可
    }
  }
}

2. 安装必要的ESLint依赖

安装eslint-plugin-import和eslint-import-resolver-typescript,前者提供导入相关规则支持,后者让ESLint自动读取tsconfig的路径配置:

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

3. 修改ESLint配置文件

调整.eslintrc.json,启用插件并配置正确的解析器,同时保留你原本的导入排序、空行规则:

{
  "extends": [
    "next/core-web-vitals",
    "plugin:xstate/recommended",
    "plugin:prettier/recommended",
    "plugin:import/recommended",
    "plugin:import/typescript" // TypeScript项目需加这一项,JS项目可移除
  ],
  "plugins": ["import"],
  "settings": {
    "import/resolver": {
      "typescript": {
        "project": "./tsconfig.json" // 自动读取tsconfig里的paths配置,无需手动写映射
      }
    },
    "import/internal-regex": "^@/" // 指定@开头的导入归为internal组,适配你的导入排序规则
  },
  "rules": {
    "import/order": [
      "error",
      {
        "groups": [
          ["builtin", "external"],
          "internal",
          ["parent", "sibling", "index"]
        ],
        "newlines-between": "always"
      }
    ],
    "padding-line-between-statements": [
      "error",
      {
        "blankLine": "always",
        "prev": "*",
        "next": [
          "export",
          "cjs-export",
          "function",
          "class",
          "multiline-expression"
        ]
      }
    ]
  }
}

关键说明

  • 用eslint-import-resolver-typescript替代之前的alias解析器,它会自动同步tsconfig的路径配置,既保证@导入正常识别,也不会干扰zod这类第三方包的导入识别。
  • import/internal-regex明确@开头的导入属于internal组,和你原本的导入排序规则匹配,确保排序逻辑不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:42:34