For AI agents: the complete documentation index is available at https://rspack.rs/llms.txt, the full documentation bundle is available at https://rspack.rs/llms-full.txt, and this page is available as Markdown at https://rspack.rs/api/javascript-api/stats.md.
close

Stats

The Stats object provides information about a single build, including errors, warnings, build duration, output assets, modules, and chunks. Use it in build scripts or plugins to check whether a build succeeded, print a summary, or provide data to an analysis tool.

Its main methods are:

  • hasErrors() and hasWarnings(): Check whether the build has errors or warnings.
  • toJson(): Return the build information you need as a JavaScript object for further processing or analysis.
  • toString(): Format the build information you need as text for console output.

Getting stats

When you call rspack() to run a build, its callback receives a Stats object as the second argument. The following script prints build errors and warnings and sets a nonzero exit code if the build fails:

build.mjs
import { rspack } from '@rspack/core';
import config from './rspack.config.mjs';

rspack(config, (err, stats) => {
  if (err) {
    console.error(err);
    process.exitCode = 1;
    return;
  }

  console.log(stats.toString('errors-warnings'));

  if (stats.hasErrors()) {
    process.exitCode = 1;
  }
});

The callback's err argument reports errors that prevent Rspack from completing the build. Compilation errors, such as missing modules or syntax errors, are recorded in stats. Even when err is absent, check stats.hasErrors() to determine whether the build succeeded.

You can also get stats in the following ways:

If you pass an array of configurations to rspack(), the callback receives a MultiStats object containing the build result for each configuration.

Stats methods

hasErrors

Can be used to check if there were errors while compiling.

Type:

hasErrors(): boolean;

Use the return value to handle compilation errors:

if (stats.hasErrors()) {
  console.error('Compilation failed');
}

hasWarnings

Can be used to check if there were warnings while compiling.

Type:

hasWarnings(): boolean;

Use the return value to handle compilation warnings:

if (stats.hasWarnings()) {
  console.warn('Compilation completed with warnings');
}

toJson

Return compilation information as a Stats JSON object. Pass a stats preset or options object to choose what to include.

For usage guidance, see Call timing and Performance overhead.

For the structure and field descriptions of objects in assets, see Asset object.

Type:

toJson(options?: StatsValue): StatsCompilation;

Use the 'minimal' preset and print the number of errors:

const statsJson = stats.toJson('minimal');
console.log(statsJson.errorsCount);

Use an options object to select the fields to include, then print the compilation hash:

const statsJson = stats.toJson({
  all: false,
  hash: true,
});
console.log(statsJson.hash);

toString

Return the compilation information in the form of a formatted string (similar to the output of CLI).

For usage guidance, see Call timing and Performance overhead.

Type:

toString(opts?: StatsValue): string;

Use Stats configuration to select what to display, and colors to control text colors:

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

Here's an example of stats.toString() usage:

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
      }),
    );
  },
);

Stats properties

compilation

Type: Compilation

Get the related compilation object.

hash

Type: string | null

Get the hash of this compilation, same as Compilation.hash.

When using it as a string, check for null first:

if (stats.hash !== null) {
  console.log(stats.hash);
}

Usage notes

Call timing

stats.toJson() and stats.toString() rely on compilation artifacts that are finalized in compiler.hooks.done. If they are called at other times (for example, on stale Stats objects captured earlier), some stats fields can be incomplete.

For complete and stable stats output, call these methods in compiler.hooks.done:

compiler.hooks.done.tap('MyPlugin', (stats) => {
  const statsJson = stats.toJson({ all: false, errors: true, warnings: true });
  const statsText = stats.toString({ preset: 'errors-warnings' });
  console.log(statsJson.errors);
  console.log(statsText);
});

Performance overhead

stats.toJson() and stats.toString() collect compilation data from Rust and process it in JavaScript. Enabling all: true can significantly increase the amount of data transferred and the time spent generating stats, especially in large projects. Detailed fields such as module sources, reasons, and chunk modules should only be enabled when needed.

Pass all: false and enable only the fields your code uses. These options must be passed directly to toJson() or toString(), which do not automatically inherit the top-level stats configuration. For example, to read error and warning details:

const statsJson = stats.toJson({
  all: false,
  errors: true,
  warnings: true,
});

If you need the same information more than once within a build, reuse the generated result to avoid the overhead of repeated calls.

MultiStats

When using MultiCompiler to run multiple compilation tasks, their results are packaged as a MultiStats object. It provides a combined hash and methods for checking, serializing, and formatting all child compilation results.

hash

ReadOnly

Type: string

Get the hash formed by concatenating the hashes of all child compilations.

Print the concatenated hash:

console.log(multiStats.hash);

hasErrors

Returns true if any child compilation has errors.

Type:

hasErrors(): boolean;

Use the return value to handle errors across all child compilations:

if (multiStats.hasErrors()) {
  console.error('At least one compilation failed');
}

hasWarnings

Returns true if any child compilation has warnings.

Type:

hasWarnings(): boolean;

Use the return value to handle warnings across all child compilations:

if (multiStats.hasWarnings()) {
  console.warn('At least one compilation completed with warnings');
}

toJson

Returns a StatsCompilation whose children array contains the Stats JSON for each child compilation. Fields enabled for every child, such as errors and warnings, are also aggregated at the top level.

Type:

toJson(options: boolean | StatsPresets | MultiStatsOptions): StatsCompilation;

Use one preset for every child compilation and inspect the number of results:

const statsJson = multiStats.toJson('minimal');
console.log(statsJson.children?.length);

MultiStatsOptions also supports a children option for configuring each child compilation individually. The following example prints the errors from the first child compilation:

const statsJson = multiStats.toJson({
  children: [
    { all: false, errors: true },
    { all: false, assets: true },
  ],
});
console.log(statsJson.children?.[0]?.errors);

toString

Format each child compilation according to the stats configuration, then concatenate the results into one string.

Type:

toString(options: boolean | StatsPresets | MultiStatsOptions): string;

Use one preset for every child compilation and print the combined output:

const statsText = multiStats.toString('minimal');
console.log(statsText);

Stats factory

StatsFactory generates Stats JSON from a Compilation and provides hooks to customize the result. When generating text output, StatsPrinter formats that JSON as a string. The following diagram shows how they work together in stats.toJson() and stats.toString():

Stats
Compilation ===============> Stats JSON =================> Stats Output
           ╰─ StatsFactory ─╯           ╰─ StatsPrinter ─╯
╰─────────── stats.toJson() ───────────╯
╰───────────────────────── stats.toString() ──────────────────────────╯

It can be got through compilation.hooks.statsFactory. Or create a new one by new StatsFactory().

Hooks

See StatsFactory hooks for more details.

create

The core method of StatsFactory, according to the type to specify the current data structure, find and run the corresponding generator to generate the stats json item.

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

The StatsFactory object only handles the calling of hooks, and the processing code of the corresponding type can be found in DefaultStatsFactoryPlugin.

Stats printer

Used to generate the output string from the stats json object, and provides hooks for fine-grained control during the generation process.

It can be got through compilation.hooks.statsPrinter. Or create a new one by new StatsPrinter().

Hooks

See StatsPrinter hooks for more details.

print

The core method of StatsPrinter, according to the type to specify the current data structure, find and run the corresponding generator to generate the output string of the stats item.

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

The StatsPrinter object only handles the calling of hooks, and the processing code of the corresponding type can be found in DefaultStatsPrinterPlugin.