手把手教你——如何擴展eslint的檢查規(guī)則

本文介紹了擴展eslint檢查規(guī)則具體方法。下面我們就以一個具體的檢查規(guī)則實例來介紹下擴展檢查規(guī)則的具體方法。

規(guī)則說明

新增規(guī)則需要檢查vue文件中的style元素必須要加上scoped屬性,否則就要報異常。

如何定義規(guī)則

在node_modules\eslint-plugin-vue\lib\rules文件夾中增加一個新規(guī)則文件。示例代碼如下:

'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. 每個規(guī)則都是一個對象,使用module.exports導出該規(guī)則對象
  2. 該對象必須包含兩個屬性meta對象和create函數(shù)
  3. meta屬性是一個對象,定義了該規(guī)則的相關定義,例如:
    docs是對規(guī)則的描述信息,包括規(guī)則含義,所屬分類,規(guī)則說明url等;
    fixable用來定義如何自動修復;
    schema用來定義規(guī)則的開關配置;
  4. create方法返回一個對象,ESLint在遍歷代碼的抽象語法樹時調(diào)用相關的方法。屬性名稱對應由ESTree定義的AST類型。分別針對各種類型定義檢查方法。
  5. context是eslint的執(zhí)行環(huán)境。由于ATS里沒有CSS相關定義,這里使用了getSourceCode方法,獲取被檢查文件的對象。通過lines屬性獲取代碼行數(shù)組。然后遍歷代碼行找到style節(jié)點,判斷是否有scoped屬性。

規(guī)則怎樣加入檢查器

  1. 注冊新規(guī)則
    在node_modules\eslint-plugin-vue\lib\index.js文件中返回對象的rules屬性中添加'style-scoped': require('./rules/style-scoped')

  2. 為規(guī)則指定分類
    在node_modules\eslint-plugin-vue\lib目錄中找到分類名稱文件,比如essential.js,在里面添加該規(guī)則'vue/style-scoped': 'error'

注意:此規(guī)則是在eslint-plugin-vue插件里添加的,如果只是直接在eslint里添加,則不需要執(zhí)行上述操作

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

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容