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