版本

貢獻核心規則

ESLint 核心規則是包含在 ESLint 套件中的規則。

規則編寫文件

有關編寫規則的完整參考資訊,請參閱自訂規則。自訂規則和核心規則都具有相同的 API。核心規則和自訂規則之間的主要區別在於

  1. 核心規則包含在 eslint 套件中。
  2. 核心規則必須遵守此頁面上記錄的慣例。

檔案結構

ESLint 中的每個核心規則都有三個檔案,其名稱使用其識別碼(例如,no-extra-semi)。

  • lib/rules 目錄中:一個來源檔案(例如,no-extra-semi.js
  • tests/lib/rules 目錄中:一個測試檔案(例如,no-extra-semi.js
  • docs/src/rules 目錄中:一個 Markdown 文件(例如,no-extra-semi.md

重要:如果您向 ESLint 儲存庫提交核心規則,您必須遵守下面說明的慣例。

以下是規則來源檔案的基本格式

/**
 * @fileoverview Rule to disallow unnecessary semicolons
 * @author Nicholas C. Zakas
 */

"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "disallow unnecessary semicolons",
            recommended: true,
            url: "https://eslint.dev.org.tw/docs/rules/no-extra-semi"
        },
        fixable: "code",
        schema: [] // no options
    },
    create: function(context) {
        return {
            // callback functions
        };
    }
};

規則單元測試

每個 ESLint 核心的捆綁規則都必須提交一組單元測試才能被接受。測試檔案的名稱與來源檔案相同,但位於 tests/lib/ 中。例如,如果規則來源檔案是 lib/rules/foo.js,則測試檔案應為 tests/lib/rules/foo.js

ESLint 提供了 RuleTester 工具,讓您可以輕鬆地為規則編寫測試。

效能測試

為了保持程式碼檢查過程的效率且不干擾,驗證新規則或修改現有規則的效能影響會很有用。

若要了解如何分析個別規則的效能,請參閱自訂規則文件中的分析規則效能

在 ESLint 核心儲存庫中開發時,npm run perf 命令會提供啟用所有核心規則時 ESLint 執行時間的概觀。

$ git checkout main
Switched to branch 'main'

$ npm run perf
CPU Speed is 2200 with multiplier 7500000
Performance Run #1:  1394.689313ms
Performance Run #2:  1423.295351ms
Performance Run #3:  1385.09515ms
Performance Run #4:  1382.406982ms
Performance Run #5:  1409.68566ms
Performance budget ok:  1394.689313ms (limit: 3409.090909090909ms)

$ git checkout my-rule-branch
Switched to branch 'my-rule-branch'

$ npm run perf
CPU Speed is 2200 with multiplier 7500000
Performance Run #1:  1443.736547ms
Performance Run #2:  1419.193291ms
Performance Run #3:  1436.018228ms
Performance Run #4:  1473.605485ms
Performance Run #5:  1457.455283ms
Performance budget ok:  1443.736547ms (limit: 3409.090909090909ms)

規則命名慣例

ESLint 的規則命名慣例如下

  • 在單字之間使用破折號。
  • 如果您的規則僅禁止某件事,請在其前面加上 no-,例如 no-eval 表示禁止 eval(),而 no-debugger 表示禁止 debugger
  • 如果您的規則是強制包含某件事,請使用不帶特殊前綴的簡短名稱。
變更語言