統計資訊

作為 rspack() 回呼的第二個參數傳遞的 stats 物件,是程式碼編譯過程的良好資訊來源。它包含

  • 錯誤和警告 (如果有的話)
  • 計時
  • 模組和區塊資訊

Stats 物件提供兩個重要的方法

  • toJson():以 統計資訊 JSON 物件的形式輸出資訊,該物件通常用於分析工具。
  • toString():以字串形式輸出資訊,通常用於 CLI 工具。

Rspack 還提供 StatsFactoryStatsPrinter 來精細控制輸出物件或字串。

統計資訊輸出
Compilation ===============> Stats JSON =================> Stats Output
           ╰─ StatsFactory ─╯           ╰─ StatsPrinter ─╯
╰─────────── stats.toJson() ───────────╯
╰───────────────────────── stats.toString() ──────────────────────────╯

透過 compilation.getStats()new Stats(compilation) 建立與編譯相關的統計資訊物件。

統計資訊方法

hasErrors

可用於檢查編譯時是否發生錯誤。

hasErrors(): boolean;

hasWarnings

可用於檢查編譯時是否發生警告。

hasWarnings(): boolean;

toJson

統計資訊 JSON 物件的形式傳回編譯資訊。 統計資訊設定 可以是字串 (預設值) 或物件,以進行細微控制

stats.toJson('minimal');
stats.toJson({
  assets: false,
  hash: true,
});

toString

以格式化字串的形式傳回編譯資訊 (類似於 CLI 的輸出)。

toJson(opts?: StatsValue): string;

選項與 stats.toJson(options) 相同,但多了一個選項

stats.toString({
  // Add console colors
  colors: true,
});

以下是 stats.toString() 用法的範例

import { rspack } from '@rspack/core';

rspack(
  {
    // ...
  },
  (err, stats) => {
    if (err) {
      console.error(err);
      return;
    }

    console.log(
      stats.toString({
        chunks: false, // Makes the build much quieter
        colors: true, // Shows colors in the console
      }),
    );
  },
);

統計資訊屬性

compilation

類型: Compilation

取得相關的編譯物件。

hash

類型: string

取得此編譯的雜湊值,與 Compilation.hash 相同。

MultiStats

當使用 MultiCompiler 執行多個編譯任務時,它們的編譯統計資訊將會打包成一個 MultiStats 物件,該物件提供與 Stats 類似的方法和屬性。

hash

唯讀

類型: string

取得合併所有編譯的雜湊值後的唯一雜湊值。

hasErrors

用於檢查編譯期間是否有錯誤,只有在所有編譯中都沒有錯誤時,才會傳回 false

hasErrors(): boolean;

hasWarnings

用於檢查編譯期間是否有警告,只有在所有編譯中都沒有警告時,才會傳回 false

hasWarnings(): boolean;

toJson

根據 統計資訊設定,產生所有 統計資訊 json 物件,將它們包裝在 children 欄位中,並總結 errorswarnings

toJson(options?: StatsValue): {
  hash: string;
  errorsCount: number;
  warningsCount: number;
  errors: StatsError[];
  warnings: StatsError[];
  children: StatsCompilation[];
};

toString

根據 統計資訊設定,串連所有編譯的統計資訊輸出字串。

toString(options?: StatsValue): string;

統計資訊工廠

用於從 Compilation 產生統計資訊 json 物件,並在產生過程中提供精細控制的 hooks。

可以透過 compilation.hooks.statsFactory 取得。或使用 new StatsFactory() 建立一個新的。

Hooks

有關更多詳細資訊,請參閱 StatsFactory hooks

create

StatsFactory 的核心方法,根據 type 來指定當前的資料結構,找到並執行對應的產生器來產生統計資訊 json 項目。

stats = statsFactory.create('compilation', compilation, {});

StatsFactory 物件僅處理 hooks 的呼叫,對應類型的處理程式碼可以在 DefaultStatsFactoryPlugin 中找到。

統計資訊列印器

用於從統計資訊 json 物件產生輸出字串,並在產生過程中提供精細控制的 hooks。

可以透過 compilation.hooks.statsPrinter 取得。或使用 new StatsPrinter() 建立一個新的。

Hooks

有關更多詳細資訊,請參閱 StatsPrinter hooks

print

StatsPrinter 的核心方法會根據資料類型指定當前的資料結構,尋找並執行對應的產生器,以生成統計項目的輸出字串。

stats = statsPrinter.print('compilation', stats, {});

StatsPrinter 物件僅處理掛鉤的調用,而對應類型的處理程式碼可以在 DefaultStatsPrinterPlugin 中找到。