【24 Eslint 9.x插件】Eslint插件编写例子-bysking

可自行移步官网查阅:eslint.org/docs/head/e...

一、需求

实现一个eslint插件,对定义的 const foo = 'bar'; 要求'foo'变量的值必须是'bar',否则执行eslint的时候报错

二、实现

  • 依赖安装
js 复制代码
 "eslint": "^9.22.0" // yarn add eslint@latest -D

同时,确保当前项目的模块查找是es模块 package.json里面增加 "type": "module"

  • eslint.config.js 配置文件新建,参考配置如下
js 复制代码
// eslint.config.js
import { defineConfig, globalIgnores } from 'eslint/config';
import js from '@eslint/js';

export default defineConfig([
  globalIgnores(['**/*.test.js', '.config/', 'dist/', 'tsconfig.json']),
  {
    plugins: {
      js,
      eslintPluginExample,
    },
    files: ['**/*.ts', '**/*.js'],
    extends: ['js/recommended'],
    rules: {
      'no-unused-vars': 'off',
    },
    languageOptions: {
      parserOptions: {
        ecmaVersion: 'latest',
        sourceType: 'module',
        ecmaFeatures: {
          jsx: true,
        },
      },

      // 全局变量声明
      globals: {
        React: true,
        ReactDOM: true,
        window: true,
        document: true,
      },
    },
  },
]);
  • package.json增加eslint命令
js 复制代码
  "scripts": {
    "lint": "eslint .",
    "lint:fix": "eslint . --fix"
  },
  • 新建插件代码源码 位置路径:./eslint-plugin-dir/index.js
js 复制代码
const fooBarRule = {
  meta: {
    type: 'problem',
    docs: {
      description:
        "Enforce that a variable named `foo` can only be assigned a value of 'bar'.",
    },
    fixable: 'code',
    schema: [],
  },
  create(context) {
    return {
      // 基于ast的语法树遍历节点函数定义执行逻辑
      VariableDeclarator(node) {
        // 变量定义检查是不是const
        if (node.parent.kind === 'const') {
          // 变量名检查是不是foo
          if (node.id.type === 'Identifier' && node.id.name === 'foo') {
            // 赋值检查 是不是'bar'
            if (
              node.init &&
              node.init.type === 'Literal' &&
              node.init.value !== 'bar' 
            ) {
            
               // 报告错误
              context.report({
                node,
                data: {
                  notBar: node.init.value,
                },
                message: '亲,不能这么写,{{ notBar }}.',
  
                // 执行eslint . --fix 的时候,具体的修复逻辑
                fix(fixer) {
                  return fixer.replaceText(node.init, '"bar"');
                },
              });
            }
          }
        }
      },
    };
  },
};

export default { rules: { 'enforce-foo-bar': fooBarRule } };
  • 引用插件
js 复制代码
import eslintPluginExample from './eslint-plugin-dir/index.js';

export default defineConfig([
  // ...其他配置
  {
    plugins: {
      eslintPluginExample,
    },
    rules: {
      'eslintPluginExample/enforce-foo-bar': 'error',
    },
  },
]}
  • 完整示范
js 复制代码
// eslint.config.js
import { defineConfig, globalIgnores } from 'eslint/config';
import js from '@eslint/js';
import eslintPluginExample from './eslint-plugin-dir/index.js';

export default defineConfig([
  globalIgnores(['**/*.test.js', '.config/', 'dist/', 'tsconfig.json']), // 全局忽略目录,文件
  {
    plugins: {
      js,
      eslintPluginExample, // 引入插件
    },
    files: ['**/*.ts', '**/*.js'], // 文件范围
    ignores: ['src/serviceWorker.js', '.rescriptsrc.js'], // 忽略
    extends: ['js/recommended'], // 继承其他eslint配置
    rules: {
      'no-unused-vars': 'off',
      'eslintPluginExample/enforce-foo-bar': 'error', // 具体规则配置
    },
    languageOptions: { // 语言配置
      parserOptions: {
        ecmaVersion: 'latest',
        sourceType: 'module',
        ecmaFeatures: {
          jsx: true,
        },
      },

      // 全局变量声明
      globals: {
        React: true,
        ReactDOM: true,
        window: true,
        document: true,
      },
    },
    // 是否允许通过注释禁用规则
    // linterOptions: {
    //   noInlineConfig: true,
    // },
  },
]);
  • 运行 yarn lint 查看效果
相关推荐
军军君015 分钟前
基于Springboot+UniApp+Ai实现模拟面试小工具二:后端项目搭建
前端·javascript·spring boot·spring·微信小程序·前端框架·集成学习
quweiie1 小时前
tp8.0\jwt接口安全验证
前端·安全·jwt·thinkphp
xiaoyan20151 小时前
最新Flutter3.32+Dart3仿微信App聊天实例
前端·flutter·dart
汪敏wangmin1 小时前
Fiddler-抓包后直接生成Loadrunner脚本或者Jmeter脚本
前端·jmeter·fiddler
彤银浦2 小时前
Web学习笔记3
前端·笔记·学习·html5
江城开朗的豌豆2 小时前
退出登录后头像还在?这个缓存问题坑过多少前端!
前端·javascript·vue.js
江城开朗的豌豆2 小时前
Vue的'读心术':它怎么知道数据偷偷变了?
前端·javascript·vue.js
江城开朗的豌豆2 小时前
手把手教你造一个自己的v-model:原来双向绑定这么简单!
前端·javascript·vue.js
我在北京coding3 小时前
el-tree 懒加载 loadNode
前端·vue.js·elementui
江城开朗的豌豆3 小时前
v-for中key值的作用:为什么我总被要求加这个'没用的'属性?
前端·javascript·vue.js