Node.js API 參考文件
雖然 ESLint 設計為在命令列上執行,但也可以透過 Node.js API 以程式化的方式使用 ESLint。Node.js API 的目的是讓外掛程式和工具作者可以直接使用 ESLint 功能,而無需透過命令列介面。
注意: 使用未記錄在文件中的 API 部分,風險自負。只有本文件中特別提及的部分才被核准使用,並將保持穩定和可靠。任何未記錄在文件中的內容都是不穩定的,可能會隨時變更或移除。
ESLint 類別
ESLint
類別是在 Node.js 應用程式中使用的主要類別。
此類別依賴 Node.js fs
模組和檔案系統,因此您無法在瀏覽器中使用它。如果您想在瀏覽器上檢查程式碼,請改用 Linter 類別。
以下是使用 ESLint
類別的簡單範例
const { ESLint } = require("eslint");
(async function main() {
// 1. Create an instance.
const eslint = new ESLint();
// 2. Lint files.
const results = await eslint.lintFiles(["lib/**/*.js"]);
// 3. Format the results.
const formatter = await eslint.loadFormatter("stylish");
const resultText = formatter.format(results);
// 4. Output it.
console.log(resultText);
})().catch((error) => {
process.exitCode = 1;
console.error(error);
});
以下是自動修正程式碼檢查問題的範例
const { ESLint } = require("eslint");
(async function main() {
// 1. Create an instance with the `fix` option.
const eslint = new ESLint({ fix: true });
// 2. Lint files. This doesn't modify target files.
const results = await eslint.lintFiles(["lib/**/*.js"]);
// 3. Modify the files with the fixed code.
await ESLint.outputFixes(results);
// 4. Format the results.
const formatter = await eslint.loadFormatter("stylish");
const resultText = formatter.format(results);
// 5. Output it.
console.log(resultText);
})().catch((error) => {
process.exitCode = 1;
console.error(error);
});
以下是使用 ESLint
類別與 lintText
API 的範例
const { ESLint } = require("eslint");
const testCode = `
const name = "eslint";
if(true) {
console.log("constant condition warning")
};
`;
(async function main() {
// 1. Create an instance
const eslint = new ESLint({
overrideConfigFile: true,
overrideConfig: {
languageOptions: {
ecmaVersion: 2018,
sourceType: "commonjs"
}
},
});
// 2. Lint text.
const results = await eslint.lintText(testCode);
// 3. Format the results.
const formatter = await eslint.loadFormatter("stylish");
const resultText = formatter.format(results);
// 4. Output it.
console.log(resultText);
})().catch((error) => {
process.exitCode = 1;
console.error(error);
});
◆ new ESLint(options)
const eslint = new ESLint(options);
建立新的 ESLint
實例。
參數
ESLint
建構子接受一個 options
物件。如果您省略 options
物件,則會為所有選項使用預設值。options
物件具有以下屬性。
檔案列舉
options.cwd
(string
)
預設值為process.cwd()
。工作目錄。這必須是絕對路徑。options.errorOnUnmatchedPattern
(boolean
)
預設值為true
。除非設定為false
,否則當找不到目標檔案時,eslint.lintFiles()
方法將會拋出錯誤。options.globInputPaths
(boolean
)
預設值為true
。如果存在false
,則eslint.lintFiles()
方法不會解譯 glob 模式。options.ignore
(boolean
)
預設值為true
。如果存在false
,則eslint.lintFiles()
方法不會遵守您設定中的ignorePatterns
。options.ignorePatterns
(string[] | null
)
預設值為null
。除了設定忽略之外,還要使用的忽略檔案模式。這些模式相對於cwd
。options.passOnNoPatterns
(boolean
)
預設值為false
。當設定為true
時,遺失的模式會導致程式碼檢查操作短路,且不回報任何失敗。options.warnIgnored
(boolean
)
預設值為true
。當檔案清單包含被忽略的檔案時,顯示警告。
程式碼檢查
options.allowInlineConfig
(boolean
)
預設值為true
。如果存在false
,ESLint 會抑制原始碼中的指示詞註解。如果此選項為false
,它會覆寫您設定中的noInlineConfig
設定。options.baseConfig
(ConfigData | ConfigData[] | null
)
預設值為null
。設定物件,由與此實例一起使用的所有設定擴充。您可以使用此選項來定義預設設定,如果您的設定檔未設定,則將使用這些預設設定。options.overrideConfig
(ConfigData | ConfigData[] | null
)
預設值為null
。設定物件,在任何現有設定之後新增,因此在您的設定檔(如果使用)中包含的內容之後套用。options.overrideConfigFile
(null | true | string
)
預設值為null
。依預設,ESLint 會搜尋設定檔。當此選項設定為true
時,ESLint 不會搜尋設定檔。當此選項設定為string
值時,ESLint 不會搜尋設定檔,並使用提供的值作為設定檔的路徑。options.plugins
(Record<string, Plugin> | null
)
預設值為null
。ESLint 用於您設定的plugins
設定的外掛程式實作。這是一個類似 map 的物件。這些鍵是外掛程式 ID,每個值都是實作。options.ruleFilter
(({ruleId: string, severity: number}) => boolean
)
預設值為() => true
。篩選要執行的規則的述詞函式。此函式使用包含ruleId
和severity
的物件呼叫,如果應執行規則,則傳回true
。options.stats
(boolean
)
預設值為false
。當設定為true
時,額外的統計資訊會新增至程式碼檢查結果(請參閱 Stats 型別)。
自動修正
options.fix
(boolean | (message: LintMessage) => boolean
)
預設值為false
。如果存在true
,則eslint.lintFiles()
和eslint.lintText()
方法在自動修正模式下運作。如果存在述詞函式,則方法會將每個程式碼檢查訊息傳遞給函式,然後僅使用函式傳回true
的程式碼檢查訊息。options.fixTypes
(("directive" | "problem" | "suggestion" | "layout")[] | null
)
預設值為null
。eslint.lintFiles()
和eslint.lintText()
方法用於自動修正的規則型別。
快取相關
options.cache
(boolean
)
預設值為false
。如果存在true
,則eslint.lintFiles()
方法會快取程式碼檢查結果,並在每個目標檔案未變更時使用它。請注意,當您升級 ESLint 外掛程式時,ESLint 不會清除快取。在這種情況下,您必須手動移除快取檔案。eslint.lintText()
方法即使您將options.filePath
傳遞給該方法,也不會使用快取。options.cacheLocation
(string
)
預設值為.eslintcache
。eslint.lintFiles()
方法將快取寫入此檔案。options.cacheStrategy
(string
)
預設值為"metadata"
。快取用於偵測已變更檔案的策略。可以是"metadata"
或"content"
。
其他選項
options.flags
(string[]
)
預設值為[]
。要為此實例啟用的功能旗標。
◆ eslint.lintFiles(patterns)
const results = await eslint.lintFiles(patterns);
此方法檢查符合 glob 模式的檔案,然後傳回結果。
參數
patterns
(string | string[]
)
程式碼檢查目標檔案。這可以包含任何檔案路徑、目錄路徑和 glob 模式。
回傳值
- (
Promise<LintResult[]>
)
將以 LintResult 物件陣列實現的 Promise。
◆ eslint.lintText(code, options)
const results = await eslint.lintText(code, options);
此方法檢查給定的原始碼文字,然後傳回結果。
依預設,此方法使用適用於目前工作目錄(cwd
建構子選項)中檔案的設定。如果您想使用不同的設定,請傳遞 options.filePath
,ESLint 將載入與 eslint.lintFiles()
對於 options.filePath
檔案會使用的相同設定。
如果 options.filePath
值設定為忽略,此方法會傳回空陣列。如果 options.warnIgnored
選項與 options.filePath
選項一起設定,此方法會傳回 LintResult 物件。在這種情況下,結果可能包含警告,指出檔案被忽略。
參數
第二個參數 options
是可省略的。
code
(string
)
要檢查的原始碼文字。options.filePath
(string
)
選用。原始碼文字的檔案路徑。如果省略,result.filePath
會變成字串"<text>"
。options.warnIgnored
(boolean
)
選用,預設為傳遞給建構子的options.warnIgnored
。如果存在true
且options.filePath
是 ESLint 應忽略的檔案,則此方法會傳回包含警告訊息的程式碼檢查結果。
回傳值
- (
Promise<LintResult[]>
)
將以 LintResult 物件陣列實現的 Promise。這是一個陣列(儘管只有一個程式碼檢查結果),目的是保持此方法與eslint.lintFiles()
方法之間的介面相似。
◆ eslint.getRulesMetaForResults(results)
const results = await eslint.lintFiles(patterns);
const rulesMeta = eslint.getRulesMetaForResults(results);
此方法傳回一個物件,其中包含給定 results
中觸發程式碼檢查錯誤的每個規則的中繼資訊。
參數
results
(LintResult[]
)
從呼叫ESLint#lintFiles()
或ESLint#lintText()
傳回的 LintResult 物件陣列。
回傳值
- (
Object
)
物件,其屬性名稱是來自results
的規則 ID,其屬性值是規則的中繼資訊(如果可用)。
◆ eslint.calculateConfigForFile(filePath)
const config = await eslint.calculateConfigForFile(filePath);
此方法計算給定檔案的設定,這對於偵錯目的非常有用。
參數
filePath
(string
)
您想要計算其設定的檔案路徑。禁止目錄路徑,因為 ESLint 無法處理overrides
設定。
回傳值
- (
Promise<Object>
)
將以設定物件實現的 Promise。
◆ eslint.isPathIgnored(filePath)
const isPathIgnored = await eslint.isPathIgnored(filePath);
此方法檢查給定檔案是否被您的設定忽略。
參數
filePath
(string
)
您要檢查的檔案路徑。
回傳值
- (
Promise<boolean>
)
將以檔案是否被忽略實現的 Promise。如果檔案被忽略,則會傳回true
。
◆ eslint.loadFormatter(nameOrPath)
const formatter = await eslint.loadFormatter(nameOrPath);
此方法載入格式器。格式器將程式碼檢查結果轉換為人類或機器可讀的字串。
參數
nameOrPath
(string | undefined
)
您要檢查的檔案路徑。允許以下值
回傳值
- (
Promise<LoadedFormatter>
)
將以 LoadedFormatter 物件實現的 Promise。
◆ eslint.hasFlag(flagName)
此方法用於判斷是否設定了給定的功能旗標,如此範例所示
if (eslint.hasFlag("x_feature")) {
// handle flag
}
參數
flagName
(string
)
要檢查的旗標。
回傳值
- (
boolean
)
如果已啟用旗標,則為 True。
◆ ESLint.version
const version = ESLint.version;
ESLint 的版本字串。例如 "7.0.0"
。
這是一個靜態屬性。
◆ ESLint.defaultConfig
const defaultConfig = ESLint.defaultConfig;
ESLint 內部使用的預設設定。這是為想要使用與 ESLint 相同預設值計算設定的工具提供的。請記住,預設設定可能會因版本而異,因此您不應依賴任何特定的鍵或值是否存在。
這是一個靜態屬性。
◆ ESLint.outputFixes(results)
await ESLint.outputFixes(results);
此方法將 ESLint 的自動修正功能修改的程式碼寫入其各自的檔案中。如果任何修改的檔案不存在,此方法不會執行任何操作。
這是一個靜態方法。
參數
results
(LintResult[]
)
要寫入的 LintResult 物件。
回傳值
- (
Promise<void>
)
所有檔案寫入後將實現的 Promise。
◆ ESLint.getErrorResults(results)
const filteredResults = ESLint.getErrorResults(results);
此方法複製給定的結果並移除警告。傳回的值僅包含錯誤。
這是一個靜態方法。
參數
results
(LintResult[]
)
要篩選的 LintResult 物件。
回傳值
- (
LintResult[]
)
篩選後的 LintResult 物件。
◆ LintResult 型別
LintResult
值是每個檔案的程式碼檢查結果資訊。eslint.lintFiles()
和 eslint.lintText()
方法會傳回它。它具有以下屬性
filePath
(string
)
此結果檔案的絕對路徑。如果檔案路徑未知(當您未將options.filePath
選項傳遞給eslint.lintText()
方法時),則這是字串"<text>"
。messages
(LintMessage[]
)
LintMessage 物件的陣列。suppressedMessages
(SuppressedLintMessage[]
)
SuppressedLintMessage 物件的陣列。fixableErrorCount
(number
)
可以使用fix
建構子選項自動修正的錯誤數。fixableWarningCount
(number
)
可以使用fix
建構子選項自動修正的警告數。errorCount
(number
)
錯誤數。這包括可修正的錯誤和嚴重錯誤。fatalErrorCount
(number
)
嚴重錯誤數。warningCount
(number
)
警告數。這包括可修正的警告。output
(string | undefined
)
修改後的原始碼文字。如果任何可修正的訊息不存在,則此屬性為 undefined。source
(string | undefined
)
原始原始碼文字。如果任何訊息不存在或output
屬性存在,則此屬性為 undefined。stats
(Stats | undefined
)
Stats 物件。這包含使用stats
選項收集的程式碼檢查效能統計資訊。usedDeprecatedRules
({ ruleId: string; replacedBy: string[]; info: DeprecatedInfo | undefined }[]
)
有關用於檢查此檔案的已棄用規則的資訊。如果規則使用新的deprecated
屬性,則info
屬性會設定為rule.meta.deprecated
。
◆ LintMessage 型別
LintMessage
值是每個程式碼檢查錯誤的資訊。LintResult 型別的 messages
屬性包含它。它具有以下屬性
ruleId
(string
|null
)
產生此程式碼檢查訊息的規則名稱。如果此訊息是由 ESLint 核心而非規則產生的,則為null
。severity
(1 | 2
)
此訊息的嚴重性。1
表示警告,2
表示錯誤。fatal
(boolean | undefined
)
如果這是與規則無關的嚴重錯誤,例如剖析錯誤,則為true
。message
(string
)
錯誤訊息。messageId
(string | undefined
)
程式碼檢查錯誤的訊息 ID。如果規則未使用訊息 ID,則此屬性為 undefined。line
(number | undefined
)
此訊息起點的從 1 開始的行號。column
(number | undefined
)
此訊息起點的從 1 開始的欄號。endLine
(number | undefined
)
此訊息終點的從 1 開始的行號。如果此訊息不是範圍,則此屬性為 undefined。endColumn
(number | undefined
)
此訊息終點的從 1 開始的欄號。如果此訊息不是範圍,則此屬性為 undefined。fix
(EditInfo | undefined
)
EditInfo 自動修正物件。如果此訊息不可修正,則此屬性為 undefined。suggestions
({ desc: string; fix: EditInfo; messageId?: string; data?: object }[] | undefined
)
建議清單。每個建議都是描述和 EditInfo 物件的配對,用於修正程式碼。API 使用者(例如編輯器整合)可以選擇其中一個來修正此訊息的問題。如果此訊息沒有任何建議,則此屬性為 undefined。
◆ SuppressedLintMessage 型別
SuppressedLintMessage
值是每個已抑制的程式碼檢查錯誤的資訊。LintResult 型別的 suppressedMessages
屬性包含它。它具有以下屬性
ruleId
(string
|null
)
與 LintMessage 型別中的ruleId
相同。severity
(1 | 2
)
與 LintMessage 型別中的severity
相同。fatal
(boolean | undefined
)
與 LintMessage 型別中的fatal
相同。message
(string
)
與 LintMessage 型別中的message
相同。messageId
(string | undefined
)
與 LintMessage 型別中的messageId
相同。line
(number | undefined
)
與 LintMessage 型別中的line
相同。column
(number | undefined
)
與 LintMessage 型別中的column
相同。endLine
(number | undefined
)
與 LintMessage 型別中的endLine
相同。endColumn
(number | undefined
)
與 LintMessage 型別中的endColumn
相同。fix
(EditInfo | undefined
)
與 LintMessage 型別中的fix
相同。suggestions
({ desc: string; fix: EditInfo; messageId?: string; data?: object }[] | undefined
)
與 LintMessage 型別中的suggestions
相同。suppressions
({ kind: string; justification: string}[]
)
抑制清單。每個抑制都是種類和理由的配對。
◆ EditInfo 型別
EditInfo
值是編輯文字的資訊。LintMessage 型別的 fix
和 suggestions
屬性包含它。它具有以下屬性
range
([number, number]
)
要移除的原始碼文字中從 0 開始的索引配對。text
(string
)
要新增的文字。
此編輯資訊表示將 range
屬性的範圍替換為 text
屬性值。它類似於 sourceCodeText.slice(0, edit.range[0]) + edit.text + sourceCodeText.slice(edit.range[1])
。因此,如果 range[0]
和 range[1]
屬性值相同,則為新增,如果 text
屬性值為空字串,則為移除。
◆ LoadedFormatter 型別
LoadedFormatter
值是將 LintResult 物件轉換為文字的物件。eslint.loadFormatter() 方法會傳回它。它具有以下方法
format
((results: LintResult[], resultsMeta?: ResultsMeta) => string | Promise<string>
)
將 LintResult 物件轉換為文字的方法。resultsMeta
是一個選用參數,主要供 ESLint CLI 使用,並且只能包含一個maxWarningsExceeded
屬性,該屬性將在context
物件呼叫基礎格式器函式時傳遞。請注意,ESLint 會自動產生context
物件的cwd
和rulesMeta
屬性,因此您通常在呼叫此方法時不需要傳遞第二個引數。
loadESLint()
loadESLint()
函式用於希望同時支援目前設定系統(扁平化設定)和舊設定系統(eslintrc)的整合。此函式會根據提供的引數傳回正確的 ESLint
類別實作
const { loadESLint } = require("eslint");
// loads the default ESLint that the CLI would use based on process.cwd()
const DefaultESLint = await loadESLint();
// loads the flat config version specifically
const FlatESLint = await loadESLint({ useFlatConfig: true });
// loads the legacy version specifically
const LegacyESLint = await loadESLint({ useFlatConfig: false });
然後,您可以使用傳回的建構子來實例化新的 ESLint
實例,如下所示
// loads the default ESLint that the CLI would use based on process.cwd()
const DefaultESLint = await loadESLint();
const eslint = new DefaultESLint();
如果您不確定傳回的建構子使用哪個設定系統,請檢查 configType
屬性,它不是 "flat"
就是 "eslintrc"
// loads the default ESLint that the CLI would use based on process.cwd()
const DefaultESLint = await loadESLint();
if (DefaultESLint.configType === "flat") {
// do something specific to flat config
}
如果您不需要同時支援舊設定系統和新設定系統,建議直接使用 ESLint
建構子。
SourceCode
SourceCode
型別代表 ESLint 在其上執行的已剖析原始碼。它在 ESLint 內部使用,也可供使用已剖析的程式碼。您可以透過傳遞代表程式碼的文字字串和 ESTree 格式的抽象語法樹狀結構 (AST)(包括位置資訊、範圍資訊、註解和 token)來建立 SourceCode
的新實例
const SourceCode = require("eslint").SourceCode;
const code = new SourceCode("var foo = bar;", ast);
如果 AST 缺少任何必要資訊,SourceCode
建構子會拋出錯誤。
SourceCode
建構子會移除 Unicode BOM。請注意,AST 也應從移除 BOM 的文字中剖析。
const SourceCode = require("eslint").SourceCode;
const code = new SourceCode("\uFEFFvar foo = bar;", ast);
assert(code.hasBOM === true);
assert(code.text === "var foo = bar;");
SourceCode#splitLines()
這是 SourceCode
上的靜態函式,用於將原始碼文字分割成行陣列。
const SourceCode = require("eslint").SourceCode;
const code = "var a = 1;\nvar b = 2;"
// split code into an array
const codeLines = SourceCode.splitLines(code);
/*
Value of codeLines will be
[
"var a = 1;",
"var b = 2;"
]
*/
Linter
Linter
物件執行 JavaScript 程式碼的實際評估。它不執行任何檔案系統操作,它只會剖析並回報程式碼。特別是,Linter
物件不處理設定檔。除非您在瀏覽器中工作,否則您可能想要改用 ESLint 類別。
Linter
是一個建構子,您可以透過傳遞您想要使用的選項來建立新的實例。可用的選項為
cwd
- 應視為目前工作目錄的目錄路徑。規則可以從context.cwd
或透過呼叫context.getCwd()
存取(請參閱 Context 物件)。如果cwd
為undefined
,如果定義了全域process
物件(例如,在 Node.js 執行階段),則會將其正規化為process.cwd()
,否則為undefined
。
例如
const Linter = require("eslint").Linter;
const linter1 = new Linter({ cwd: 'path/to/project' });
const linter2 = new Linter();
在此範例中,在 linter1
上執行的規則將從 context.cwd
或在呼叫 context.getCwd()
時取得 path/to/project
。在 linter2
上執行的規則將在定義了全域 process
物件時取得 process.cwd()
,否則取得 undefined
(例如,在瀏覽器 https://eslint.dev.org.tw/demo 上)。
Linter#verify
Linter
上最重要的函式是 verify()
,它會啟動給定文字的程式碼檢查。此方法接受三個引數
code
- 要檢查的原始碼(字串或SourceCode
的實例)。config
- 設定物件或設定物件陣列。- 注意:如果您想要檢查文字並讓您的設定從檔案系統讀取,請改用
ESLint#lintFiles()
或ESLint#lintText()
。
- 注意:如果您想要檢查文字並讓您的設定從檔案系統讀取,請改用
options
- (選用)此執行的其他選項。filename
- (選用)要與原始碼關聯的檔案名稱。preprocess
- (選用)外掛程式中的處理器 文件將其描述為preprocess
方法的函式。postprocess
- (選用)外掛程式中的處理器 文件將其描述為postprocess
方法的函式。filterCodeBlock
- (選用)決定程式碼檢查器應採用哪些程式碼區塊的函式。該函式接收兩個引數。第一個引數是程式碼區塊的虛擬檔案名稱。第二個引數是程式碼區塊的文字。如果函式傳回true
,則程式碼檢查器會採用程式碼區塊。如果省略了函式,則程式碼檢查器僅採用*.js
程式碼區塊。如果您提供了filterCodeBlock
函式,它會覆寫此預設行為,因此程式碼檢查器不會自動採用*.js
程式碼區塊。disableFixes
- (選用)設定為true
時,程式碼檢查器不會建立程式碼檢查結果的fix
或suggestions
屬性。allowInlineConfig
- (選用)設定為false
以停用來自變更 ESLint 規則的行內註解。reportUnusedDisableDirectives
- (選用)當設定為true
時,當在停用區域中不會回報任何問題時,會為未使用的eslint-disable
和eslint-enable
指示詞新增回報的錯誤。ruleFilter
- (選用)決定應執行哪些規則的函式述詞。它接收一個包含ruleId
和severity
的物件,如果應執行規則,則傳回true
。
如果第三個引數是字串,則會將其解譯為 filename
。
您可以像這樣呼叫 verify()
const Linter = require("eslint").Linter;
const linter = new Linter();
const messages = linter.verify("var foo;", {
rules: {
semi: 2
}
}, { filename: "foo.js" });
// or using SourceCode
const Linter = require("eslint").Linter,
linter = new Linter(),
SourceCode = require("eslint").SourceCode;
const code = new SourceCode("var foo = bar;", ast);
const messages = linter.verify(code, {
rules: {
semi: 2
}
}, { filename: "foo.js" });
verify()
方法傳回物件陣列,其中包含有關程式碼檢查警告和錯誤的資訊。以下是一個範例
[
{
fatal: false,
ruleId: "semi",
severity: 2,
line: 1,
column: 23,
message: "Expected a semicolon.",
fix: {
range: [1, 15],
text: ";"
}
}
]
每個程式碼檢查訊息可用的資訊為
column
- 發生錯誤的欄。fatal
- 通常省略,但如果存在剖析錯誤(與規則無關),則會設定為 true。line
- 發生錯誤的行。message
- 應輸出的訊息。messageId
- 用於產生訊息的訊息 ID(如果規則未使用訊息 ID,則會省略此屬性)。nodeType
- (已棄用: 此屬性將在未來版本的 ESLint 中移除。)使用問題回報的節點或 token 型別。ruleId
- 觸發訊息的規則 ID(如果fatal
為 true,則為 null)。severity
- 1 或 2,取決於您的設定。endColumn
- 發生錯誤的範圍的結束欄(如果不是範圍,則會省略此屬性)。endLine
- 發生錯誤的範圍的結束行(如果不是範圍,則會省略此屬性)。fix
- 描述問題修正的物件(如果沒有可用的修正,則會省略此屬性)。suggestions
- 描述編輯器以程式化方式啟用可能的程式碼修正的物件陣列(請參閱 規則文件 中的詳細資訊)。
您可以從先前的執行中透過 getSuppressedMessages()
方法取得已抑制的訊息。如果沒有先前的執行,getSuppressedMessage()
將會傳回空清單。
const Linter = require("eslint").Linter;
const linter = new Linter();
const messages = linter.verify("var foo = bar; // eslint-disable-line -- Need to suppress", {
rules: {
semi: ["error", "never"]
}
}, { filename: "foo.js" });
const suppressedMessages = linter.getSuppressedMessages();
console.log(suppressedMessages[0].suppressions); // [{ "kind": "directive", "justification": "Need to suppress" }]
您也可以使用 getSourceCode()
方法取得 linter
內部使用的 SourceCode
物件的實例
const Linter = require("eslint").Linter;
const linter = new Linter();
const messages = linter.verify("var foo = bar;", {
rules: {
semi: 2
}
}, { filename: "foo.js" });
const code = linter.getSourceCode();
console.log(code.text); // "var foo = bar;"
如此一來,您可以取回上次執行 linter.verify()
時使用的文字和 AST。
Linter#verifyAndFix()
此方法與 verify 類似,不同之處在於它還會執行自動修正邏輯,類似於命令列上的 --fix
標誌。結果物件將包含自動修正後的程式碼,以及程式碼中任何未自動修正的剩餘 lint 訊息。
const Linter = require("eslint").Linter;
const linter = new Linter();
const messages = linter.verifyAndFix("var foo", {
rules: {
semi: 2
}
});
此方法的輸出物件
{
fixed: true,
output: "var foo;",
messages: []
}
可用的資訊如下
fixed
- 若程式碼已修正,則為 True。output
- 已修正的程式碼文字 (若未套用修正,則可能與輸入相同)。messages
- 給定程式碼的所有訊息集合 (它具有與上方verify
區塊下說明的相同資訊)。
Linter#version/Linter.version
Linter
的每個實例都有一個 version
屬性,其中包含該 Linter
實例來自的 ESLint 的語意版本號碼。
const Linter = require("eslint").Linter;
const linter = new Linter();
linter.version; // => '9.0.0'
還有一個 Linter.version
屬性,您無需實例化 Linter
即可讀取
const Linter = require("eslint").Linter;
Linter.version; // => '9.0.0'
Linter#getTimes()
此方法用於取得檔案花費的時間 (解析、修正、linting)。請參閱 Stats 物件的 times
屬性。
Linter#getFixPassCount()
此方法用於取得自動修正通過的次數。請參閱 Stats 物件的 fixPasses
屬性。
Linter#hasFlag()
此方法用於判斷是否設定了給定的功能旗標,如此範例所示
const Linter = require("eslint").Linter;
const linter = new Linter({ flags: ["x_feature"] });
console.log(linter.hasFlag("x_feature")); // true
RuleTester
eslint.RuleTester
是一個用於撰寫 ESLint 規則測試的工具。它在內部用於 ESLint 捆綁的規則,並且也可以由外掛程式使用。
使用範例
"use strict";
const rule = require("../../../lib/rules/my-rule"),
RuleTester = require("eslint").RuleTester;
const ruleTester = new RuleTester();
ruleTester.run("my-rule", rule, {
valid: [
{
code: "var foo = true",
options: [{ allowFoo: true }]
}
],
invalid: [
{
code: "var invalidVariable = true",
errors: [{ message: "Unexpected invalid variable." }]
},
{
code: "var invalidVariable = true",
errors: [{ message: /^Unexpected.+variable/ }]
}
]
});
RuleTester
建構子接受一個可選的物件引數,可用於為您的測試案例指定預設值。例如,如果您的所有測試案例都使用 ES2015,您可以將其設定為預設值
const ruleTester = new RuleTester({ languageOptions: { ecmaVersion: 2015 } });
RuleTester#run()
方法用於執行測試。它應傳遞以下引數
- 規則的名稱 (字串)。
- 規則物件本身 (請參閱 「使用規則」)。
- 一個包含
valid
和invalid
屬性的物件,每個屬性都是一個包含測試案例的陣列。
測試案例是一個具有以下屬性的物件
name
(字串,可選):用於測試案例的名稱,以便更容易找到。code
(字串,必填):應在其上執行規則的原始程式碼。options
(陣列,可選):傳遞給規則的選項。規則嚴重性不應包含在此列表中。before
(函式,可選):在測試案例之前執行的函式。after
(函式,可選):在測試案例之後執行的函式,無論其結果如何。filename
(字串,可選):給定案例的檔案名稱 (對於對檔案名稱進行斷言的規則很有用)。only
(布林值,可選):在支援的測試框架中獨佔執行此案例以進行偵錯。
除了上述屬性之外,無效的測試案例還可以具有以下屬性
-
errors
(數字或陣列,必填):斷言在此程式碼上執行規則時預期產生的錯誤的某些屬性。如果這是數字,則斷言產生的錯誤數量。否則,這應該是一個物件列表,每個物件都包含有關單個報告錯誤的資訊。以下屬性可用於錯誤 (除非另有說明,否則均為可選)message
(字串/正規表示式):錯誤的訊息。必須提供此項或messageId
。messageId
(字串):錯誤的 ID。必須提供此項或message
。有關詳細資訊,請參閱 使用 messageId 測試錯誤。data
(物件):佔位符資料,可以與messageId
結合使用。type
(字串):(已棄用: 此屬性將在未來版本的 ESLint 中移除。) 報告的 AST 節點的類型。line
(數字):報告位置的從 1 開始的行號。column
(數字):報告位置的從 1 開始的欄號。endLine
(數字):報告位置結束的從 1 開始的行號。endColumn
(數字):報告位置結束的從 1 開始的欄號。suggestions
(陣列):包含建議詳細資訊的物件陣列,用於檢查。如果規則產生建議,則為必填。有關詳細資訊,請參閱 測試建議。
如果提供字串作為錯誤而不是物件,則該字串將用於斷言錯誤的
message
。 -
output
(字串,如果規則修正程式碼則為必填):斷言使用此規則進行單次自動修正 (例如,使用--fix
命令列標誌) 時將產生的輸出。如果這是null
或省略,則斷言沒有任何報告的問題建議自動修正。
測試案例的任何其他屬性都將直接作為配置選項傳遞給 linter。例如,測試案例可以具有 languageOptions
屬性來配置解析器行為
{
code: "let foo;",
languageOptions: { ecmaVersion: 2015 }
}
如果有效的測試案例僅使用 code
屬性,則可以選擇性地將其作為包含程式碼的字串提供,而不是具有 code
鍵的物件。
使用 messageId
測試錯誤
如果受測規則使用 messageId
,您可以使用測試案例中的 messageId
屬性來斷言報告錯誤的 messageId
,而不是其 message
。
{
code: "let foo;",
errors: [{ messageId: "unexpected" }]
}
對於帶有佔位符的訊息,測試案例也可以使用 data
屬性來額外斷言報告錯誤的 message
。
{
code: "let foo;",
errors: [{ messageId: "unexpected", data: { name: "foo" } }]
}
請注意,測試案例中的 data
不會斷言傳遞給 context.report
的 data
。相反,它用於形成預期的訊息文字,然後將其與收到的 message
進行比較。
測試修正
套用修正的結果可以使用無效測試案例的 output
屬性進行測試。只有當您期望對指定的 code
套用修正時,才應使用 output
屬性;如果預期程式碼不會變更,您可以安全地省略 output
。這是一個範例
ruleTester.run("my-rule-for-no-foo", rule, {
valid: [],
invalid: [{
code: "var foo;",
output: "var bar;",
errors: [{
messageId: "shouldBeBar",
line: 1,
column: 5
}]
}]
})
在此無效測試案例的結尾,RuleTester
預期會套用修正,導致程式碼從 var foo;
變更為 var bar;
。如果套用修正後的輸出不匹配,則測試失敗。
測試建議
可以通過在 errors 物件上定義 suggestions
鍵來測試建議。如果這是數字,則斷言為該錯誤提供的建議數量。否則,這應該是一個物件陣列,每個物件都包含有關單個提供的建議的資訊。可以使用以下屬性
desc
(字串):建議的desc
值。必須提供此項或messageId
。messageId
(字串):用於使用messageId
的建議的建議messageId
值。必須提供此項或desc
。data
(物件):佔位符資料,可以與messageId
結合使用。output
(字串,必填):表示將建議修正應用於輸入程式碼的結果的程式碼字串。
範例
ruleTester.run("my-rule-for-no-foo", rule, {
valid: [],
invalid: [{
code: "var foo;",
errors: [{
suggestions: [{
desc: "Rename identifier 'foo' to 'bar'",
output: "var bar;"
}]
}]
}]
})
建議測試物件中的 messageId
和 data
屬性的運作方式與錯誤測試物件中的相同。有關詳細資訊,請參閱 使用 messageId 測試錯誤。
ruleTester.run("my-rule-for-no-foo", rule, {
valid: [],
invalid: [{
code: "var foo;",
errors: [{
suggestions: [{
messageId: "renameFoo",
data: { newName: "bar" },
output: "var bar;"
}]
}]
}]
})
自訂 RuleTester
RuleTester
依賴兩個函式來執行測試:describe
和 it
。這些函式可以來自不同的位置
-
如果
RuleTester.describe
和RuleTester.it
已設定為函式值,則RuleTester
將使用RuleTester.describe
和RuleTester.it
來執行測試。您可以使用此功能自訂RuleTester
的行為,以符合您正在使用的測試框架。如果
RuleTester.itOnly
已設定為函式值,則RuleTester
將呼叫RuleTester.itOnly
而不是RuleTester.it
來執行具有only: true
的案例。如果未設定RuleTester.itOnly
,但RuleTester.it
具有only
函式屬性,則RuleTester
將回退到RuleTester.it.only
。 -
否則,如果
describe
和it
作為全域變數存在,則RuleTester
將使用globalThis.describe
和globalThis.it
來執行測試,並使用globalThis.it.only
來執行具有only: true
的案例。這允許RuleTester
在使用 Mocha 等框架時無需任何額外配置即可運作。 -
否則,
RuleTester#run
將僅按順序執行所有測試,並且如果其中一個測試失敗,則會拋出錯誤。這表示您只需使用Node.js
執行呼叫RuleTester.run
的測試檔案,而無需測試框架。
RuleTester#run
使用兩個引數呼叫 describe
函式:描述規則的字串和回呼函式。回呼呼叫 it
函式,其中包含描述測試案例的字串和測試函式。如果測試通過,則測試函式將成功返回,如果測試失敗,則會拋出錯誤。only
的簽名與 it
相同。即使某些案例具有 only: true
,RuleTester
也會為每個案例呼叫 it
或 only
,並且測試框架負責實作測試案例的排他性。(請注意,這是使用 Mocha 等框架時測試套件的標準行為;此資訊僅在您計劃自訂 RuleTester.describe
、RuleTester.it
或 RuleTester.itOnly
時才相關。)
自訂 RuleTester
的範例
"use strict";
const RuleTester = require("eslint").RuleTester,
test = require("my-test-runner"),
myRule = require("../../../lib/rules/my-rule");
RuleTester.describe = function(text, method) {
RuleTester.it.title = text;
return method.call(this);
};
RuleTester.it = function(text, method) {
test(RuleTester.it.title + ": " + text, method);
};
// then use RuleTester as documented
const ruleTester = new RuleTester();
ruleTester.run("my-rule", myRule, {
valid: [
// valid test cases
],
invalid: [
// invalid test cases
]
})