Express项目的ESLint配置最佳实践

解读

面试官问“Express 项目的 ESLint 配置最佳实践”,并不是想听你把 .esslintrc 文件念一遍,而是考察三件事:

  1. 你是否理解 Node 服务端代码与前端代码在运行环境、全局变量、模块体系上的差异;
  2. 你是否能把“代码质量”拆成“语法正确、风格统一、潜在 Bug 提前暴露”三层目标,并用 ESLint 的规则、插件、共享配置逐层落地;
  3. 你是否能把 ESLint 无缝嵌入到国内真实的研发流程里:VS Code 实时反馈、Git Hooks 拦截、GitLab-CI 卡点、npm script 统一命令,并兼顾团队二次定制与性能。

一句话:要你给出“能直接拷贝到现网 Express 仓库、跑在国产电脑、过得了老板 Code Review、撑得住 2 万行业务代码”的实战方案。

知识点

  1. 运行环境区分:Node 16/18/20 的 ECMA 版本、CommonJS vs ESM、全局变量(__dirname、process)。
  2. 插件生态:
    • @eslint/js 提供官方推荐规则集;
    • eslint-config-airbnb-base 或 eslint-config-standard 做风格层;
    • eslint-plugin-node 或 eslint-plugin-n 做 Node 专属规则(如禁止 fs.readFileSync 拼路径);
    • eslint-plugin-security 做注入漏洞提示;
    • @typescript-eslint/* 如果项目用 TypeScript。
  3. 配置层级:.eslintrc.js → package.json 的 eslintConfig → CLI 参数,优先级与合并策略。
  4. 解析器选型:默认 Espree 仅支持 Stage 4 语法;TypeScript 项目必须切 @typescript-eslint/parser;若用 ESM 最新语法,需把 ecmaVersion 拉到 latest。
  5. 全局变量注入:Express 常见 req, res, next 在 middleware 里被反复解构,需配置 globals 防止 no-undef 误报。
  6. 性能优化:
    • eslint --cache 把缓存写 .eslintcache,CI 里挂载到 ~/eslint-cache;
    • 用 lint-staged 仅校验 git diff 文件,平均耗时从 30s 降到 3s;
    • 大仓库开 TIMING=1 找慢规则,把重型规则(如 import/no-cycle)降级到 warn 或仅在 nightly 跑。
  7. 国产研发链落地:
    • VS Code 插件市场下载 dbaeumer.vscode-eslint,设置 eslint.validate: ["javascript", "typescript"];
    • husky + lint-staged 在 pre-commit 钩子强制修复可自动修正的格式错误;
    • GitLab-CI 里用 eslint . --max-warnings 0 做 Merge Request 卡点,失败返回非 0;
    • npm script 统一入口:"lint": "eslint . --cache --ext .js,.ts","lint:fix": "npm run lint -- --fix",防止各开发机命令不一致。
  8. 渐进升级策略:老项目存量 3 万条错误,用 eslint-interactive 或 suppress-eslint-errors 批量加 eslint-disable-next-line 注释,后续迭代逐步清零,避免一次性爆炸式改动。

答案

下面给出一份“可直接落地到国内 Express 生产仓库”的最小最佳实践,兼顾 JavaScript 与 TypeScript 双栈。拷贝后 npm i 即可运行。

  1. 安装依赖
npm i -D eslint @eslint/js eslint-config-airbnb-base eslint-plugin-node eslint-plugin-security eslint-plugin-import @typescript-eslint/parser @typescript-eslint/eslint-plugin typescript
  1. 配置文件 .eslintrc.js(CommonJS 写法,兼容 Node 14+)
module.exports = {
  root: true,
  // 1) 运行环境
  env: {
    node: true,
    es2023: true,
  },
  // 2) 解析器:TypeScript 项目用 ts 解析器,纯 JS 可删
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    project: './tsconfig.json', // 若用 TS 必须指向真实 tsconfig
  },
  // 3) 继承顺序:官方推荐 → Node 专属 → 安全 → 风格
  extends: [
    '@eslint/js/recommended',
    'plugin:node/recommended',
    'plugin:security/recommended',
    'airbnb-base',
  ],
  plugins: ['@typescript-eslint'],
  rules: {
    // 4) 关闭与 Node 冲突的风格规则
    'node/no-unsupported-features/es-syntax': 'off', // 我们靠 ecmaVersion 控制
    'node/no-missing-import': 'off', // 让 import 插件处理
    'node/shebang': 'off', // Express 入口一般无 shebang
    'no-console': 'off', // 服务端允许 console
    'import/extensions': ['error', 'ignorePackages', { js: 'never', ts: 'never' }],
    // 5) 安全加固
    'security/detect-object-injection': 'warn',
    'security/detect-eval-with-expression': 'error',
    // 6) 性能
    'import/no-cycle': 'warn', // MR 卡点可暂时容忍
  },
  // 7) 全局注入,防止误报
  globals: {
    __dirname: 'readonly',
    __filename: 'readonly',
    global: 'readonly',
  },
  // 8) 覆盖测试目录
  overrides: [
    {
      files: ['test/**/*', '*.test.js', '*.spec.ts'],
      env: { mocha: true },
      rules: { 'node/no-unpublished-require': 'off' },
    },
  ],
};
  1. 配套脚本 package.json
"scripts": {
  "lint": "eslint . --cache --ext .js,.ts",
  "lint:fix": "npm run lint -- --fix",
  "prepare": "husky install"
}
  1. Git Hooks(husky v8 写法)
    .husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx lint-staged

package.json 追加

"lint-staged": {
  "*.{js,ts}": "eslint --cache --fix"
}
  1. GitLab-CI 卡点 .gitlab-ci.yml
lint:
  stage: test
  image: node:18-alpine
  cache:
    key: ${CI_COMMIT_REF_SLUG}
    paths:
      - .eslintcache/
  script:
    - npm ci
    - npm run lint
  only:
    - merge_requests
  1. VS Code 统一行为
    .vscode/settings.json
{
  "eslint.validate": ["javascript", "typescript"],
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}

至此,一个“开箱即用、可维护、可扩展、跑得动 2 万行 Express 业务代码”的 ESLint 最佳实践就搭建完成。后续若切 ESM、上 Monorepo、换 Biome,只需改解析器与缓存路径即可平滑迁移。

拓展思考

  1. 国内很多 Express 项目仍跑在 Node 14,甚至 12,如何在不升级运行时的前提下,把 ESLint 的 ecmaVersion 拉到 2023 而又不触发 node/no-unsupported-features?
    答:用 Babel 转译或写 eslint-plugin-n 的 version: '14' 指定,规则会自动读取 Node 版本白名单;同时把 parserOptions.ecmaVersion 设 2023 仅影响静态分析,不会把语法带到生产。

  2. 微服务仓库爆炸到 50 个子服务,如何做到“一处配置,处处生效”?
    答:把上述 .eslintrc.js 抽成 @your-company/eslint-config-express 私有包,发布到自建 Verdaccio;各服务 extends: '@your-company/eslint-config-express',再配合 rush 或 nx 做云端缓存,lint 时间从 5 分钟降到 30 秒。

  3. 如果团队想渐进迁移到 TypeScript,但老 JS 文件不动,如何共存?
    答:在 overrides 里对 *.ts 追加 @typescript-eslint/recommended 规则集,并开启 parserOptions.project;对 *.js 关闭 no-undef 等严格规则,保持原有风格。这样新旧代码各走各的解析器,互不干扰。

  4. 当 ESLint 被诟病“慢”时,如何量化并说服老板不砍掉?
    答:在 CI 里加 TIMING=1 eslint . > eslint-timing.txt,把最耗时的 10 条规则贴出来,评估是否可降级;再对比“无 lint”导致的线上故障平均修复时间(MTTR),用数据证明“3 秒 lint 换 3 小时 hotfix”是值得的。