如何开发一个自定义的ESLint插件
解读
面试官问“如何开发一个自定义的 ESLint 插件”,并不是想听你背诵官方文档,而是考察四个维度:
- 对 ESLint 整体架构(规则、配置、插件、Parser、Processor)是否成体系;
- 是否能把“公司代码规范”抽象成可复用、可落地的规则;
- 是否具备把插件发布到私有 npm 源并集成到 CI 的完整交付经验;
- 是否了解国内常见“坑”:Monorepo、私有源、Proxy、Git Hooks 权限、Windows 路径、旧项目 Babel 共存等。
回答时要“先给骨架,再给血肉”,用“本地→私有源→CI”三步法展示工程化思维,最后主动抛一个“规则性能优化”话题,引导面试官继续深挖。
知识点
- 插件与规则的关系:插件是一个 npm 包,暴露
rules、configs、processors三个字段;规则是插件内部的一个文件,必须实现meta+create。 - 规则开发 API:
context.getSourceCode()、context.report()、fixer.replaceText()、fixer.removeRange(),以及 2022 之后支持的context.sourceCode.getScope(node)。 - 配置收敛:用
configs.recommended统一团队配置,避免“复制粘贴 .eslintrc”。 - 单元测试:官方工具
RuleTester,必须覆盖valid、invalid、errors、output四项;国内要求 100% 分支覆盖,否则 SonarQube 质量门禁失败。 - 私有 npm 源:阿里/腾讯/华为云镜像,需配置
.npmrc的registry与always-auth,并在 GitLab CI 里用NPM_TOKEN变量。 - 性能红线:规则不得遍历全文两次;不得同步读文件;不得用正则回溯;大型 Monorepo 必须在 200ms 内完成单条规则扫描。
- 合规:若代码需过“信创”审计,插件包里不能出现 MIT 之外的许可证文件;README 必须中文。
答案
下面用“国内交付”视角,给出一条可落地的最小闭环:
第一步:初始化插件脚手架
# 公司私有源
npm config set @mycompany:registry https://npm.mycompany.com
npx yo eslint:plugin # 生成 eslint-plugin-mycompany
目录规范:
lib/rules/no-dangerous-html.js
tests/lib/rules/no-dangerous-html.js
lib/index.js
lib/configs/recommended.js
第二步:编写规则
以“禁止 innerHTML 直接拼接用户输入”为例:
// lib/rules/no-dangerous-html.js
module.exports = {
meta: {
type: 'problem',
docs: { description: 'disallow direct innerHTML with user input' },
schema: [],
messages: { dangerous: 'innerHTML 可能引发 XSS,请使用 v-html/xss-filters' }
},
create(context) {
return {
AssignmentExpression(node) {
const left = node.left;
if (left.type === 'MemberExpression' &&
left.property.name === 'innerHTML') {
context.report({
node,
messageId: 'dangerous'
});
}
}
};
}
};
第三步:单元测试
const { RuleTester } = require('eslint');
const rule = require('../../../lib/rules/no-dangerous-html');
const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2022 } });
ruleTester.run('no-dangerous-html', rule, {
valid: ['element.textContent = userInput'],
invalid: [{
code: 'element.innerHTML = userInput',
errors: [{ messageId: 'dangerous' }]
}]
});
执行 npm test 必须全绿,再跑 npm run test:coverage 保证分支 100%。
第四步:暴露 configs
// lib/configs/recommended.js
module.exports = {
plugins: ['@mycompany/eslint-plugin-mycompany'],
rules: {
'@mycompany/no-dangerous-html': 'error'
}
};
// lib/index.js
module.exports = {
rules: { 'no-dangerous-html': require('./rules/no-dangerous-html') },
configs: { recommended: require('./configs/recommended') }
};
第五步:本地验证
在项目里 .eslintrc.js:
module.exports = { extends: ['plugin:@mycompany/recommended'] };
执行 npx eslint src/ 能看到新规则生效。
第六步:发布到私有源
npm version patch
npm publish --registry https://npm.mycompany.com
在 GitLab CI 模板里加:
eslint:
image: node:18-alpine
before_script:
- echo "//npm.mycompany.com/:_authToken=${NPM_TOKEN}" > ~/.npmrc
script:
- npx eslint --max-warnings 0 src/
至此,插件完成“本地→私有源→CI”闭环,符合国内企业的合规、性能、质量门禁要求。
拓展思考
- 规则性能优化:若规则需跨文件分析(如检测“重复接口定义”),可借助
eslint-plugin-import的ExportMap缓存,或把耗时逻辑拆成独立 Worker,避免阻塞主线程。 - 自动修复冲突:当两条规则的 fixer 作用域重叠时,ESLint 采用“先注册先执行”策略,如何在插件里用
meta.fixable标记范围、用fixer.insertTextAfterRange避开冲突? - 低代码场景:国内很多 B 端产品用自研 DSL,如何把 ESLint 插件扩展到自定义 Parser(基于
@babel/parserfork),并在 VS Code 插件里做实时提示? - 合规审计:在“信创”环境下,如果插件依赖了
lodash,如何把依赖打成单文件并替换许可证声明,以满足“无 MIT 依赖”要求?
主动把上述任意一点抛给面试官,可展示你对“开发插件”背后更深层的工程与合规思考,从而拿到加分。