美文网首页让前端飞
手把手教你如何扩展eslint的检查规则

手把手教你如何扩展eslint的检查规则

作者: belllee | 来源:发表于2018-10-25 19:47 被阅读5次

本文介绍了扩展eslint检查规则具体方法。下面我们就以一个具体的检查规则实例来介绍下扩展检查规则的具体方法。

规则说明

新增规则需要检查vue文件中的style元素必须要加上scoped属性,否则就要报异常。

如何定义规则

在node_modules\eslint-plugin-vue\lib\rules文件夹中增加一个新规则文件。示例代码如下:

'use strict'

module.exports = {
  meta: {
    docs: {
      description: 'There is no scoped in `<style>`',
      category: 'essential',
      url: ''
    },
    fixable: null,
    schema: []
  },

  create (context) {
    let repostError = (line)=>{
      context.report({
        loc: {
          start:{
            line: line,
            column: 0
          },
          end:{
            line: line,
            column: 0
          }
        },
        message: "Style node need a attribute of scoped"
      });
    }
    
    return {
      Program () {
        let lines = context.getSourceCode().lines
        let styleLines = []
        let isScoped = false
        for(let i=0,len=lines.length; i<len; i++){
          let l = lines[i]
          if(l.indexOf('<style') > -1){
            isScoped = l.indexOf('scoped') > -1
            styleLines.push(i+1)
          }
        }
        
        if(!isScoped && styleLines.length>0){
          for(let i=0,l; l=styleLines[i]; i++){
            repostError(l)
          }
        }
      }
    }
  }
}

详细说明:

  1. 每个规则都是一个对象,使用module.exports导出该规则对象
  2. 该对象必须包含两个属性meta对象和create函数
  3. meta属性是一个对象,定义了该规则的相关定义,例如:
    docs是对规则的描述信息,包括规则含义,所属分类,规则说明url等;
    fixable用来定义如何自动修复;
    schema用来定义规则的开关配置;
  4. create方法返回一个对象,ESLint在遍历代码的抽象语法树时调用相关的方法。属性名称对应由ESTree定义的AST类型。分别针对各种类型定义检查方法。
  5. context是eslint的执行环境。由于ATS里没有CSS相关定义,这里使用了getSourceCode方法,获取被检查文件的对象。通过lines属性获取代码行数组。然后遍历代码行找到style节点,判断是否有scoped属性。

规则怎样加入检查器

  1. 注册新规则
    在node_modules\eslint-plugin-vue\lib\index.js文件中返回对象的rules属性中添加'style-scoped': require('./rules/style-scoped')

  2. 为规则指定分类
    在node_modules\eslint-plugin-vue\lib目录中找到分类名称文件,比如essential.js,在里面添加该规则'vue/style-scoped': 'error'

注意:此规则是在eslint-plugin-vue插件里添加的,如果只是直接在eslint里添加,则不需要执行上述操作

eslint配置

这里是在vue工程里使用eslint-plugin-vue插件的相关配置

module.exports = {
  root: true,
  parserOptions: {
    parser: "babel-eslint",
    sourceType: 'module'
  },
  env: {
    browser: true,
  },
  extends: [
    "plugin:vue/essential"
  ],
  plugins: [
    'vue'
  ],
  'rules': { }
}

参考资料

https://vue-loader.vuejs.org/zh/guide/linting.html#eslint
https://cn.eslint.org/docs/developer-guide/working-with-plugins
https://github.com/estree/estree/blob/master/es2015.md

相关文章

网友评论

    本文标题:手把手教你如何扩展eslint的检查规则

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