自定义 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",
      },
    };
相关推荐
non_hana4 天前
一些 linter & formatter 配置最佳实践
typescript·node.js·eslint
锈儿海老师5 天前
AST 工具大PK!Biome 的 GritQL 插件 vs. ast-grep,谁是你的菜?
前端·javascript·eslint
去伪存真8 天前
提交规范靠吼没用,看我用“shell+husky螺丝刀”,一键给40多个项目上锁
前端·eslint
wanna10 天前
eslint使用
eslint
去伪存真2 个月前
ESLint + Husky 如何只扫描发生改动的文件?
前端·eslint
孟陬2 个月前
利用 caniuse 结合 browserslist 对 JS 做兼容性检测
typescript·eslint·trae
USER_A0012 个月前
【VUE3】Eslint 与 Prettier 的配置
vue3·eslint·prettier
去伪存真2 个月前
给接手历史项目配置ESLint+Prettier,发现还是会踩坑
前端·eslint
卡列尼娜翠花3 个月前
vscode 导入语句排序和删除未使用的导入
前端·javascript·vscode·编辑器·eslint·前端工程化·esm