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/compilation.md.
close

Compilation

The Compilation object is one of the core objects used in the Rspack build process. Whenever Rspack performs a build (including rebuilds in watch mode), a new Compilation instance is created, which contains all the information about the current build.

This page lists the available methods and properties of the Compilation object. You can also refer to Compilation Hooks to learn about the hooks provided by the Compilation object.

Notice

In Rspack, the real compilation object runs on the Rust side, and the JavaScript compilation object is only a proxy object used to communicate with the Rust compilation object.

Therefore, some complex data structures and methods will not be supported on the JavaScript compilation object, the data is read-only and the structure may differ from webpack.

Get compilation object

You can get the current compilation object via compiler.hooks.thisCompilation or compiler.hooks.compilation hooks.

class ExamplePlugin {
  apply(compiler) {
    compiler.hooks.thisCompilation.tap('ExamplePlugin', (compilation) => {
      console.log('thisCompilation hook called:', compilation);
    });

    compiler.hooks.compilation.tap('ExamplePlugin', (compilation) => {
      console.log('compilation hook called:', compilation);
    });
  }
}

Compilation methods

emitAsset

Emit an asset. Emitting the same filename with identical content is allowed. Emitting different content for an existing filename records a compilation error. Use updateAsset to intentionally replace an existing asset.

emitAsset(
  filename: string, // filename of the new asset
  source: Source, // content of the new asset
  info?: AssetInfo // asset info of the new asset
): void;

The following code will add a new asset named asset-name.js and will not be compressed because minimized is set to true:

compiler.hooks.thisCompilation.tap('MyPlugin', (compilation) => {
  const { RawSource } = compiler.rspack.sources;
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    const buffer = Buffer.from(
      'i am content of emit asset, do not minimize me',
    );
    const source = new RawSource(buffer, false);
    compilation.emitAsset('asset-name.js', source, {
      minimized: true,
    });
  });
});

updateAsset

Update an existing asset, throw an error if the asset does not exist.

updateAsset(
  filename: string, // filename of the updating asset
  source: Source | ((source: Source) => Source), // the new content or a function returns the new content
  info?:  // the new info or a function returns the new info
    | AssetInfo
    | ((assetInfo: AssetInfo) => AssetInfo | undefined)
): void;

A Source object cannot be modified in place; to update its content, create a new Source or wrap the existing one with ReplaceSource or ConcatSource.

The following code replaces the content of main.js:

compiler.hooks.thisCompilation.tap('MyPlugin', (compilation) => {
  const { RawSource } = compiler.rspack.sources;
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    const updatedSource = new RawSource(`console.log("Updated");`);
    compilation.updateAsset('main.js', updatedSource, {
      // optional asset info...
    });
  });
});

renameAsset

Rename an existing asset.

renameAsset(
  filename: string, // filename of the renaming asset
  newFilename: string // new filename
): void;

The following code renames the asset named main.js to my-asset-name.js:

compiler.hooks.thisCompilation.tap('MyPlugin', (compilation) => {
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    compilation.renameAsset('main.js', 'my-asset-name.js');
  });
});

deleteAsset

Delete an existing asset.

deleteAsset(
  filename: string // filename of the deleting asset
): void;

The following code will delete the asset named no-need.js:

compiler.hooks.thisCompilation.tap('MyPlugin', (compilation) => {
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    compilation.deleteAsset('no-need.js');
  });
});

getAssets

Get the list of asset objects. For descriptions of common info fields, see Asset info.

getAssets(): ReadonlyArray<{
  name: string;
  source: Source;
  info: AssetInfo;
}>;

The following code will print the total size of all assets:

compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    const assets = compilation.getAssets();
    const totalSize = assets.reduce(
      (total, asset) => total + asset.source.size(),
      0,
    );
    console.log(`total size: ${totalSize}`);
  });
});

getAsset

Get the asset object with the specified name. For descriptions of common info fields, see Asset info.

getAsset(
  name: string // name of the asset
): Readonly<{
  name: string;
  source: Source;
  info: AssetInfo;
}> | undefined;

The following code will print the size of the asset named main.js:

compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    const assetSize = compilation.getAsset('main.js')?.source.size();
    console.log(`main size: ${assetSize}`);
  });
});

getPath

Generate path string based on the Filename template, see Filename placeholders for the template rules.

getPath(
  filename: Filename, // filename template
  data: PathData = {} // generating path data
): string;

The following code will replace the placeholder in the template to generate the path:

const path = compilation.getPath('[contenthash]-[fullhash].js', {
  contentHash: 'some1',
  hash: 'some2',
});
console.log(path); // "some1-some2.js"

getPathWithInfo

Generate path string and asset info based on the Filename template, see Filename placeholders.

getPathWithInfo(
  filename: Filename, // filename template
  data: PathData = {} // generating path data
): {
  path: string;
  info: AssetInfo;
};

The following code will replace the placeholder in the template to generate the path and asset info:

const { path, info } = compilation.getPathWithInfo(
  '[contenthash]-[fullhash].js',
  {
    contentHash: 'some1',
    hash: 'some2',
  },
);
console.log(path); // "some1-some2.js"
console.log(info);
/* Object {
  immutable: true,
  minimized: false,
  fullhash: [ 'some2' ],
  chunkhash: [],
  contenthash: [ 'some1' ],
  development: false,
  hotModuleReplacement: false,
  related: {},
  extras: {}
} */

getStats

Get the stats object of current compilation:

getStats(): Stats;

The following code prints the total number of modules:

compiler.hooks.emit.tap('MyPlugin', (compilation) => {
  const modules = compilation.getStats().toJson({ modules: true }).modules;
  console.log(`Total modules: ${modules.length}`);
});

createChildCompiler

Create a child Compiler with its own output options and additional plugins, and return it. The child inherits eligible hook taps and built-in plugins from the parent compiler.

Taps on make, compile, emit, afterEmit, invalid, done, and thisCompilation are not copied to the child. Built-in plugins are inherited only when they support child compiler inheritance. Use the plugins argument to apply additional plugins to the child compiler.

createChildCompiler(
  name: string, // name for the child `Compiler`
  outputOptions: OutputNormalized, // Output options object
  plugins?: (RspackPluginInstance | Falsy)[] // Additional plugins for the child compiler
): Compiler;

The following code will start a child compiler with child-entry.js as the entry, and output to dist/child:

compiler.hooks.make.tap('MyPlugin', (compilation) => {
  const childCompiler = compilation.createChildCompiler(
    'ChildCompiler',
    {
      path: 'dist/child',
    },
    [new compiler.rspack.EntryPlugin(compiler.context, './child-entry.js')],
  );
  childCompiler.compile((err, childCompilation) => {});
});

addRuntimeModule

Add a custom Rspack runtime module to the compilation.

addRuntimeModule(
  c: Chunk, // the chunk to add the Rspack runtime module to
  m: RuntimeModule, // the Rspack runtime module instance to add
): void;

The following code adds a Rspack runtime module to the "main" chunk to define __webpack_require__.mock:

rspack.config.mjs
export default {
  entry: './index.js',
  plugins: [
    {
      apply(compiler) {
        const { RuntimeModule, RuntimeGlobals } = compiler.rspack;

        class CustomRuntimeModule extends RuntimeModule {
          constructor() {
            super('custom');
          }

          generate() {
            const compilation = this.compilation;
            return `
            __webpack_require__.mock = function() {
              // ...
            };
          `;
          }
        }

        compiler.hooks.thisCompilation.tap('CustomPlugin', (compilation) => {
          compilation.hooks.runtimeRequirementInTree
            .for(RuntimeGlobals.ensureChunkHandlers)
            .tap('CustomPlugin', (chunk, set) => {
              if (chunk.name === 'main') {
                compilation.addRuntimeModule(chunk, new CustomRuntimeModule());
              }
            });
        });
      },
    },
  ],
};

When implementing a custom Rspack runtime module, you can override the following methods and properties to control its behavior:

  • Pass the name and stage parameters in the constructor to specify the module name and the insertion stage.
  • Override the generate() method to control the generated code of the module.
  • Override the shouldIsolate() method to control whether the module is wrapped in an IIFE.
  • Override the attach() method to modify the behavior when the module is added.
  • Modify its fullHash or dependentHash properties to control whether the module can be cached.

rebuildModule

Triggers a re-build of the module.

rebuildModule(
  m: Module, // module to be rebuilt
  f: (err: Error | null, m: Module | null) => void //  function to be invoked when the module finishes rebuilding
): void;

The following code will rebuild the module ending with a.js:

compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
  compilation.hooks.finishModules.tapPromise('MyPlugin', async (modules) => {
    const oldModule = Array.from(modules).find((item) =>
      item.resource?.endsWith('a.js'),
    );
    if (!oldModule) {
      return;
    }

    await new Promise((resolve, reject) => {
      compilation.rebuildModule(oldModule, (err, rebuiltModule) => {
        if (err) {
          reject(err);
          return;
        }
        console.log(`Rebuilt ${rebuiltModule.identifier()}.`);
        resolve();
      });
    });
  });
});

getLogger

Get a log output utility object with the specified name, which can be used to print logs with unified format in the plugin.

getLogger(name: string | (() => string)): Logger;

The following code prints the asset to the debug log in processAssets:

compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
  const logger = compilation.getLogger('MyPlugin');

  compilation.hooks.processAssets.tap('MyPlugin', () => {
    for (const asset of compilation.getAssets()) {
      logger.debug(`asset name: ${asset.name}`);
      logger.debug(`asset info: ${asset.info}`);
    }
  });
});

getCache

Get a cache object with the specified name, which can be used for the plugin to share data during multiple compilations.

getCache(name: string): CacheFacade;

Compilation properties

options

Type: RspackOptionsNormalized

The normalized options used by this Compilation, see Configure Rspack for details.

runtimeTemplate

Type: RuntimeTemplate

Helpers that generate Rspack runtime code matching the capabilities of the targeted environment, as declared by output.environment. Use them instead of hand-written snippets so that generated code stays valid for older targets.

class MyPlugin {
  apply(compiler) {
    compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
      const { runtimeTemplate } = compilation;

      // `() => (globalThis)` when arrow functions are supported,
      // `function() { return globalThis; }` otherwise
      runtimeTemplate.returningFunction('globalThis');

      // `(a) => {\n\tconsole.log(a);\n}` when arrow functions are supported,
      // `function(a) {\n\tconsole.log(a);\n}` otherwise
      runtimeTemplate.basicFunction('a', 'console.log(a);');
    });
  }
}

compiler

Type: Compiler

Current compiler object.

hooks

The Compilation hooks.

hash/fullHash

Type: Readonly<string | null>

The hash representing the current compilation as a whole. Rspack calculates it from the chunks and their content hashes, together with its internal rebuild state.

In Rspack, hash and fullHash are read-only aliases that return the same value:

  • null: the compilation hash has not been calculated yet, for example when the thisCompilation hook runs.
  • string: the compilation hash is available. You can read it in hooks that run after hashing, such as processAssets or afterSeal.

The hash is calculated before asset processing. Updating assets in processAssets does not automatically recalculate this value.

compiler.hooks.thisCompilation.tap('MyPlugin', (compilation) => {
  compilation.hooks.processAssets.tap('MyPlugin', () => {
    console.log('Compilation hash:', compilation.hash);
    // compilation.fullHash has the same value.
  });
});

assets

Type: Record<string, Source>

The mapping from asset filenames and content sources.

chunkGroups

Type: ReadonlyArray<ChunkGroup>

The list of chunk group objects, with the structure as follows:

entrypoints

Type: ReadonlyMap<string, Entrypoint>

A map with entry names as keys and Entrypoint objects as values. Each Entrypoint represents the chunk group for an entry and provides access to its chunks and output files.

For example, when generating HTML on the server, you need to know which JavaScript and CSS files to include for each entry. Iterate over compilation.entrypoints, call entrypoint.getFiles() to get those filenames, and save them in a manifest.

The following plugin generates entrypoints.json after the standard asset optimization and hash processing stages:

class EntryManifestPlugin {
  apply(compiler) {
    const { Compilation, sources } = compiler.rspack;

    compiler.hooks.thisCompilation.tap('EntryManifestPlugin', (compilation) => {
      compilation.hooks.processAssets.tap(
        {
          name: 'EntryManifestPlugin',
          stage: Compilation.PROCESS_ASSETS_STAGE_REPORT,
        },
        () => {
          const manifest = Object.fromEntries(
            Array.from(compilation.entrypoints, ([name, entrypoint]) => [
              name,
              entrypoint.getFiles(),
            ]),
          );
          compilation.emitAsset(
            'entrypoints.json',
            new sources.RawSource(JSON.stringify(manifest, null, 2)),
          );
        },
      );
    });
  }
}

The manifest maps each entry name to an array of filenames. For example, if the main entry produces an entry script, a separate Rspack runtime, and a CSS file, the manifest might look like this:

entrypoints.json
{
  "main": ["runtime.js", "main.js", "main.css"]
}

The filenames returned by getFiles() are relative to the output directory and do not include publicPath.

getFiles() only returns files in the entrypoint's chunk group. Async chunks loaded on demand through import() and plugin assets outside that chunk group, such as entrypoints.json itself, are not included in the manifest.

namedChunkGroups

Type: ReadonlyMap<string, Readonly<ChunkGroup>>

The mapping from names to chunk groups.

modules

Type: ReadonlySet<Module>

All modules in the current compilation. For each module, use module.identifier() to identify it, and module.originalSource() to read its source after loaders have run. The source can be null for modules without source code.

Use compilation.moduleGraph to inspect relationships between modules.

builtModules

Type: ReadonlySet<Module>

List of built modules that were not be cached, with the structure as follows:

moduleGraph

Provides access to module dependencies:

  • getModule(dependency): the module referenced by a dependency, or null.
  • getOutgoingConnections(module): connections from this module to its dependencies; connection.module is the target module, or null.
  • getIncomingConnections(module): connections from other modules to this module; connection.originModule is the importing module, or null.

You can query these relationships in the finishModules hook, after modules have been built. For example, log each module and the modules it depends on:

compiler.hooks.compilation.tap('InspectModules', (compilation) => {
  compilation.hooks.finishModules.tap('InspectModules', (modules) => {
    for (const module of modules) {
      const connections =
        compilation.moduleGraph.getOutgoingConnections(module);
      for (const connection of connections) {
        if (connection.module) {
          console.log(module.identifier(), connection.module.identifier());
        }
      }
    }
  });
});

chunks

Type: ReadonlySet<Chunk>

List of all chunks, with the structure as follows:

namedChunks

Type: ReadonlyMap<string, Readonly<Chunk>>

The mapping from names to chunks.

fileDependencies

Type: FileSystemDependencies

Files that this compilation depends on. In watch mode, Rspack rebuilds when these files change.

For example, a plugin may read site.json from the project root. Reading the file with Node.js alone does not make Rspack watch it. Add its absolute path to fileDependencies in the thisCompilation hook so the dependency is recorded on every compilation.

import path from 'node:path';

class WatchConfigPlugin {
  apply(compiler) {
    compiler.hooks.thisCompilation.tap('WatchConfigPlugin', (compilation) => {
      const configPath = path.resolve(compiler.context, 'site.json');
      compilation.fileDependencies.add(configPath);
    });
  }
}

contextDependencies

Type: FileSystemDependencies

Directories that this compilation depends on. In watch mode, Rspack rebuilds when files are added to or removed from these directories.

For example, if a plugin scans an existing templates directory to get a list of templates, add the directory's absolute path:

import path from 'node:path';

class WatchTemplatesPlugin {
  apply(compiler) {
    compiler.hooks.thisCompilation.tap(
      'WatchTemplatesPlugin',
      (compilation) => {
        const templatesPath = path.resolve(compiler.context, 'templates');
        compilation.contextDependencies.add(templatesPath);
      },
    );
  }
}

If the plugin also reads template contents, add those files to fileDependencies to watch for changes to their contents.

missingDependencies

Type: FileSystemDependencies

Files that this compilation needs to watch but that do not yet exist. In watch mode, Rspack rebuilds when these files are created.

For example, a plugin may support an optional site.local.json configuration file that the user has not created yet. The plugin should check whether the file exists on each compilation: if it is absent, add its path to missingDependencies; if it exists, add its path to fileDependencies. This triggers rebuilds both when the file is created and when it is edited later.

import { existsSync } from 'node:fs';
import path from 'node:path';

class WatchLocalConfigPlugin {
  apply(compiler) {
    compiler.hooks.thisCompilation.tap(
      'WatchLocalConfigPlugin',
      (compilation) => {
        const configPath = path.resolve(compiler.context, 'site.local.json');
        if (existsSync(configPath)) {
          compilation.fileDependencies.add(configPath);
        } else {
          compilation.missingDependencies.add(configPath);
        }
      },
    );
  }
}

buildDependencies

Type: FileSystemDependencies

Files that the build tooling itself depends on, such as configuration files and loaders. Rspack uses these dependencies to determine whether the persistent cache is still valid. See cache.buildDependencies for configuration details.

To rebuild when files or directories read by a plugin change in watch mode, use fileDependencies, contextDependencies, or missingDependencies.

errors

Type: RspackError[]

List of emitted errors during this compilation, with the structure as follows:

warnings

Type: RspackError[]

List of emitted warnings during this compilation.

This page is adapted from webpack documentation under the CC BY 4.0, with modifications.