自定义 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",
      },
    };
相关推荐
To_OC3 天前
装完 ESLint 它一声不吭?我还以为代码写得多好
后端·node.js·eslint
先吃饱再说8 天前
代码写得好不好,谁说了算?ESLint 如何让团队代码风格“自动统一”
代码规范·eslint
Darling噜啦啦8 天前
别再写"烂代码"了!ESLint v10 完整实战,用 Flat Config 治好团队的代码洁癖
eslint
烬羽8 天前
ESLint 10 把 .eslintrc 删了:flat config 到底怎么配,我帮你踩完了
代码规范·eslint·前端工程化
Asize8 天前
ESLint 到底在帮我们守住什么?从规则配置到工程实践
代码规范·eslint
嘟嘟07178 天前
ESLint 入门:从 npm run lint 到 --fix 与规则级别一次讲清
javascript·代码规范·eslint
Flynt23 天前
我用Biome替换ESLint+Prettier在项目上踩了不少坑
rust·eslint·前端工程化
任磊abc1 个月前
react native项目配置eslint+prettier
react native·eslint·prettier
任磊abc3 个月前
nextjs16配置eslint+prettier
前端·eslint·nextjs·prettier
梵得儿SHI3 个月前
Vue 项目实战与性能优化:工程化与协作全指南(规范 + 配置 + 协作 + 文档)
前端·vue.js·代码规范·eslint·团队协作·前端工程化·前端架构