美文网首页让前端飞程序员
eslint-plugin 开发入门

eslint-plugin 开发入门

作者: 文者字清 | 来源:发表于2018-11-02 22:52 被阅读3次
eslint

对于前端开发者,eslint是比较常用的代码规范和错误检查工具,eslint非常强大,不仅提供了大量的常用rules,而且允许开发者根据实际需要自定义rule,通过开发eslint-plugin把自定义rule加入到eslint正常检查过程中,简单方便。

如何自定义rule,以及开发eslint-plugin呢?

这里以一个简单的示例来演示一下如何开发自己的rule以及plugin。
示例需求:检查js文件中 class name 是否与 parent folder name 相同,如果不同,就给出报错

先看官方文档对于自定义rule的示例以及一些属性的说明,下面敲黑板,划重点,要考的😂

  • rule 是一个对象,里面有个方法 create ,参数是 context ,这里面有很多属性 方法,根据自己的需要,使用对应的方法属性,我们要获取 parent folder name ,所以使用 getFilename() 这个方法,这个方法返回文件的绝对路径,可以使用字符串方法得到父文件夹名称。
  • create 必须返回一个 object ,看文档的介绍
    create
    文档里的 node 是AST语法树中的node,推荐一个AST在线转换网站
    class转换
    由上图可见,我们要使用的 node type 是 ClassDeclaration ,
  • 直接上代码:
    文件目录
├── README.md
├── __tests__
│   └── rules
│       └── index.js
├── jest.config.js
├── lib
│   ├── index.js
│   └── rules
│       └── checkClassName.js
├── package.json
└── yarn.lock

checkClassName.js

module.exports = {
  meta: {
    docs: {}
  },
  create(context) {
    return {
      "ClassDeclaration": function (node) {
        // 参数 node 就是 AST 里面 ClassDeclaration 对象
        const filePath = context.getFilename();
        const filePatchArr = filePath.split('/');
        const folderName = filePatchArr[filePatchArr.length - 2];

        if (filePath.indexOf('/src/view') > -1 && node.id && node.id.name !== folderName) {
          // 过滤文件
          context.report({ node, message: 'class 名称与文件夹名称不一致,class name is \'' + node.id.name + '\'.' })
          // 抛出报错信息
        }
      }
    }
  }
}

lib/index.js

const rule = require('./rules/checkClassName.js');

module.exports.rules = {
  'check-pview-name': rule
};

在项目里使用,编辑.eslintrc文件:

 {
    "plugins": [
      "eslint-plugin-check-class-name"
      // 你 publish 的 npm 包名称,可以省略 eslint-plugin
    ],
    "rules": {
      "check-class-name/check-name": "error"
      // plugin name / rule
    }
  }

目录中的test文件就不展示了,我这里也没用到,具体的单元测试,网上一大堆文档可以参考。我这里的测试是通过在项目中的node_modules里某个eslint-plugin源码中加入自己的代码,慢慢调试,虽然很low,但是很方便快速🙃

如此,一个非常简单的eslint-plugin开发完成,重点还是要体会eslint对拓展插件的应用方式,由简及繁,慢慢进阶。

相关文章

网友评论

    本文标题:eslint-plugin 开发入门

    本文链接:https://www.haomeiwen.com/subject/pyqhxqtx.html