Eslint在Jsx中的使用(6)

在 npm 上发布自己的 Eslint 规则

自定义规则

基于上一篇文章我们有了以下代码,回顾上文

/* 自定义规则 */
module.exports = {
  meta: {
    type: "problem",
    docs: {
      description: "error console.log have 99",
    },
    fixable: "code",
    schema: [],
  },
  create: function (context) {
    return {
      ExpressionStatement: function (node) {
        /* 存在相等则报错 */
        if (node.expression.arguments[0].value === "99") {
          context.report({
            node: node,
            message: "error console.log have 99",
          });
        }
      },
    };
  },
};

自定义测试

/* 自定义测试 */
const rule = require("../../../lib/rules/eslint-plugins-rule");
const RuleTester = require("eslint").RuleTester;

const ruleTester = new RuleTester();

ruleTester.run("eslint-plugins-rule", rule, {
  /* 有效场景 */
  valid: ['console.log("66");'],
  /* 无效场景 */
  invalid: [
    {
      code: "console.log('99');",
      errors: [
        {
          message: "error console.log have 99",
          type: "ExpressionStatement",
        },
      ],
    },
  ],
});
console.log("All tests passed!");

配置 rules 文件夹的 index.js 文件

/**
 * @fileoverview con99
 * @author con99
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const requireIndex = require("requireindex");
// 在这里导入了我们上面写的自定义规则
const rules = requireIndex(__dirname + "/rules");
module.exports = {
  // rules是必须的
  rules,
  // 增加configs配置
  configs: {
    // 配置了这个之后,就可以在其他项目中像下面这样使用了
    // extends: ['"plugin:xxxx/recommended"']
    recommended: {
      plugins: ["con99"], //con99 是package.json中 "name": "eslint-plugin-con99",中eslint-plugin-后面的名字
      rules: {
        "con99/eslint-plugins-rule": ["error"], //eslint-plugins-rule为我们自己创建的规则文件名称
      },
    },
  },
};

发布插件

/* 登录 */
npm login
/* 发布 */
npm publish

登录成功
在这里插入图片描述

发布成功
在这里插入图片描述

在 npm 查看包
在这里插入图片描述

下载插件

在我们之前创建 jsx 文件中下载插件

npm i eslint-plugin-con99

在这里插入图片描述

使用插件

在我们之前创建好的项目中的.eslintrc.json 中使用插件
在这里插入图片描述

重启 vscode 的 Eslint 插件
在这里插入图片描述

测试插件情况

在我们之前创建好的项目中的 App.jsx 中输入 console.log(“99”)
在这里插入图片描述

到这里我们完成了自定义 Eslint 插件的下载和使用

更新插件

如果我们要更新我们自定义的 Eslint 插件,就在我们更新完的插件文件输入以下命令

npm version patch
/* 这个命令是基于当前的包现在的版本进行一个小版本的更新
假如我们当前版本为0.0.0,输入这个命令版本就变成了0.0.1,再输入就变成了0.0.2
*/


npm version 2.0.2
/* 这个命令是自定义版本号,不能比之前版本低哦
*/

我使用 npm version 2.0.2 这个命令更新版本
在这里插入图片描述

发布更新插件

/* 在输入npm publish即可把最新版本提交上去 */
npm publish

发布成功
在这里插入图片描述

在项目中使用更新插件

/* 在输入npm 插件名字@版本号即可下载对应版本 */
npm i eslint-plugin-con99@2.0.2

在这里插入图片描述

到这里然后npm 上发布自己的 Eslint 规则就完成了!

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值