eslint插件開發教程

開發eslint插件目的:根據項目須要,自定義知足項目特殊須要的校驗規則node

參考eslint官方文檔展開闡述git

下面開始經過一個示例demo來介紹插件整個開發流程github

代碼中出現的方法及變量的詳細解釋與相關文檔,會在文末給你們列舉出來,你們能夠先把代碼拷貝到本身的demo中而後結合本文第3部分的變量|方法解釋去理解代碼npm

開發一個校驗註釋中是否包含指定關鍵詞的插件(eslint-plugin-comments-key)json

1. 環境準備

目錄結構

.
├── README.md                   插件介紹文檔
├── index.js                    對外暴露插件
├── lib                         
│   └── rules                   自定義規則
│       └── comments-key.js     
├── package.json
└── tests                       測試自定義規則
    └── lib
        └── rules
            └── comments-key.js

安裝依賴

  • eslint
  • mocha
npm i eslint mocha -D

2. 開始編碼

編寫自定義規則

不包含自定義參數校驗規則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') }]
        }
    ]
})

修改package.json

加入編輯器

"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']
            }]
        }
    ]
})

3.文中一些變量|方法的解釋及其文檔

  • meta (object) 包含規則的元數據
    • schema 指定該選項 這樣的 ESLint 能夠避免無效的規則配置
  • create (function) 返回一個對象,其中包含了 ESLint 在遍歷 JavaScript 代碼的抽象語法樹 AST (ESTree 定義的 AST) 時,用來訪問節點的方法
    • context 包含與規則上下文相關的信息
      • options 檢索一個規則的可選項,它是個數組,包含該規則的全部配置的可選項
      • getSourceCode() 返回一個SourceCode對象,你可使用該對象處理傳遞給 ESLint 的源代碼
        • getAllComments() 獲取全部註釋節點
          • 每一個註釋節點的屬性
            • loc 註釋在文檔中的位置
            • value 註釋中的內容
            • type 註釋的類型 BlockLine
      • report() 它用來發布警告或錯誤(取決於你所使用的配置)。該方法只接收一個參數,是個對象
        • message 有問題的消息提示
        • node (可選)與問題有關節點
        • loc (可選)用來指定問題位置的一個對象。若是同時指定的了 loc 和 node,那麼位置將從loc獲取而非node
        • data (可選) message的佔位符
        • fix (可選) 一個用來解決問題的修復函數
  • RuleTester 單元測試示例介紹

tips:AST在開發插件時沒必要深刻研究,不一樣地方AST的實現和結構都有所差別

4.導出

至此咱們的插件算開發完成了,接下來編寫對eslint暴露這個模塊的代碼

index.js

'use strict';
module.exports = {
  rules: {
    'diy': require('./lib/rules/comments-key') 
  },
  rulesConfig: {
    'diy': 1
  }
};

5.發佈npm

要在其它項目中使用的eslint-plugin插件的話,能夠把整個插件的根目錄拷貝到目標項目的node_modules中或者發佈到npm中去,其它項目直接經過npm install 安裝這個依賴

下面介紹發佈到npm的步驟

  1. 註冊npm帳號(有的話直接跳過這步驟)

直接點擊官網註冊

  1. 設置登錄的帳號
    登陸以前修改registry爲原來的,由於國內通常用的鏡像源例如淘寶源:https://registry.npm.taobao.org
npm config set registry https://registry.npmjs.org/
npm login

按提示依次輸入帳號,密碼,郵箱

登陸完成以後,查看當前npm用戶,不報錯說明登陸成功

npm whoami
  1. 編寫README.md方便指引他人使用
  2. 修改packgae.json
{
  "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"
  }
}
  1. 運行npm publish發佈npm包

至此發佈整個流程完畢

6.項目中引入

Installation

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.

Usage

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插件,在編碼的時候就會給予警告⚠️

最後

eslint-plugin-comments-key相關地址

因筆者水平有限,內容上若有闡述不明白之處,還請斧正

相關文章
相關標籤/搜索