Lerna管理的Monorepo如何配置ESLint

解读

国内一线/二线前端面试中,Monorepo 已成“标配”基建。面试官抛出此题,核心想验证三点:

  1. 你是否理解 Lerna 只负责“包管理”,而 ESLint 需要“自己搭”;
  2. 能否在“多包”场景下兼顾:
    • 统一规范(一套规则走天下)
    • 差异化定制(某包特殊规则)
    • 性能(不重复 parse)
    • 研发体验(VS Code 秒级反馈、Git Hooks 秒级拦截、CI 秒级卡点)
  3. 是否掌握“渐进落地”路径:老代码如何兼容、新代码如何强制、未来如何平滑升级。

答得太浅(“每个包各自装一份 ESLint”)会被判“不会 scale”;答得太深(“自己写 parser 插件”)会被判“过度设计”。因此,要给出一套“国内团队可落地、可维护、可演进”的完整方案,并提前准备“坑点”问答。

知识点

  1. Monorepo 拓扑:workspace protocol、hoist、no-hoist、phantom dependencies。
  2. ESLint 配置合并优先级:.eslintrc.* < package.json eslintConfig < CLI --config < extends 链。
  3. Flat Config(eslint.config.js)与 Legacy Config 差异,及 2025 年国内迁移节奏。
  4. root eslint.config.js 的 ignores 写法与 .eslintignore 废弃通告。
  5. @eslint/js、typescript-eslint、eslint-plugin-vue / react / node 的共享配置层设计。
  6. lint-staged + simple-git-hooks(或 husky)在 Monorepo 下的路径通配写法。
  7. CI 侧缓存:eslint --cache-location、eslint-cache-key 与 GitHub Actions / GitLab CI / 自建 Jenkins 的 cache 策略。
  8. 老代码基线:eslint-config-prettier、@eslint/migrate-config、eslint --print-config 用于 diff。
  9. 性能调优:eslint --cache-strategy content、并发线程、vite-plugin-eslint(dev 阶段仅 type-check 不 lint)。
  10. 国内私有源(npmmirror、verdaccio)与 workspace 协议冲突时的 lock 文件一致性。

答案

下面给出一套“2025 年国内团队可直接抄作业”的参考实现,兼顾 Flat Config、渐进迁移、性能与体验。

  1. 目录约定
repo/
├─ package.json         // private: true, workspaces: ["packages/*"]
├─ eslint.config.js     // 根配置,导出数组
├─ packages/
│  ├─ foo/
│  │  ├─ src/
│  │  └─ package.json   // 类型: "module"
│  └─ bar/
│     ├─ src/
│     └─ package.json   // 类型: "commonjs"
  1. 根 package.json 只保留一份 ESLint 依赖
"devDependencies": {
  "eslint": "^9.5.0",
  "@eslint/js": "^9.5.0",
  "typescript-eslint": "^8.0.0",
  "eslint-plugin-vue": "^9.27.0",
  "globals": "^15.6.0"
}

Lerna 7 默认用 npm/yarn/pnpm workspace,hoist 后子包无需重复安装,CI 缓存只需一份 node_modules。

  1. 根 eslint.config.js(Flat Config)
import js from '@eslint/js'
import ts from 'typescript-eslint'
import vue from 'eslint-plugin-vue'
import { defineFlatConfig } from 'eslint-define-config'

export default defineFlatConfig([
  // 1) 全局忽略
  {
    ignores: ['**/dist/**', '**/lib/**', '**/.turbo/**', '**/coverage/**']
  },
  // 2) 基础 JS 规则
  js.configs.recommended,
  // 3) TS 通用规则
  ...ts.configs.recommended,
  // 4) Vue3 规则
  ...vue.configs['flat/recommended'],
  // 5) 自定义团队规则
  {
    rules: {
      'no-console': 'warn',
      '@typescript-eslint/no-explicit-any': 'error'
    }
  },
  // 6) 子包 bar 特殊规则
  {
    files: ['packages/bar/**/*.{js,ts}'],
    rules: {
      'no-console': 'off' // bar 包允许 console
    }
  }
])

关键点:

  • 用数组顺序显式表达“合并”过程,避免 extends 黑盒。
  • 子包差异化通过 files 字段精准匹配,无需在每个包再放 .eslintrc。
  • ignores 放在最前,减少无意义 parse。
  1. VS Code 秒级反馈 .vscode/settings.json
{
  "eslint.experimental.useFlatConfig": true,
  "eslint.workingDirectories": ["./packages/foo", "./packages/bar"],
  "eslint.options": { "cache": true, "cacheLocation": "node_modules/.cache/eslint" }
}

缓存目录放在 node_modules 下,可被 CI 整体缓存。

  1. Git Hooks(simple-git-hooks,零依赖) 根 package.json
"simple-git-hooks": {
  "pre-commit": "lint-staged"
},
"lint-staged": {
  "*.{js,ts,vue}": ["eslint --cache --fix", "git add"]
}

lint-staged 会自动从 Git 根目录开始匹配,无需 cd 到子包。

  1. CI 卡点(GitHub Actions 示例)
- name: ESLint
  run: |
    npm run lint -- --cache --cache-location node_modules/.cache/eslint
  env:
    ESLINT_CACHE_KEY: ${{ runner.os }}-eslint-${{ hashFiles('eslint.config.js', 'packages/**/src/**') }}
- uses: actions/cache@v4
  with:
    path: node_modules/.cache/eslint
    key: ${{ env.ESLINT_CACHE_KEY }}

缓存 key 包含配置文件与源码哈希,保证“规则变”或“源码变”即失效。

  1. 老代码基线处理
  • 先跑 npm run lint -- --max-warnings 0 2>&1 | tee lint.log 统计当前错误数。
  • 在 eslint.config.js 顶部加
{
  files: ['packages/legacy/**/*'],
  rules: { 'no-console': 'off', '@typescript-eslint/no-explicit-any': 'warn' }
}
  • 后续用 eslint-nibble 或 eslint-interactive 逐步修复,降低 warning 阈值,实现“增量干净”。
  1. 性能兜底
  • 开 --cache-strategy content(eslint 9 默认),避免 mtime 误伤。
  • 大仓库配合 TIMING=1 eslint ... 输出每规则耗时,针对性关闭慢规则。
  • 若包间技术栈差异极大(如 React + Vue + Node),可拆多条 export 数组,用 files 精确隔离,防止插件重复加载。
  1. 发布与版本 Lerna 发布时无需做任何 ESLint 相关改动,因为 ESLint 只是静态工具,不进入产物。若子包需要把 lint 脚本暴露给外部消费者,可在 package.json 里加
"scripts": {
  "lint": "eslint src --cache"
}

但注意:依赖仍指向 root,避免重复安装。

拓展思考

  1. 如果团队 2025 年仍需兼容 ESLint 8(Flat Config 未全量迁移),如何“双轨”运行?

    • 根目录同时保留 .eslintrc.js 与 eslint.config.js,在 CI 里通过 ESLINT_USE_FLAT_CONFIG=true 开关做 A/B。
    • 用 eslint --config 显式指定,逐步把子包 CI 任务迁移到 Flat Config,最后删除老配置。
  2. 当 Monorepo 扩大到 200+ 包、且使用 pnpm 时,node_modules 结构变成 symlink + hardlink,eslint --cache 是否会误伤?

    • pnpm 与 eslint 9 已修复 inode 复用问题,但建议 cache-strategy=content + cache-location=.eslintcache 放在项目外(如 /tmp),避免 Docker 层缓存失效。
  3. 如何做到“子包自定义插件”但又不安装到 root?

    • 在子包单独装 eslint-plugin-xxx,然后在根 eslint.config.js 用 createRequire(import.meta.url) 动态 require 子包路径,通过 files 限定作用域。Lerna 7 的 hoist=false 可仅对该插件关闭提升,兼顾隔离与复用。
  4. 未来 ESLint 10 计划移除 env 字段,完全用 globals 显式导入,如何提前适配?

    • 在 Flat Config 里写 languageOptions: { globals: {...browser, ...node} },避免升级时突发报错。
  5. 国内私有源同步延迟,导致 @typescript-eslint/eslint-plugin 与 typescript 版本不匹配,如何在 CI 提前拦截?

    • 在 package.json 的 overrides 字段(npm 8+)或 pnpm.overrides 里锁死 typescript 版本,并在 CI 加一步 npx tsc --version 与 npm ls typescript 双重校验,防止“幽灵依赖”带来的 parse 错误。

把上述方案与思考准备好,面试时先给“最小可用”骨架,再主动抛出“老代码、性能、双轨、未来升级”话题,基本能拿到“代码工程化深度”高分。