如何配置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,基本就稳了。

知识点

  1. 解析器层面:默认 espree 把 require/module.exports 当语法错,需要把 sourceType 设成 script(非 module)。
  2. 环境层面:env.node=true 一次性注入 require、module、__dirname 等 38 个全局变量,避免 no-undef 误报。
  3. 规则层面:必须启用 plugin:node/recommended 或 eslint-plugin-node 的 no-unsupported-features/es-syntax,把 import 语句直接报错,堵住“混写”技术债。
  4. 文件层面:.eslintrc.js 自身就是 CommonJS,要加 root:true 防止向上递归;若项目里还有 ESM 子目录,用 overrides 把 sourceType 切回 module。
  5. 工程层面:CI 里跑 eslint . --max-warnings 0 前,先 npm i eslint-plugin-node@11 锁版本,避免 12+ 仅支持 ESM 的新版插件在 Node 14 机器上挂掉。

答案

  1. 安装依赖(国内源提速)

    npm i -D eslint eslint-plugin-node@11
    
  2. 项目根目录新建 .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' }
        }
      ]
    };
    
  3. package.json 脚本

    "scripts": {
      "lint": "eslint . --max-warnings 0 --ext .js,.cjs",
      "lint:fix": "npm run lint -- --fix"
    }
    
  4. VS Code 用户加本地 .vscode/settings.json

    {
      "eslint.validate": ["javascript", "javascriptreact"],
      "eslint.codeActionOnSave.mode": "problems"
    }
    
  5. Git Hooks(husky@8 仍兼容 CommonJS)

    npx husky add .husky/pre-commit 'npm run lint'
    

按以上五步,ESLint 即可在纯 CommonJS 项目里零误报、零漏报,同时堵住 ESM 混写风险。

拓展思考

  1. 渐进迁移:若团队计划半年后切 ESM,可在 .eslintrc.js 里把 sourceType 改成 unambiguous,让 ESLint 按文件后缀自动识别,但需配套 node --experimental-specifier-resolution=node 跑脚本,CI 阶段用 eslint-plugin-import 的 import/no-commonjs 规则把新增 .js 强制写成 ESM,老文件逐步重构。
  2. 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。
  3. 性能调优:国内 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。