統計資料
雖然可以透過設定 TIMING 環境變數來分析 ESLint 執行的整體規則效能,但有時取得更細微的時間資料(每個檔案、每個規則的檢查時間)或收集其他感興趣的度量會很有用。特別是在開發新的自訂外掛程式和評估/基準測試新語言或規則集時。對於這些用例,您可以選擇性地從 ESLint 收集執行時統計資料。
啟用統計資料收集
若要啟用統計資料的收集,您可以選擇
- 使用
--stats
CLI 選項。這會將統計資料傳遞到用於輸出 ESLint 結果的格式化工具。(注意:並非所有格式化工具都會輸出統計資料。) - 將
stats: true
設定為ESLint
建構函式的選項。
啟用統計資料會在每個 LintResult 物件中新增一個新的 stats
鍵,其中包含諸如剖析時間、修正時間、每個規則的檢查時間等資料。
因此,它無法透過 stdout 取得,但可以透過使用 CLI 的格式化工具或透過 Node.js API 輕鬆擷取,以滿足您的特定需求。
◆ 統計資料類型
Stats
值是每次檢查執行的時間資訊。 LintResult 類型的 stats
屬性包含它。它具有以下屬性
fixPasses
(number
)
ESLint 在檢查後至少套用一次修正的次數。times
({ passes: TimePass[] }
)
在檔案上花費的時間(剖析、修正、檢查),其中檢查是指每個規則的時間資訊。TimePass
({ parse: ParseTime, rules?: Record<string, RuleTime>, fix: FixTime, total: number }
)
一個物件,包含在(剖析、修正、檢查)上花費的時間ParseTime
({ total: number }
)
剖析檔案時花費的總時間。RuleTime
({ total: number }
)在規則上花費的總時間。 FixTime
({ total: number }
)在將修正套用至程式碼上花費的總時間。
CLI 使用方式
讓我們考慮以下範例
/*eslint no-regex-spaces: "error", wrap-regex: "error"*/
function a() {
return / foo/.test("bar");
}
使用 --stats
執行 ESLint,並透過內建的 json
格式化工具輸出至 JSON
npx eslint file-to-fix.js --fix --stats -f json
這會產生以下 stats
項目,作為格式化檢查結果物件的一部分
{
"times": {
"passes": [
{
"parse": {
"total": 3.975959
},
"rules": {
"no-regex-spaces": {
"total": 0.160792
},
"wrap-regex": {
"total": 0.422626
}
},
"fix": {
"total": 0.080208
},
"total": 12.765959
},
{
"parse": {
"total": 0.623542
},
"rules": {
"no-regex-spaces": {
"total": 0.043084
},
"wrap-regex": {
"total": 0.007959
}
},
"fix": {
"total": 0
},
"total": 1.148875
}
]
},
"fixPasses": 1
}
請注意,對於上面的簡單範例,所有規則時間的總和應該可以直接與 TIMING 輸出的第一欄比較。使用 TIMING=all
執行相同的命令,您可以驗證這一點
$ TIMING=all npx eslint file-to-fix.js --fix --stats -f json
...
Rule | Time (ms) | Relative
:---------------|----------:|--------:
wrap-regex | 0.431 | 67.9%
no-regex-spaces | 0.204 | 32.1%
API 使用方式
您可以使用 Node.js API 透過將 stats: true
作為選項傳遞給 ESLint
建構函式來實現相同的效果。例如
const { ESLint } = require("eslint");
(async function main() {
// 1. Create an instance.
const eslint = new ESLint({ stats: true, fix: true });
// 2. Lint files.
const results = await eslint.lintFiles(["file-to-fix.js"]);
// 3. Format the results.
const formatter = await eslint.loadFormatter("json");
const resultText = formatter.format(results);
// 4. Output it.
console.log(resultText);
})().catch((error) => {
process.exitCode = 1;
console.error(error);
});