如何配置ESLint支持CommonJS模块系统
解读
国内前端项目仍有大量存量代码跑在 Node 12-16 的 CommonJS 环境(Egg、Webpack4、BFF 层等)。面试官问“怎么让 ESLint 认识 CommonJS”并不是考你会不会装 eslint-plugin-node,而是看你是否能把「语法解析 → 规则集 → 全局变量 → 运行环境」四条线一次说清,并给出可落地的 .eslintrc.js 片段。答不到“env.node=true”或“parserOptions.sourceType=script”都算漏点;如果还能把 overrides 区分 src 和 test,基本就稳了。
知识点
- 解析器层面:默认 espree 把
require/module.exports当语法错,需要把sourceType设成script(非 module)。 - 环境层面:
env.node=true一次性注入require、module、__dirname等 38 个全局变量,避免no-undef误报。 - 规则层面:必须启用
plugin:node/recommended或eslint-plugin-node的no-unsupported-features/es-syntax,把import语句直接报错,堵住“混写”技术债。 - 文件层面:
.eslintrc.js自身就是 CommonJS,要加root:true防止向上递归;若项目里还有 ESM 子目录,用overrides把sourceType切回module。 - 工程层面:CI 里跑
eslint . --max-warnings 0前,先npm i eslint-plugin-node@11锁版本,避免 12+ 仅支持 ESM 的新版插件在 Node 14 机器上挂掉。
答案
-
安装依赖(国内源提速)
npm i -D eslint eslint-plugin-node@11 -
项目根目录新建
.eslintrc.js(CommonJS 写法)module.exports = { root: true, env: { node: true }, // 注入 CommonJS 全局变量 parserOptions: { ecmaVersion: 2022, // 支持可选链、nullish 等新语法 sourceType: 'script' // 关键:按脚本解析,禁止顶层 import/export }, extends: [ 'eslint:recommended', 'plugin:node/recommended' // 内置 no-unsupported-features/es-syntax ], rules: { 'node/no-unpublished-require': 'off' // 若私有包不在 package.json 可关 }, overrides: [ { files: ['src/**/*.mjs'], // 若未来有 ESM 子目录 parserOptions: { sourceType: 'module' } } ] }; -
package.json 脚本
"scripts": { "lint": "eslint . --max-warnings 0 --ext .js,.cjs", "lint:fix": "npm run lint -- --fix" } -
VS Code 用户加本地
.vscode/settings.json{ "eslint.validate": ["javascript", "javascriptreact"], "eslint.codeActionOnSave.mode": "problems" } -
Git Hooks(husky@8 仍兼容 CommonJS)
npx husky add .husky/pre-commit 'npm run lint'
按以上五步,ESLint 即可在纯 CommonJS 项目里零误报、零漏报,同时堵住 ESM 混写风险。
拓展思考
- 渐进迁移:若团队计划半年后切 ESM,可在
.eslintrc.js里把sourceType改成unambiguous,让 ESLint 按文件后缀自动识别,但需配套node --experimental-specifier-resolution=node跑脚本,CI 阶段用eslint-plugin-import的import/no-commonjs规则把新增.js强制写成 ESM,老文件逐步重构。 - Monorepo 场景:在 pnpm workspace 里,子包 A 是 CommonJS、子包 B 是 ESM,根目录
.eslintrc.js只保留root:true与公共规则,各子包再放自己的.eslintrc.cjs覆盖sourceType,配合eslint --cache --cache-location node_modules/.cache/eslint把 10 万行代码检查时间从 90s 降到 12s。 - 性能调优:国内 GitLab CI 机器常给 2C4G,把
eslint .改成eslint $(git diff --name-only origin/main...HEAD | grep -E '\.(js|cjs)$')只检增量文件,能再省 40% 时间;同时把eslint-plugin-node的no-missing-require规则缓存到.eslintcache.json,避免每次都扫node_modules。