统计

传递给 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 对象,并在生成过程中提供钩子,以便进行细粒度控制。

可以通过 compilation.hooks.statsFactory 获取。或者通过 new StatsFactory() 创建一个新的。

钩子

有关更多详细信息,请参阅 统计工厂钩子

create

StatsFactory 的核心方法,根据 type 指定当前数据结构,查找并运行相应的生成器以生成统计 json 项目。

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

StatsFactory 对象只处理钩子的调用,相应类型的处理代码可以在 DefaultStatsFactoryPlugin 中找到。

统计打印机

用于从统计 json 对象生成输出字符串,并在生成过程中提供钩子,以便进行细粒度控制。

可以通过 compilation.hooks.statsPrinter 获取。或者通过 new StatsPrinter() 创建一个新的。

钩子

有关更多详细信息,请参阅 统计打印机钩子

print

StatsPrinter 的核心方法,根据 type 指定当前数据结构,查找并运行相应的生成器以生成统计项目的输出字符串。

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

StatsPrinter 对象只处理钩子的调用,相应类型的处理代码可以在 DefaultStatsPrinterPlugin 中找到。