統計資料
雖然可以透過設定 TIMING 環境變數來分析 ESLint 運行的整體規則效能,但有時取得更細微的計時資料(每個檔案每個規則的 lint 時間)或收集其他感興趣的指標可能很有用。特別是在開發新的自訂外掛程式和評估/基準測試新語言或規則集時。對於這些使用案例,您可以選擇性地從 ESLint 收集執行階段統計資訊。
啟用統計資料收集
若要啟用統計資料收集,您可以選擇
- 使用
--stats
CLI 選項。這會將統計資料傳遞到用於輸出 ESLint 結果的格式器中。(注意:並非所有格式器都會輸出統計資料。) - 在
ESLint
建構函式上將stats: true
設定為選項。
啟用統計資料會在每個 LintResult 物件中新增一個 stats
鍵,其中包含諸如解析時間、修復時間、每個規則的 lint 時間等資料。
因此,它無法透過 stdout 取得,但可以透過使用 CLI 的格式器或透過 Node.js API 輕鬆擷取,以滿足您的特定需求。
◆ 統計資料類型
Stats
值是每次 lint 運行的計時資訊。LintResult 類型的 stats
屬性包含它。它具有以下屬性
fixPasses
(number
)
ESLint 在 linting 後至少套用一次修復的次數。times
({ passes: TimePass[] }
)
花費在檔案 (解析、修復、linting) 上的時間,其中 linting 指的是每個規則的計時資訊。TimePass
({ parse: ParseTime, rules?: Record<string, RuleTime>, fix: FixTime, total: number }
)
包含花費在 (解析、修復、linting) 上的時間的物件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
npm
npx eslint file-to-fix.js --fix --stats -f json
yarn
yarn dlx eslint file-to-fix.js --fix --stats -f json
pnpm
pnpm dlx eslint file-to-fix.js --fix --stats -f json
bun
bunx eslint file-to-fix.js --fix --stats -f json
這會產生以下 stats
條目,作為格式化的 lint 結果物件的一部分
{
"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);
});