Ghost monorepo 共享 ESLint 配置体系深度解析:nodeLibConfig 与 reactAppConfig 工程化实践
Ghost 将 ESLint 规则抽成了两个内部配置包(@internal/cfg-eslint 与 @internal/cfg-eslint-react),分别面向 Node.js 库与 React 应用提供"同步工厂函数",从而让几十个工作区共享同一套扁平配置(flat config)。本文基于 configs/eslint/README.md 展开,结合 configs/eslint/index.mjs、configs/eslint-react/index.mjs 及其真实消费者配置,讲解这些工厂的全部选项、规则原子(rule atoms)、legacy* 迁移例外、插件依赖纪律与验证流程。读完你既能直接给新工作区接入共享配置,也能理解 Ghost 这套"错误即 error、禁用写 off、绝不用 warn"的规则哲学背后的工程权衡。
为什么 monorepo 需要共享 ESLint 工厂
Ghost 是一个由 Nx + pnpm workspace 管理的多包仓库:前端应用位于 apps/,Node 库分布在 koenig/、packages/,此外还有 ghost/core、apps/ember-admin、apps/admin-toolbar 等独立代码库。仓库采用 ESLint flat config,且每个工作区都有自己的 eslint.config.{js,mjs};根目录 eslint.config.mjs 直接 export default []——按该文件的注释,仓库根没有可 lint 的代码,保留空配置只是为了给从根目录调起的 eslint 一个扁平配置入口,避免散落的根级文件"悄悄继承"某个工作区的规则。
在这种结构下,如果每个包各自手写配置,规则会迅速漂移,迁移成本也很高。因此 Ghost 把规则沉淀为两个内部包:
@internal/cfg-eslint(位于 configs/eslint):提供共享规则原子(atomic rule objects)与面向 Node.js 库的nodeLibConfig();@internal/cfg-eslint-react(位于 configs/eslint-react):提供面向 React 应用的reactAppConfig()。
从 configs/eslint/index.mjs 的头注释可以看到一个关键设计意图:React 插件栈被刻意拆到单独包中。@internal/cfg-eslint 只静态引入 Node 库真正需要的插件(并声明为自己的依赖),因此 nodeLibConfig 可以是同步函数;而 React 插件集只在 @internal/cfg-eslint-react 中加载,Node 库永远不会被迫加载 eslint-plugin-react 等重型插件。
两个工厂都是同步的,其选项全部通过 index.mjs 里的 JSDoc + 示例文档化。由于它们采用"白名单校验",传入未知选项会直接抛错,保证配置错误在 lint 运行前就被发现。
包依赖结构:一个"原子库",一个"React 工厂"
| 包 | 位置 | 职责 |
|---|---|---|
@internal/cfg-eslint | configs/eslint/package.json | 规则原子 + nodeLibConfig() + localFilenamesPlugin 等导出 |
@internal/cfg-eslint-react | configs/eslint-react/package.json | reactAppConfig(),构建在 @internal/cfg-eslint 之上 |
从 configs/eslint/package.json 可见基包只声明了 @eslint/js、eslint-plugin-ghost、globals、typescript-eslint 四个运行时依赖,全部走根 catalog 版本;configs/eslint-react/package.json 则额外声明了 eslint-plugin-react、eslint-plugin-react-hooks、eslint-plugin-react-refresh、eslint-plugin-tailwindcss、eslint-plugin-storybook、eslint-plugin-i18next 等,并以 "@internal/cfg-eslint": "workspace:*" 依赖基包。工厂把这些插件作为对象注入 config block(如 reactFlat.plugins、basePlugins),这正是消费方只需依赖配置包、无需逐一声明插件的原因。
快速接入:声明依赖并"按名消费"工厂
原文档给出的最小接入方式如下:把相关包加为 workspace:* 开发依赖,再 import 工厂并按名调用。
import {reactAppConfig} from '@internal/cfg-eslint-react';
export default reactAppConfig({
tailwindCssPath: `${import.meta.dirname}/../admin/src/index.css`,
shadeRestricted: true
});
真实仓库中,apps/admin/eslint.config.js 就是最典型的消费者——它同时引用了 reactAppConfig 与基包导出的 shadeLayeredImportsRule:
import { reactAppConfig } from '@internal/cfg-eslint-react';
import { shadeLayeredImportsRule } from '@internal/cfg-eslint';
export default tseslint.config(
...reactAppConfig({
tailwindCssPath: `${import.meta.dirname}/src/index.css`,
shadeRestricted: true,
ignores: ['dist/**/*', 'test-utils/acceptance/public/**/*'],
srcGlobs: ['**/*.{ts,tsx}'],
testGlobs: false,
extraSrcRules: {
'react-refresh/only-export-components': [
'error',
{ allowConstantExport: true, extraHOCs: ['withErrorBoundary'] },
],
},
}),
// ...
);
这段真实代码还揭示了接入共享配置的常见姿势:工厂只负责通用规则,工作区自己在后面追加"类型感知"或"边界约束"的额外 block。由于 reactAppConfig 本身是 type-unaware 的,admin 在其后叠加了 tseslint.configs.recommendedTypeCheckedOnly(通过 projectService: true 提供类型信息),并用 no-restricted-imports 禁止绕过框架层直接 import react-router、裸 fetch 等。这说明"工厂 + 追加 block"是比把每个工作区特殊规则塞进工厂更优的演进路径。
nodeLibConfig:Node.js 库的标准配置工厂
核心选项速查
依据 configs/eslint/index.mjs 的 JSDoc,nodeLibConfig 支持以下选项(未列出的键会抛 nodeLibConfig: unknown options ...):
| 选项 | 类型 / 默认值 | 含义 |
|---|---|---|
typescript | boolean,默认 true | true 时继承 tseslint.configs.recommended 并应用 tsUnusedVarsRule;false 时为纯 JS + jsUnusedVarsRule |
commonjs | boolean,默认 false | true 时 sourceType 变为 'commonjs' 而非 'module' |
legacyLocalFilenames | boolean,默认 false | LEGACY 逃生舱(仅 packages/i18n 使用):注册 localFilenamesPlugin 并关闭 ghost/filenames/match-regex,改用工作区本地变体 |
srcGlobs | string[] | 覆盖 src glob。TS 默认 ['src/**/*.ts'],JS 默认 ['*.js', 'lib/**/*.js'] |
testGlobs | string[] / false | 覆盖 test glob。TS 默认 ['test/**/*.ts'],JS 默认 ['test/**/*.js'];传 false 跳过 test block |
ignores | string[],默认 ['build/**/*'] | 替换默认忽略 glob |
extraSrcRules | object | 工作区级 src 规则覆盖 |
extraTestRules | object | 工作区级 test 规则覆盖 |
extraBlocks | Linter.Config[] | 追加额外 config block;每个 block 应自带 files: glob(flat config 中无 files: 的 block 会作用于所有文件,通常不是期望行为) |
生成的 config 结构(configs/eslint/index.mjs)由若干 block 组成:全局 ignores、应用 strictLinterOptions 的全文件 block、src block、可选的 extraBlocks、test block。语言选项统一为 ecmaVersion: 2022,src 使用 globals.node,test block 额外加入 globals.mocha、globals.vitest 以及 vi、beforeAll、should、sinon 等只读全局。TS 分支会关闭 no-undef(交给编译器处理)并在 test 里应用 mochaRulesOff(ghostPlugin),避免 Vitest 写法触发 mocha 风格的误报。
最简与"重型"两种真实用法
最小用法就是库包的标准样板。例如 packages/parse-email-address/eslint.config.mjs 全文仅三行:
import { nodeLibConfig } from '@internal/cfg-eslint';
export default nodeLibConfig();
而需要迁移豁免、额外规则与自定义 block 的工作区则充分使用各选项。以 JS-only 且为 CommonJS 的 packages/i18n/eslint.config.mjs 为例,它综合演示了 legacyLocalFilenames、extraSrcRules、extraTestRules、extraBlocks 的配合:
import { nodeLibConfig, noGhostIgnitionRequireRule } from '@internal/cfg-eslint';
export default [
{ ignores: ['lib/registry/**', 'build/**'] },
...nodeLibConfig({
typescript: false,
commonjs: true,
legacyLocalFilenames: true,
srcGlobs: ['*.js', 'lib/**/*.js'],
testGlobs: ['test/**/*.js'],
extraSrcRules: {
...noGhostIgnitionRequireRule,
'local-filenames/match-regex': ['error', '^[a-z0-9.-]+$', false],
},
extraTestRules: {
...noGhostIgnitionRequireRule,
'ghost/ghost-custom/node-assert-strict': 'error',
},
extraBlocks: [
// 入口是公开面,限制行数
{
files: ['lib/**/index.js', 'index.js'],
rules: { 'max-lines': ['error', { skipBlankLines: true, skipComments: true, max: 50 }] },
},
],
}),
];
reactAppConfig:前端应用配置工厂
完整选项表
依据 configs/eslint-react/index.mjs 的 JSDoc,其选项如下(同样有白名单校验与若干互斥校验):
| 选项 | 类型 / 默认值 | 含义 |
|---|---|---|
typescript | boolean,默认 true | false 时为纯 JS 应用(LEGACY,仅 sodo-search、announcement-bar 使用,计划迁移 TS) |
reactRefresh | boolean,默认 true | false 时跳过 eslint-plugin-react-refresh。UMD 打包应用(comments-ui、signup-form、portal、sodo-search、announcement-bar 均为 false)与纯 JS 应用需要关闭——react-refresh 是 Vite HMR 规则,没有 Vite 运行时就没有意义 |
i18next | boolean,默认 false | true 时应用 eslint-plugin-i18next 的 flat/recommended |
storybook | 'plugin' 或 null | 'plugin' 时应用 eslint-plugin-storybook 全量规则集并对 *.stories.* / *.story.* 追加 hierarchy-separator、no-redundant-story-name、prefer-pascal-case 等规则(shade 使用) |
tailwindCssPath | string | Tailwind v4 CSS 配置的绝对路径;缺省则不启用 Tailwind。与 legacyTailwindV3ConfigPath 同时传入会抛错 |
legacyTailwindV3ConfigPath | string | LEGACY 逃生舱:Tailwind v3 JS/CJS 配置绝对路径,comments-ui、signup-form 迁移到 v4 前使用 |
shadeRestricted | boolean,默认 false | true 时禁止 barrel 导入 @tryghost/shade,强制走分层子路径(components/primitives/patterns/utils/app/tokens) |
sortImports | boolean,默认 false | true 时应用 ghost/sort-imports-es6-autofix/sort-imports-es6 |
legacyJsTsSplit | boolean,默认 false | LEGACY(仅 portal):JS/TS 混编迁移期生成两个 src block。要求 typescript: true 且不能与 srcGlobs/testGlobs 同用 |
tsconfigRootDir | string | 类型感知 lint block 定位 tsconfig.json 的工作区目录;仅 legacyJsTsSplit: true 时生效,默认 process.cwd()(配合 pnpm --filter ... exec eslint 从工作区调用可正常工作) |
ignores | string[],默认 ['dist/**/*'] | 忽略 glob(传入数组会整体替换默认值) |
srcGlobs | string[] | TS 默认 ['src/**/*.{js,ts,cjs,tsx}'],JS 默认 ['src/**/*.{js,jsx}'] |
testGlobs | string[] / false | 默认镜像 srcGlobs 到 test/;false 跳过 test block(UMD 应用可用 srcGlobs 合并 src+test) |
extraSrcRules / extraTestRules | object | 工作区级规则覆盖(优先级最高) |
工厂内部还做了多组防御性校验(configs/eslint-react/index.mjs):
tailwindCssPath与legacyTailwindV3ConfigPath同时传入 → 抛错;legacyJsTsSplit需要typescript: true,否则抛错;legacyJsTsSplit与srcGlobs/testGlobs同时传入 → 抛错(split 分支硬编码按扩展名分组,传 glob 会被静默丢弃);shadeRestricted与extraSrcRules['no-restricted-imports']同时出现 → 抛错,因为展开时后者会覆盖前者的 shade 限制(而该限制带有安全含义),需要工作区自行合并。
规则分层:src 与 test 双区 + 插件栈
从实现看(configs/eslint-react/index.mjs),TS React 应用的 src block 按以下顺序叠加规则层:js.configs.recommended.rules → reactFlat.rules →(可选 i18next)→ reactHooksPlugin.configs.recommended.rules → tsReactAppRules → viteOnlyExtras →(可选 shade/sortImports/tailwind 规则)→ extraSrcRules。
关键插件与设置:
react: { version: 'detect' },Tailwind v4 通过tailwindcss: { cssConfigPath }settings 方式解析(v4 插件为 settings-based);legacy v3 应用则必须从应用目录 require 自己的eslint-plugin-tailwindcss——因为根 catalog 的 4.x 插件规则不接受 v3 风格的{config}每规则选项,硬套会触发 schema 校验失败(configs/eslint-react/index.mjs 的实现注释对此解释得很清楚);- test block 与 src block 使用同一组插件注册——扁平配置中若规则引用未注册的插件会直接报错,所以 spread 出来的
tsReactAppRules/jsReactAppRules所依赖的插件必须在同一 block 内声明(configs/eslint-react/index.mjs); mochaRulesOff同样应用到 React 测试 block,规避 Vitest 写法触发 mocha 误报。
一个值得注意的细节是 Tailwind 双轨并存的代价记录在 pnpm-workspace.yaml:catalog tailwind3 固定了 tailwindcss: 3.4.19 与 eslint-plugin-tailwindcss: 3.18.3。legacy v3 应用(comments-ui、signup-form)通过 catalog:tailwind3 声明该插件,而 v4 应用走主 catalog,两者互不干扰。之所以迟迟没有合并,是因为 v3→v4 涉及主题 token 重写、类名重写与 CDN 回归测试(耗时多天且缺负责人),属于"被记录在案的技术债"而非新工作的默认值——这与 legacy* 参数的设计意图完全一致。
规则哲学:error 或 off,绝不用 warn
README 明确要求:工厂消费者只用 error 或 off,不用 warn。源码对此给出了最直白的理由(configs/eslint/index.mjs):
Warnings get ignored by humans and agents and just pollute lint output.
即 warn 既会被人类忽略、也会被 Agent 忽略,只会污染 lint 输出。因此所有规则原子的取值只有两种:
'error':必须修复;'off':显式关闭。凡是off的规则基本都带内联 TODO 注释并记录违规数量,让"重新开启"成为范围清晰的清理 PR(cleanup PR)。
例如在 configs/eslint/index.mjs 的 tsReactAppRules 中可以看到这类被标记的债务:
'@typescript-eslint/no-explicit-any': 'error', // 真类型安全回归用 error
'@typescript-eslint/no-non-null-assertion': 'off', // TODO: 97 violations across 8 workspaces
'@typescript-eslint/no-empty-function': 'off', // TODO: 121 violations across 9 TS React workspaces
react-hooks/exhaustive-deps 同理:它是真实 bug 捕获器(漏写 useEffect/useMemo 依赖),但仓库当前有约 46 处历史违规,插件默认值是 'warn'(违反 Ghost 禁令),于是显式置为 'off' 并等待逐调用点清理后翻转为 'error'(configs/eslint-react/index.mjs)。
另一个值得注意的细节是 jsUnusedVarsRule 对 ESLint 9 行为变化的回填(configs/eslint/index.mjs):ESLint 9 把 no-unused-vars 对 caughtErrors 的默认值从 'none' 翻转为 'all',Ghost 显式配置 caughtErrors: 'none' 恢复旧行为,让未使用的 catch 绑定继续被容忍。这类注释让后人修改时能明白"为什么是这个值"。
规则原子库:被反复组合的最小单元
@internal/cfg-eslint 导出的规则原子既被两个工厂组合,也被不适合工厂的独立工作区直接 import。以下是核心原子的速览(出处见 configs/eslint/index.mjs):
| 原子 | 内容 |
|---|---|
correctnessRules(L24-L38) | curly、camelcase(properties: 'never')、dot-notation、eqeqeq(always)、no-plusplus(允许 for 循环后置 ++)、no-eval、no-useless-call、no-console、no-shadow、array-callback-return、no-constructor-return、no-promise-executor-return,以及 ghost/filenames/match-regex(文件名校验 ^[a-z0-9.-]+$) |
tsUnusedVarsRule / jsUnusedVarsRule(L40-L56) | TS 用 @typescript-eslint/no-unused-vars(args: 'after-used'、argsIgnorePattern: '^_');JS 用 no-unused-vars 并恢复 caughtErrors: 'none' |
nodeLibRules(L177-L184) | 在 correctnessRules 上加 no-var、one-var: never 及三条 ghost-custom 规则(no-native-error、ghost-error-usage、ghost-tpl-usage) |
noTopLevelAwaitRule(L192-L206) | 用 no-restricted-syntax 禁止源码中的顶层 await/for-await-of:它会让 ESM 模块图异步化,破坏通过 require() 加载 ESM 包(require(esm))的 CommonJS 消费者如 ghost/core,抛出 ERR_REQUIRE_ASYNC_MODULE。函数内的 await 不受影响,且只作用于 src block(测试文件不会被 require) |
noGhostIgnitionRequireRule(L208-L219) | 禁止 require('ghost-ignition'),引导改用 @tryghost/errors、@tryghost/logging、@tryghost/debug |
strictLinterOptions(L221-L225) | linterOptions.reportUnusedDisableDirectives: 'error'——多余的 eslint-disable 注释也会报错,避免禁用指令堆积 |
reactDefaultsOff / reactStrictRules(L82-L100) | 关闭 react/react-in-jsx-scope(新 JSX transform 不再需要)、react/prop-types(用 TS 做 prop 类型);开启 react/jsx-sort-props(reservedFirst、callbacksLast、shorthandLast、locale: 'en')、button-has-type、no-array-index-key、jsx-key |
sortImportsRule(L58-L65) | 自动修复的 import 排序 ghost/sort-imports-es6-autofix/sort-imports-es6,排序为 none → all → single → multiple |
shadeLayeredImportsRule(L67-L80) | 用 no-restricted-imports 禁止直接 import @tryghost/shade 桶文件,提示走分层子路径 |
tailwindRulesV4 / tailwindRulesWithConfig(config)(L102-L125) | 开启 classnames-order、enforces-negative-arbitrary-values、enforces-shorthand、no-contradicting-classname;migration-from-tailwind-2、no-arbitrary-value、no-custom-classname 有意关闭(自定义类名是代码库依赖,任意值是允许的)。v3 版把 {config} 作为每规则选项 |
其中 localFilenamesPlugin 值得一提:它是 eslint-plugin-filenames-ts 的 match-regex 规则的 ESLint-9 兼容替代品(configs/eslint/index.mjs)。上游规则调用 context.getScope(),而该方法在 ESLint 9 已被移除,因此 Ghost 在仓库内实现了等价规则(含 Program 节点检查、ignoreExporting 逻辑,文件名来自 path.parse(context.filename).name)。同理,mochaRulesOff(plugin) 辅助函数会把 eslint-plugin-ghost 中所有 mocha/* 规则动态置 off,用于测试 block。
从组合关系看,nodeLibRules 面向服务端,tsReactAppRules(= correctness + unused-vars + React 默认/严格规则 + react-hooks 规则集级应用 + TS 安全默认)+ jsReactAppRules 面向 React 源码,而"react-hooks 规则放在规则集层"是为了让它们同时覆盖 src 与 test 两个 block(configs/eslint/index.mjs)。
legacy* 参数:迁移期例外不是新工作默认
README 强调:所有以 legacy 为前缀的参数,包括 legacyTailwindV3ConfigPath 与 legacyJsTsSplit,标记的是临时迁移例外,而非新工作的默认值。 结合真实消费者可看到它们各自服务于一段正在进行的迁移:
legacyTailwindV3ConfigPath:见 apps/comments-ui/eslint.config.js 与 apps/signup-form/eslint.config.js,它们把各自目录内的tailwind.config.js/tailwind.config.cjs传给工厂,等待 v4 迁移完成后切到tailwindCssPath;legacyJsTsSplit:见 apps/portal/eslint.config.js——portal 处于 JS→TS 迁移中间态,src/下.js/.ts混编,工厂会拆出"纯 JS block(vanilla 规则)"与"TS block(tseslint 规则 +project: './tsconfig.json')"。源码注释还记录了一个已修复的 bug:tsconfigRootDir曾经错误地解析到工厂所在目录(仓库根)而非工作区,现已改为tsconfigRootDir ?? process.cwd()(configs/eslint-react/index.mjs);typescript: false:见 apps/sodo-search/eslint.config.js 与 apps/announcement-bar/eslint.config.js,注释明言这是 LEGACY,期望迁移到 TS。
这些应用都同时带 reactRefresh: false 注释,因为 comments-ui、signup-form、portal、sodo-search、announcement-bar 是以 UMD 形式分发到主题里的应用,没有 Vite HMR 运行时,react-refresh 规则毫无意义。
独立配置区:不适合工厂的例外
README 明确指出,Ghost Core、Ember Admin 与 Admin Toolbar(分别见 ghost/core/eslint.config.mjs、apps/ember-admin/eslint.config.mjs、apps/admin-toolbar/eslint.config.js)的规则集无法套进共享工厂,因此保留独立配置并直接阅读其文件。它们仍然可以按需 import 基包的共享原子(如 correctnessRules、nodeLibRules、localFilenamesPlugin、strictLinterOptions)。
这在代码里有现成印证:apps/admin(React 应用)虽然是工厂消费者,却也直接从 @internal/cfg-eslint import 了 shadeLayeredImportsRule,再把它与自己的 no-restricted-imports 边界规则合并后作为数组展开使用(apps/admin/eslint.config.js)。也就是说"用不用工厂"与"用不用原子"是两件事——原子是细粒度可复用的最小单元,工厂则是"按约定组合原子"的默认装配线。
插件依赖纪律:谁 import,谁声明
扁平配置要求每个被解析到的 ESLint 插件都能被解析,Ghost 对此有三条纪律(README "Plugin dependencies" 一节):
- 工厂消费者只需声明配置包本身——工厂以对象形式自带插件,消费者无需逐个声明;
- 手写配置若直接 import 插件,就必须在自己的
devDependencies里声明该插件,不允许依赖根目录依赖提升(hoisting)的"意外可用"; - 使用 Tailwind 的工作区必须本地声明
tailwindcss(settings-based 的 v4 解析器需要它在本地解析);legacy v3 应用还要用tailwind3catalog 条目引入eslint-plugin-tailwindcss(对应 pnpm-workspace.yaml 中固定的eslint-plugin-tailwindcss: 3.18.3,与根主 catalog 的 4.x 版本隔离)。
这条纪律在源码中反复被强调:例如 React 工厂注释指出 v3 lane 必须从应用目录 createRequire(...) 解析 v3 插件,因为把 v4 插件的规则硬塞给 v3 的 {config} 选项会直接 schema 校验失败;@internal/cfg-eslint-react 之所以单独成包,也正是为了让 Node 库永远不必加载 React 插件集。
变更后的验证流程
最后,README 给出了明确的变更验证链路,与仓库根 package.json 的 lint 脚本互相印证:
- 修改单个工作区的
eslint.config→ 运行该工作区的pnpm linttarget(Nx 下等价于pnpm nx run <project>:lint,或按 JSDoc 提示的pnpm --filter <workspace> exec eslint直调); - 修改共享规则原子或任一工厂 → 必须运行根级
pnpm lint(即pnpm nx run-many -t lint lint:boundaries加 packages/docs 检查的聚合脚本),因为改动会波及其余全部工作区。
小结
Ghost 的共享 ESLint 体系可以概括为三个层次:原子层(correctnessRules、nodeLibRules、localFilenamesPlugin 等纯规则对象与插件,独立工作区也能复用)、工厂层(nodeLibConfig 面向 Node 库、reactAppConfig 面向 React 应用,同步、白名单校验、JSDoc 文档化)、工作区层(每个 eslint.config 组合工厂与自身追加 block)。贯穿始终的设计准则是"error 或 off、绝不 warn;legacy* 只是迁移期例外;谁 import 插件谁声明依赖"。对 monorepo 维护者而言,这套模式最有借鉴价值的地方在于:把规则写成带 TODO 与违规数量的可组合原子、把 React 插件栈隔离在独立包、并在工厂里做防御性选项校验——这让"配置漂移"和"静默失效"都变得几乎不可能发生。
如果要在仓库中继续深入,建议按这条路径阅读:先看 configs/eslint/README.md 的约束声明,再对照 configs/eslint/index.mjs 与 configs/eslint-react/index.mjs 的 JSDoc 选项与实现,最后打开自己关注的工作区(如 apps/admin/eslint.config.js、packages/i18n/eslint.config.mjs)观察"工厂 + 追加 block"的实际组合方式。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



