ESLint 插件(Plugin)开发指南
一、ESLint 插件概述
ESLint 插件是用于扩展 ESLint 功能的模块,主要提供以下能力:
- 自定义规则:例如禁止变量名以 $ 开头
- 预设配置:一键启用特定规则组合(如 recommended 配置)
- 文件处理器:支持处理非 JS 文件(如 .txt、.md 中的代码片段)
- 元信息:包含插件名称、版本和命名空间等基本信息
插件本质上是复用 ESLint 扩展功能的封装模块,可通过 npm 发布实现跨项目共享。
二、插件基本结构
插件是一个包含特定属性的导出对象:
const plugin = {
meta: {}, // 元信息
configs: {}, // 预设配置
rules: {}, // 自定义规则
processors: {}, // 文件处理器
};
// ESM 导出方式
export default plugin;
// CommonJS 导出方式
module.exports = plugin;
三、元信息配置
建议在 meta 中明确声明以下信息以方便调试和缓存:
const plugin = {
meta: {
name: "eslint-plugin-example", // npm 包名
version: "1.2.3", // 包版本
namespace: "example", // 插件命名空间
}
};
最佳实践
命名空间通常是包名去掉 eslint-plugin-
前缀的部分。例如 eslint-plugin-vue
的命名空间是 vue
。
推荐从 package.json 自动读取名称和版本:
import fs from "fs";
const pkg = JSON.parse(
fs.readFileSync(new URL("./package.json", import.meta.url), "utf8")
);
const plugin = {
meta: {
name: pkg.name,
version: pkg.version,
namespace: "example",
}
};
四、自定义规则实现
通过 rules 对象提供自定义规则,每个规则通过 create(context) 方法实现:
const plugin = {
rules: {
"dollar-sign": {
create(context) {
// 规则实现逻辑
}
}
}
};
使用方式
// eslint.config.js
import { defineConfig } from "eslint/config";
import example from "eslint-plugin-example";
export default defineConfig([
{
plugins: { example },
rules: {
"example/dollar-sign": "error" // 启用规则
}
}
]);
五、文件处理器
处理器使 ESLint 能够处理非 JS 文件,包含两个核心方法:
const plugin = {
processors: {
"processor-name": {
preprocess(text, filename) { /* 文件预处理 */ },
postprocess(messages, filename) { /* 结果后处理 */ }
}
}
};
配置使用
export default defineConfig([
{
files: ["**/*.txt"],
plugins: { example },
processor: "example/processor-name"
}
]);
六、预设配置
提供内置配置(如 recommended)可简化用户配置:
const plugin = {
configs: {},
rules: {
"dollar-sign": { create(context) {} }
}
};
Object.assign(plugin.configs, {
recommended: [
{
plugins: { example: plugin },
rules: { "example/dollar-sign": "error" },
languageOptions: {
globals: { myGlobal: "readonly" },
parserOptions: { ecmaFeatures: { jsx: true } }
}
}
]
});
使用方式
export default defineConfig([
{
plugins: { example },
extends: ["example/recommended"]
}
]);
七、兼容旧版配置
为支持传统 .eslintrc 项目,可同时提供新旧配置:
Object.assign(plugin.configs, {
"flat/recommended": [{ /* 新版配置 */ }],
recommended: {
plugins: ["example"],
rules: { "example/dollar-sign": "error" }
}
});
八、发布插件
发布到 npm 时需注意:
- 声明 ESLint 版本依赖
{
"peerDependencies": {
"eslint": ">=9.0.0"
}
}
- 添加关键词优化搜索
{
"keywords": ["eslint", "eslintplugin", "eslint-plugin"]
}
九、测试建议
推荐使用 ESLint 提供的 RuleTester 进行单元测试,并配置以下工具:
- eslint
- eslint-plugin-eslint-plugin
- eslint-plugin-n
总结
一个完整的 ESLint 插件应包含:
- meta:插件元信息
- rules:自定义规则
- processors:文件处理器
- configs:预设配置
开发完成后发布到 npm 即可实现跨项目共享。