eslint插件開發教程


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

參考eslint官方文檔展開闡述

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

代碼中出現的方法及變量的詳細解釋與相關文檔,會在文末給大家列舉出來,大家可以先把代碼拷貝到自己的demo中然后結合本文第3部分的變量|方法解釋去理解代碼

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

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. 開始編碼

編寫自定義規則

不包含自定義參數校驗規則

/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.js

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"
}

運行腳本查看測試結果

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相關地址

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM