自定义 eslint 规则

自定义 eslint 规则

  1. 起名规范

eslint-plugin-guojieEslint
eslint-plugin-xxxx

  1. npm init
    初始化一个项目
json 复制代码
//  package.json
{
  "name": "eslint-plugin-guojieeslint",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "author": "",
  "license": "ISC"
}
  1. 主逻辑
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,
  },
};
  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`
    js 复制代码
    module.exports = {
      plugins: ["guojieeslint"],
      parserOptions: {
        ecmaVersion: 2018,
        sourceType: "module",
      },
      rules: {
        "guojieeslint/amount-check": "error",
      },
    };
相关推荐
angelQ5 天前
针对"@antfu/eslint-config": "^4.17.0"最新版本使用报错Unexpected token 'with'的解决方法
前端·eslint
jason_yang9 天前
代码规范-3大利器 prettier eslint husky
代码规范·eslint
拾光拾趣录13 天前
ESLint:从代码扫描到自动修复
前端·eslint
namehu17 天前
从 ESLint 到 Oxlint:一次提速百倍的前端 Lint 工具链升级实战
前端·javascript·eslint
non_hana2 个月前
一些 linter & formatter 配置最佳实践
typescript·node.js·eslint
锈儿海老师2 个月前
AST 工具大PK!Biome 的 GritQL 插件 vs. ast-grep,谁是你的菜?
前端·javascript·eslint
去伪存真2 个月前
提交规范靠吼没用,看我用“shell+husky螺丝刀”,一键给40多个项目上锁
前端·eslint
wanna2 个月前
eslint使用
eslint
去伪存真3 个月前
ESLint + Husky 如何只扫描发生改动的文件?
前端·eslint