自定义 eslint 规则

自定义 eslint 规则

  1. 起名规范

eslint-plugin-guojieEslint
eslint-plugin-xxxx

  1. npm init
    初始化一个项目
//  package.json
{
  "name": "eslint-plugin-guojieeslint",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "author": "",
  "license": "ISC"
}
  1. 主逻辑
//  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",
          });
        }
      },
    };
  },
};
//  index.js
const amountCheck = require("./amount-check.js");
module.exports = {
  rules: {
    "amount-check": amountCheck,
  },
};
  1. 这样一个简单的 eslint 规则就完成了,如何使用
    环境 "eslint": "^8.57.1"
    命令 "test": "npx lint index.js"

     4.1 先在 我的自定义elsint 规则中 执行 `npm link `
     4.2 再在我们项目根目录 执行 `npm link eslint-plugin-guojieeslint`
         配置项:在项目中`.eslintrc.js`
    
    module.exports = {
      plugins: ["guojieeslint"],
      parserOptions: {
        ecmaVersion: 2018,
        sourceType: "module",
      },
      rules: {
        "guojieeslint/amount-check": "error",
      },
    };
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光头程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值