ESLint类的核心方法和事件有哪些

解读

在国内一线/二线大厂的面试中,这道题常被用来区分“只会用”和“真正懂”。
面试官想确认三件事:

  1. 你是否把 ESLint 当成黑箱,还是清楚它内部的生命周期;
  2. 面对自定义规则、插件、共享配置时,你能否精准地找到“切入点”;
  3. 当 CI 出现偶发 lint 错误时,你能否通过事件钩子快速定位是规则 bug、缓存失效还是并发写文件。
    因此,回答必须围绕“类”——即 eslint npm 包导出的 ESLint 类(v8 之后的新 API),而不是已废弃的 CLIEngine。要讲清楚“方法”负责“干什么”,“事件”负责“通知什么”,并给出真实可运行的代码片段,才能拿到高分。

知识点

  1. 核心类迁移史

    • CLIEngine(v7 及以前)→ ESLint 类(v8+)。
    • 新类把“执行”与“输出”彻底分离,所有磁盘写操作都通过 outputFixes() 显式调用,避免副作用。
  2. 实例化选项(高频追问)

    • cwd、resolvePluginsRelativeTo、rulePaths、ignorePath、cache、cacheLocation、baseConfig。
    • 面试官常追问:为什么 monorepo 里必须配 resolvePluginsRelativeTo?答:否则插件解析会走到根目录 node_modules,导致“找不到插件”假阴性。
  3. 核心方法(按执行顺序)

    1. static version() → 返回 semver,用于插件做版本兼容;
    2. static outputFixes(results) → 把 result.output 写回磁盘,必须在 lintFiles/lintText 之后显式调用;
    3. calculateConfigForFile(filePath) → 给出该文件的最终落点配置(含 extends、overrides),是调试“为什么这条规则不生效”的利器;
    4. isPathIgnored(filePath) → 与 .eslintignore 逻辑保持一致,用于增量扫描前过滤;
    5. lintFiles(patterns) → 并发执行,返回 Promise<LintResult[]>;
    6. lintText(code, { filePath }) → 内存 lint,常用于 IDE 实时诊断;
    7. loadFormatter(name | path) → 返回 { format(results) } 对象,内置 stylish、unix、json、compact、tap、html,也可加载第三方 formatter;
    8. getRules() → 返回 Map<ruleId, rule>,用于做“规则白名单”扫描,比如合规审计要求“禁用所有带 eval 的规则”。
  4. 事件(EventEmitter 混入)
    ESLint 类本身不继承 EventEmitter,但内部 Linter 实例提供了规则运行时钩子;社区实践中,有三种“事件”可监听:

    • rule-runtime 事件:在自定义规则里通过 context.report({ message, loc, fix }) 触发,可被上层工具拦截做“规则耗时”统计;
    • processor-transform 事件:当解析 .vue、.md 文件时,processor 的 preprocess/postprocess 会抛出伪事件,可被插件用来缓存中间代码;
    • cache-miss 事件:当 eslint --cache 发现文件哈希变化时,CLI 层会打印 debug 日志,可通过 DEBUG=eslint:cache* 环境变量捕获,用于度量“缓存命中率”。

    面试时要强调:官方类没有暴露标准事件,但可以通过 monkey-patch Linter.prototype.verify 或接入 eslint-formatter-event 这类社区包,把“方法”转成“事件”流,实现实时仪表盘。

  5. 并发与缓存实现

    • lintFiles 内部使用 p-limit 做 os.cpus().length 并发,默认 10;
    • 缓存文件为 .eslintcache,格式是 JSON 的 Map<filePath, hash>;
    • 若启用了 --cache-strategy content(v8.44+),则走文件内容哈希,避免 git checkout 触发全量重检。

答案

ESLint 类(v8+)的核心方法按职责分为“配置计算、文件扫描、结果输出、工具辅助”四类:

  1. 配置计算

    • calculateConfigForFile(filePath)
    • isPathIgnored(filePath)
  2. 文件扫描

    • lintFiles(patterns: string[])
    • lintText(code: string, options?: { filePath?: string, warnIgnored?: boolean })
  3. 结果输出

    • static outputFixes(results: LintResult[])
    • loadFormatter(name?: string)
  4. 工具辅助

    • static version()
    • getRules()

事件方面,官方 ESLint 类未暴露 EventEmitter,但运行时可通过以下三种途径拿到“伪事件”:

  • 在自定义规则里调用 context.report() 时,相当于抛出问题事件;
  • 在 processor 的 preprocess/postprocess 里可植入自定义事件,用于多阶段文件(Vue、Markdown)转换;
  • 开启 DEBUG=eslint:cache* 环境变量后,缓存命中/失效会打印对应事件,可用于 CI 性能分析。

实战示例:

import { ESLint } from 'eslint';

const eslint = new ESLint({
  cache: true,
  cacheLocation: 'node_modules/.cache/.eslintcache'
});

// 1. 计算最终配置
const cfg = await eslint.calculateConfigForFile('src/main.ts');
console.log('该文件生效的 rule 数:', Object.keys(cfg.rules).length);

// 2. 扫描
const results = await eslint.lintFiles(['src']);

// 3. 自动修复
await ESLint.outputFixes(results);

// 4. 事件级耗时统计(伪代码)
const linter = new (await import('eslint')).Linter();
const original = linter.verify;
linter.verify = function (...args) {
  console.time('rule-verify');
  const ret = original.apply(this, args);
  console.timeEnd('rule-verify');
  return ret;
};

拓展思考

  1. 如何在不写文件的前提下拿到“修复后”的代码?
    答:对每条结果取 result.output,若存在则即为修复后内容;可封装为 const fixed = results.map(r => r.output || r.source),用于 CI 增量评论。

  2. 在 pnpm monorepo 中,子包引用自定义插件报“Cannot find module eslint-plugin-xxx”怎么办?
    答:实例化时加 resolvePluginsRelativeTo: __dirname,强制插件解析从当前子包 node_modules 开始;同时把插件写成 eslint-plugin-xxx 并放到 devDependencies,避免 hoisting 差异。

  3. 想做“规则性能大盘”,除了 monkey-patch 还有什么官方友好方案?
    答:写自定义 formatter,在 format(results) 里遍历每条消息的 ruleId 与 severity,结合 process.hrtime.bigint() 统计耗时;再接入 Prometheus pushgateway,即可在 Grafana 实时看到每条规则的耗时 P99。