ESM模块的ESLint配置要点

解读

国内前端项目已普遍转向“纯 ESM”方案(Vite、原生 Node ESM、公司级 Monorepo 统一 ESM 规范)。面试官问“ESM 模块的 ESLint 配置要点”,并不是让你背 .eslintrc.js 的语法,而是考察三件事:

  1. 你是否理解 ESM 与 CommonJS 在语法、解析路径、文件扩展名上的差异;
  2. 你是否能把这些差异映射到 ESLint 的规则与解析器配置里,保证“既跑起来又跑得快”;
  3. 你是否能在团队工程化链路(VS Code、Git Hooks、CI)里落地,并给出可复制的“踩坑清单”。

一句话:让 ESLint 在 ESM 环境下“零误报、零漏报、秒级启动”,同时不给后人留坑。

知识点

  1. 解析器层面

    • parser: @typescript-eslint/parser 或最新 espree 必须显式 ecmaVersion:2022+ 且 sourceType:'module';
    • parserOptions.project 指向 tsconfig.eslint.json,避免把编译产物、声明文件拉进来拖慢速度;
    • 若用 Vitest/Storybook 等子项目,要在 parserOptions.tsconfigRootDir 里指到仓库根,防止找不到 tsconfig.json 而回退到松散模式。
  2. 规则层面

    • import/no-unresolved 必须搭配 eslint-import-resolver-typescript,否则 .js 扩展名缺失会误报;
    • import/extensions 强制写 .js,因为 ESM 在浏览器与 Node 原生环境都不允许“裸路径”;
    • node/file-extension-in-import 与 unicorn/prefer-node-protocol 双保险,杜绝 import fs from 'fs' 这种即将在 Node 16+ 被废弃的写法;
    • no-duplicate-imports 关闭,用 import/no-duplicates 代替,后者能识别 import type 与 import 的重复;
    • 若仓库同时存在 .mts/.cts,加 overrides 把 .mts 当 sourceType:'module'、.cts 当 script,防止解析错误。
  3. 插件与共享配置

    • 国内团队普遍直接 extends airbnb-base 或 standard,但这两条 preset 默认 sourceType:'script',要在 overrides 里对 **/*.js,**/*.ts 重新声明 sourceType:'module';
    • 自研共享配置包(@company/eslint-config-base)时,把 env:{node:true} 与 env:{browser:true} 拆成两份,避免把 window 注入 Node 脚本导致 no-undef 误报。
  4. 性能与缓存

    • 开启 ESLint flat config(eslint.config.js)后,用 languageOptions.parserOptions.projectService:true 可复用 TypeScript 语言服务实例,CI 提速 40% 以上;
    • 国内 GitLab CI 并发数高,加 TIMING=1 eslint . 观察慢规则,把 import/namespace 这种 O(n²) 规则在 MR 阶段关掉,主干分支再全开。
  5. 工程化集成

    • VS Code 插件市场下载量最高的 dbaeumer.vscode-eslint 2.4+ 才支持 flat config,老项目要提示成员升级;
    • husky + lint-staged 场景下,给 lint-staged 传 --cache --cache-location node_modules/.cache/eslint,避免每次全量扫描;
    • 若用 pnpm Monorepo,把 ESLINT_USE_FLAT_CONFIG=true 写进 .npmrc,否则 CLI 会误判配置文件位置。

答案

“ESM 模块的 ESLint 配置要点”可以拆成四步,每一步给出可落地的代码片段与踩坑提示,面试官听完就能判断你“真上过线”。

第一步:让解析器认识 ESM

// eslint.config.js (flat config 写法,推荐新工程直接上)
import js from '@eslint/js'
import tsParser from '@typescript-eslint/parser'
import importPlugin from 'eslint-plugin-import'

export default [
  js.configs.recommended,
  {
    files: ['**/*.{js,mjs,ts,mts}'],
    languageOptions: {
      parser: tsParser,
      parserOptions: {
        sourceType: 'module',
        ecmaVersion: 'latest',
        project: './tsconfig.eslint.json',
        tsconfigRootDir: import.meta.dirname
      }
    },
    plugins: { import: importPlugin },
    rules: {
      'import/no-unresolved': 'error',
      'import/extensions': ['error', 'ignorePackages', { js: 'always', ts: 'always' }]
    },
    settings: {
      'import/resolver': {
        typescript: {
          project: './tsconfig.eslint.json'
        }
      }
    }
  }
]

踩坑提示:如果仍用 .eslintrc.js,记得把 module.exports 改成 export default,文件后缀改为 .mjs,否则 Node 会按 CommonJS 加载,导致 __dirname is not defined 报错。

第二步:补全 ESM 专属规则

rules: {
  'node/file-extension-in-import': ['error', 'always'],   // 强制写 .js
  'unicorn/prefer-node-protocol': 'error',                // 强制 node:fs
  'import/no-duplicates': 'error',                        // 替代 no-duplicate-imports
  'no-import-assign': 'error'                             // ESM 禁止对 import 绑定重新赋值
}

第三步:性能优化
CI 脚本示例(GitLab):

eslint:
  stage: lint
  script:
    - TIMING=1 eslint . --cache --cache-strategy content --max-warnings 0
  cache:
    key: $CI_COMMIT_REF_SLUG
    paths:
      - node_modules/.cache/eslint

本地开发:

// package.json
"lint-staged": {
  "*.{js,mjs,ts,mts}": "eslint --cache --fix"
}

第四步:兼容旧 CommonJS 遗留文件

// eslint.config.js 追加 overrides
{
  files: ['scripts/*.cjs'],
  languageOptions: { sourceType: 'script' },
  rules: { 'node/file-extension-in-import': 'off' }
}

一句话总结:把 sourceType:'module' 写死、把 .js 扩展名写全、把 TypeScript 解析器指向最小 tsconfig.eslint.json,再配两条导入专用规则,就能让 ESLint 在 ESM 项目里“一次配置、全队复制、秒级 lint”。

拓展思考

  1. 双模包(dual package)场景下,exports 字段同时暴露 import 与 require 路径,ESLint 如何分别校验?
    思路:在 eslint.config.js 里写两份 overrides,一份 files: ['src/**/*.js'] 按 ESM 规则,一份 files: ['lib/cjs/**/*.js'] 关闭 import/extensions,并改用 @eslint/eslintrc 的 CommonJS 环境。

  2. 当项目升级到 TypeScript 5.x 的 moduleResolution:bundler,路径别名全部写成 #utils 这种子路径,ESLint 会大面积 import/no-unresolved,如何零成本解决?
    思路:把 eslint-import-resolver-typescript 升到 3.6+,它已支持读取 tsconfig 的 paths 与 subpathImports,无需再写 eslint-import-resolver-alias。

  3. 国内有团队把 ESLint 规则下沉到 Maven 仓库(后端混合前端),如何让 Gradle 构建也享受 ESLint 缓存?
    思路:用 gradle-node-plugin 把 node_modules 与 .cache/eslint 挂到 Gradle 的 buildCache 目录,实现跨机器共享,减少 50% 流水线时间。