从0-1的eslint插件开发教程
开发eslint插件目的:根据项目需要,自定义满足项目特殊需要的校验规则是
参考eslint官方文档展开阐述
下面开始通过一个示例demo来介绍插件整个开发流程
代码中出现的方法及变量的详细解释与相关文档,会在文末给大家列举出来,大家可以先把代码拷贝到自己的demo中然后结合本文第3部分
的变量|方法解释去理解代码
开发一个校验注释中是否包含指定关键词的插件(eslint-plugin-comments-key
)
1. 环境准备
目录结构
├── README.md 插件介绍文档
├── index.js 对外暴露插件
├── lib
│ └── rules 自定义规则
│ └── comments-key.js
├── package.json
└── tests 测试自定义规则
└── lib
└── rules
└── comments-key.js
安装依赖
- eslint
- mocha
npm i eslint mocha -D
2. 开始编码
编写自定义规则
不包含自定义参数校验规则
/lib/rules/comments-key.js
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Not allowed comment words", // 规则的简述
category: "Stylistic Issues", // 规则分类
recommended: true // 配置文件中的 "extends": "eslint:recommended"属性是否启用该规则
}
},
create: function (context) {
// context对象包含与规则上下文相关的信息
// 返回一个SourceCode对象,你可以使用该对象处理传递给 ESLint 的源代码
const sourceCode = context.getSourceCode()
// 定义不被允许出现在注释中的内容
const notAllowWords = ['fixme', 'xxx']
return {
Program(node) {
// 获取所有注释的节点
const comments = sourceCode.getAllComments()
// 遍历注释节点判断是否有不符合规范的
comments.forEach(comment => {
let {
loc, value, type } = comment
value = value.toLowerCase()
let warnWord = ''
// 判断注释内容是否包含不被允许的word
for (const word of notAllowWords) {
if (value.includes(word)) {
warnWord = word
}
}
if (warnWord) {
context.report({
node: comment, // 可选 与问题有关的 AST 节点
message: