自定义eslint规则

我要自定义我的个人的eslint规则

示例:不让团队成员使用 aaa 这几个字来作为变量名

-rule定义:针对这个规范的需求,编写一个 rule,原理是通过 ast,通过 ast 节点处理来完成

-plugin插件定义:将rule 进行插件化,提供给外部使用

-use使用:将插件引入到 eslint 配置文件中,使用插件

\myeslint

\myeslint\plugins\eslint-plugin-whh.js

\myeslint\rules\no-whh-vars.js

javascript 复制代码
// \myeslint\plugins\eslint-plugin-whh.js
​
​
// 插件的本质是对象,符合插件的基础协议
import { noWhhVars } from "../rules/no-whh-vars.js";
​
export const eslintWhhPlugin = {
  rules: {
    "no-whh-vars": noWhhVars,
  },
};

eslintConfig 中导入

javascript 复制代码
import { eslintWhhPlugin } from "./myeslint/plugins/eslint-plugin-whh.js";
export default defineConfig(
     {
        plugins: {
          js,
          whh: eslintWhhPlugin, // 插件定义好之后,插件的名称就是规则的作用域,rules 中使用自定义规则要在前面带名称
        },
        extends: ["js/recommended"],
      },
      {
        rules: {
          "whh/no-whh-vars": "error", // 自定义规则,不能使用 whh 作为变量名;   rules 中使用自定义规则要在前面带名称
        },
      },
])

astexplore 主要是看节点的便利顺序,生成对应的 ast 树

scss 复制代码
// \myeslint\rules\no-whh-vars.js
​
// 规则的本质是一个对象
// 在插件化规则里,这个对象的属性约束就是我们所说的插件化协议
​
// eslint的插件必须长的像一个约定好的对象
// 必须要有如下属性, meta 和 creat 方法
​
export const noWhhVars = {
  meta: {}, // 插件元信息
  create(context) {
    //插件的入口,插件的上下文
    return {
      // 这是一个访问者模式,访问到某一个节 ast 节点,就进行处理
      VariableDeclaration(node) {
        console.log("VariableDeclaration --->", node);
      },
      VariableDeclarator(node) {
        console.log("VariableDeclarator --->", node);
      },
      Identifier(node) {
        console.log("Identifier --->", node);
      },
      Literal(node) {
        console.log("Literal --->", node);
      },
    };
  },
};

控制规则主要走这个方法( Identifier(node)做文章

javascript 复制代码
// 规则的本质是一个对象
// 在插件化规则里,这个对象的属性约束就是我们所说的插件化协议
​
// eslint的插件必须长的像一个约定好的对象
// 必须要有如下属性, meta 和 creat 方法
​
export const noWhhVars = {
  meta: {
    messages: {
      noWhhVars: "不允许使用 whh 变量",
    },
  }, // 插件元信息
  create(context) {
    //插件的入口,插件的上下文
    return {
      // 控制规则主要走这个方法做文章
      Identifier(node) {
        // console.log("Identifier --->", node);
        if (node.name === "whh") {
          // 上报错误
          context.report({
            node,
            messageId: "noWhhVars", // 上报的 messageId 和元信息的 messages 一致
            data: {
              name: node.name,
            },
          });
        }
      },
    };
  },
};
相关推荐
奔跑的web.1 天前
TypeScript Enum 类型入门:从基础到实战
前端·javascript·typescript
盐真卿1 天前
python2
java·前端·javascript
梦梦代码精1 天前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
seabirdssss1 天前
《bootstrap is not defined 导致“获取配置详情失败”?一次前端踩坑实录》
前端·bootstrap·html
kgduu1 天前
js之表单
开发语言·前端·javascript
谢尔登1 天前
Vue3 响应式系统——computed 和 watch
前端·架构
愚公移码1 天前
蓝凌EKP产品:主文档权限机制浅析
java·前端·数据库·蓝凌
欣然~1 天前
法律案例 PDF 批量转 TXT 工具代码
linux·前端·python
一个小废渣1 天前
Flutter Web端网络请求跨域错误解决方法
前端·flutter
符文师1 天前
css3 新特性
前端·css3