開發eslint插件目的:根據項目須要,自定義知足項目特殊須要的校驗規則node
參考eslint官方文檔展開闡述git
下面開始經過一個示例demo來介紹插件整個開發流程github
代碼中出現的方法及變量的詳細解釋與相關文檔,會在文末給你們列舉出來,你們能夠先把代碼拷貝到本身的demo中而後結合本文第3部分
的變量|方法解釋去理解代碼npm
開發一個校驗註釋中是否包含指定關鍵詞的插件(
eslint-plugin-comments-key
)json
. ├── README.md 插件介紹文檔 ├── index.js 對外暴露插件 ├── lib │ └── rules 自定義規則 │ └── comments-key.js ├── package.json └── tests 測試自定義規則 └── lib └── rules └── comments-key.js
npm i eslint mocha -D
不包含自定義參數校驗規則api
/lib/rules/comments-key.js數組
module.exports = { meta: { type: "suggestion", docs: { description: "Not allowed comment words", // 規則的簡述 category: "Stylistic Issues", // 規則分類 recommended: true // 配置文件中的 "extends": "eslint:recommended"屬性是否啓用該規則 } }, create: function (context) { // context對象包含與規則上下文相關的信息 // 返回一個SourceCode對象,你可使用該對象處理傳遞給 ESLint 的源代碼 const sourceCode = context.getSourceCode() // 定義不被容許出如今註釋中的內容 const notAllowWords = ['fixme', 'xxx'] return { Program(node) { // 獲取全部註釋的節點 const comments = sourceCode.getAllComments() // 遍歷註釋節點判斷是否有不符合規範的 comments.forEach(comment => { let { loc, value, type } = comment value = value.toLowerCase() let warnWord = '' // 判斷註釋內容是否包含不被容許的word for (const word of notAllowWords) { if (value.includes(word)) { warnWord = word } } if (warnWord) { context.report({ node: comment, // 可選 與問題有關的 AST 節點 message: `註釋中含有不被容許的字符${warnWord}` // 有問題發出的消息 }) } }) } }; } };
/tests/lib/rules/comments-key.jsbash
const { RuleTester } = require('eslint') // 獲取自定義的規則 const rule = require('../../../lib/rules/comments-key') // TESTS // 加入默認配置 const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2018 } }) const errMsg = warnWord => `註釋中含有不被容許的字符${warnWord}` ruleTester.run('comments-key', rule, { valid: [ '// sssss', '// fixdddd', `/** * 容十三內水s是說 */` ], invalid: [ { code: "// fixme: DDL 2020-4-28 測試內容", errors: [{ message: errMsg('fixme') }] }, { code: "// FIXME: DDL 2020-5-23 測試內容", errors: [{ message: errMsg('fixme') }] }, { code: `/** * xxx * 內容 */`, errors: [{ message: errMsg('xxx') }] } ] })
加入編輯器
"scripts": { "test": "mocha tests/lib/rules" }
運行腳本查看測試結果ide
npm run test
上面的示例中限定的關鍵詞是在代碼中寫死了的
一般的場景中如:
rules:{ "quotes": ["error", "double"], // 只容許雙引號 "no-warning-comments": [ // 不容許註釋開頭出現 todo|fixme等內容 1, { "terms": [ "todo", "fixme" ], "location": "start" } ], }
大多數eslint規則都擁有可配置的屬性
咱們能夠經過context.options
獲取配置的屬性
下面示例加入可配置屬性,用於自定義關鍵詞的檢測(代碼中只包含修改部分,其他部分跟前面相同)
module.exports = { meta: { // ...code schema: [ // 指定該選項 這樣的 ESLint 能夠避免無效的規則配置 // 遵循 json schema 後文會有介紹文檔 { "keyWords": { "type": "array", "items": { "type": "string" } } } ] }, create: function (context) { // ...code // 定義不被容許出如今註釋中的內容 // 可使用 context.options檢索一個規則的可選項,它是個數組,包含該規則的全部配置的可選項 // console.log(context.options); // 取得設置的keywords let [argv0] = context.options let keyWords = argv0 ? argv0.keyWords ? argv0.keyWords.length > 0 ? argv0.keyWords : undefined : undefined : undefined // 沒有設置則使用默認的 let notAllowWords = keyWords || ['fixme', 'xxx'] // 忽略大小寫 notAllowWords = notAllowWords.map(v => v.toLowerCase()) // ...code } };
// ...code ruleTester.run('comments-key', rule, { valid: [ '// sssss', '// fixdddd', `/** * 容十三內水s是說 */` ], invalid: [ { code: "// fixme: DDL 2020-4-28 測試內容", errors: [{ message: errMsg('ddl') }], options: [{ // 經過options 配置自定義參數 keyWords: ['ddl'] }] }, { code: '// FIXME: DDL 2020-5-23 測試內容 \n let a = "232"', errors: [{ message: errMsg('fixme') }], rules: { // 經過rules 配置eslint提供的一些規則 "quotes": ["error", "double"], }, options: [{ keyWords: ['abc', 'efg', 'fixme'] }] }, { code: `/** * xxx * 內容 */`, errors: [{ message: errMsg('xxx') }] }, { code: '// abds asa', errors: [{ message: errMsg('abd') }], options: [{ keyWords: ['abc', 'abd'] }] } ] })
getSourceCode()
返回一個SourceCode對象,你可使用該對象處理傳遞給 ESLint 的源代碼
loc
註釋在文檔中的位置value
註釋中的內容type
註釋的類型 Block
|Line
message
有問題的消息提示node
(可選)與問題有關節點loc
(可選)用來指定問題位置的一個對象。若是同時指定的了 loc 和 node,那麼位置將從loc獲取而非nodedata
(可選) message的佔位符fix
(可選) 一個用來解決問題的修復函數tips:AST在開發插件時沒必要深刻研究,不一樣地方AST的實現和結構都有所差別
至此咱們的插件算開發完成了,接下來編寫對eslint暴露這個模塊的代碼
index.js
'use strict'; module.exports = { rules: { 'diy': require('./lib/rules/comments-key') }, rulesConfig: { 'diy': 1 } };
要在其它項目中使用的eslint-plugin插件的話,能夠把整個插件的根目錄拷貝到目標項目的node_modules中或者發佈到npm
中去,其它項目直接經過npm install
安裝這個依賴
下面介紹發佈到npm的步驟
直接點擊官網註冊
npm config set registry https://registry.npmjs.org/
npm login
按提示依次輸入帳號
,密碼
,郵箱
登陸完成以後,查看當前npm用戶,不報錯說明登陸成功
npm whoami
README.md
方便指引他人使用{ "name": "eslint-plugin-comments-key", "version": "1.0.0", "description": "校驗註釋中是否包含指定關鍵詞的插件", "main": "index.js", "directories": { "lib": "lib", "test": "tests" }, "scripts": { "test": "mocha tests/lib/rules" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "eslint": "^7.0.0", "mocha": "^7.1.2" } }
npm publish
發佈npm包至此發佈整個流程完畢
You'll first need to install ESLint:
$ npm i eslint --save-dev
Next, install eslint-plugin-comments-key
:
$ npm install eslint-plugin-comments-key --save-dev
Note: If you installed ESLint globally (using the -g
flag) then you must also install eslint-plugin-comments-key
globally.
Add comments-key
to the plugins section of your .eslintrc
configuration file or package.json
. You can omit the eslint-plugin-
prefix:
package.json
demo
"eslintConfig": { "plugins": [ "comments-key" ], "rules": { "comments-key/diy":[1,{ "wordKeys":["fixme","xxx"] }] } }
tips: 若是編輯器中安裝了Eslint插件,在編碼的時候就會給予警告⚠️
因筆者水平有限,內容上若有闡述不明白之處,還請斧正