ESM模块的ESLint配置要点
解读
国内前端项目已普遍转向“纯 ESM”方案(Vite、原生 Node ESM、公司级 Monorepo 统一 ESM 规范)。面试官问“ESM 模块的 ESLint 配置要点”,并不是让你背 .eslintrc.js 的语法,而是考察三件事:
- 你是否理解 ESM 与 CommonJS 在语法、解析路径、文件扩展名上的差异;
- 你是否能把这些差异映射到 ESLint 的规则与解析器配置里,保证“既跑起来又跑得快”;
- 你是否能在团队工程化链路(VS Code、Git Hooks、CI)里落地,并给出可复制的“踩坑清单”。
一句话:让 ESLint 在 ESM 环境下“零误报、零漏报、秒级启动”,同时不给后人留坑。
知识点
-
解析器层面
- parser:
@typescript-eslint/parser或最新espree必须显式ecmaVersion:2022+且sourceType:'module'; - parserOptions.project 指向
tsconfig.eslint.json,避免把编译产物、声明文件拉进来拖慢速度; - 若用 Vitest/Storybook 等子项目,要在
parserOptions.tsconfigRootDir里指到仓库根,防止找不到tsconfig.json而回退到松散模式。
- parser:
-
规则层面
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,防止解析错误。
-
插件与共享配置
- 国内团队普遍直接 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误报。
- 国内团队普遍直接 extends
-
性能与缓存
- 开启
ESLint flat config(eslint.config.js)后,用languageOptions.parserOptions.projectService:true可复用 TypeScript 语言服务实例,CI 提速 40% 以上; - 国内 GitLab CI 并发数高,加
TIMING=1 eslint .观察慢规则,把import/namespace这种 O(n²) 规则在 MR 阶段关掉,主干分支再全开。
- 开启
-
工程化集成
- VS Code 插件市场下载量最高的
dbaeumer.vscode-eslint2.4+ 才支持 flat config,老项目要提示成员升级; - husky + lint-staged 场景下,给
lint-staged传--cache --cache-location node_modules/.cache/eslint,避免每次全量扫描; - 若用 pnpm Monorepo,把
ESLINT_USE_FLAT_CONFIG=true写进.npmrc,否则 CLI 会误判配置文件位置。
- VS Code 插件市场下载量最高的
答案
“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”。
拓展思考
-
双模包(dual package)场景下,exports 字段同时暴露
import与require路径,ESLint 如何分别校验?
思路:在eslint.config.js里写两份 overrides,一份files: ['src/**/*.js']按 ESM 规则,一份files: ['lib/cjs/**/*.js']关闭import/extensions,并改用@eslint/eslintrc的CommonJS环境。 -
当项目升级到 TypeScript 5.x 的
moduleResolution:bundler,路径别名全部写成#utils这种子路径,ESLint 会大面积import/no-unresolved,如何零成本解决?
思路:把eslint-import-resolver-typescript升到 3.6+,它已支持读取tsconfig的paths与subpathImports,无需再写eslint-import-resolver-alias。 -
国内有团队把 ESLint 规则下沉到 Maven 仓库(后端混合前端),如何让 Gradle 构建也享受 ESLint 缓存?
思路:用gradle-node-plugin把node_modules与.cache/eslint挂到 Gradle 的buildCache目录,实现跨机器共享,减少 50% 流水线时间。