自定义 eslint 规则
- 起名规范
eslint-plugin-guojieEslint
eslint-plugin-xxxx
- npm init
初始化一个项目
json
// package.json
{
"name": "eslint-plugin-guojieeslint",
"version": "1.0.0",
"description": "",
"main": "index.js",
"author": "",
"license": "ISC"
}
- 主逻辑
js
// amount-check.js
module.exports = {
meta: {
type: "problem",
docs: {
description: "禁止直接对金额变量进行加法运算,防止精度丢失",
category: "Possible Errors",
recommended: false,
},
messages: {
noAmountPlus:
"金额运算不能直接用加法,可能会有精度丢失,请使用专用金额运算方法。",
},
},
create(context) {
return {
BinaryExpression(node) {
console.log(node.left.name, node.right.name);
if (
node.operator === "+" &&
node.left.type === "Identifier" &&
node.right.type === "Identifier" &&
/Amount$/.test(node.left.name) &&
/Amount$/.test(node.right.name)
) {
context.report({
node,
messageId: "noAmountPlus",
});
}
},
};
},
};
js
// index.js
const amountCheck = require("./amount-check.js");
module.exports = {
rules: {
"amount-check": amountCheck,
},
};
-
这样一个简单的 eslint 规则就完成了,如何使用
环境
"eslint": "^8.57.1"
命令
"test": "npx lint index.js"
4.1 先在 我的自定义elsint 规则中 执行 `npm link ` 4.2 再在我们项目根目录 执行 `npm link eslint-plugin-guojieeslint` 配置项:在项目中`.eslintrc.js`
jsmodule.exports = { plugins: ["guojieeslint"], parserOptions: { ecmaVersion: 2018, sourceType: "module", }, rules: { "guojieeslint/amount-check": "error", }, };