The content of this section is derived from the content of the following links and is subject to the CC BY 4.0 license.
The following contents can be assumed to be the result of modifications and deletions based on the original contents if not specifically stated.
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.
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.
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);
});
}
}Emit a new asset, throw an error if the asset already exists.
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:
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,
});
});
});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)
): void;The following code replaces the content of main.js and not to minimize it:
compiler.hooks.thisCompilation.tap('MyPlugin', compilation => {
const { RawSource } = compiler.rspack.sources;
compilation.hooks.processAssets.tap('MyPlugin', () => {
const updatedSource = new RawSource(
`module.exports = "This is the updated"`,
);
compilation.updateAsset('main.js', updatedSource, {
minimized: true,
});
});
});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');
});
});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');
});
});Get the list of asset objects.
getAssets(): ReadonlyArray<{
filename: 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}`);
});
});Get the asset object with the specified name.
getAsset(
filename: string // filename of the getting asset
): Readonly<{
filename: string;
source: Source;
info: AssetInfo;
}> | void;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}`);
});
});Generate path string based on the Filename template, see Template String 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"Generate path string and asset info based on the Filename template, see Template String.
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: {}
} */Get the stats object of current compilation:
getStats(): Stats;The following code prints the total number of modules:
compiler.hooks.emit.tapAsync('MyPlugin', compilation => {
const modules = compilation.getStats().toJson({ modules: true }).modules;
console.log(`Total modules: ${modules.length}`);
});Allows running another instance of Rspack inside of Rspack. However, as a child with different settings and configurations applied. It copies all hooks and plugins from the parent (or top-level compiler) and creates a child Compiler instance. Returns the created Compiler.
createChildCompiler(
name: string, // name for the child `Compiler`
outputOptions: OutputNormalized, // Output options object
plugins: RspackPluginInstance[] // Plugins that will be applied
): 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) => {});
});Add a custom runtime module to the compilation.
addRuntimeModule(
c: Chunk, // the runtime chunk which to add the runtime module
m: RuntimeModule, // the runtime module instance to add
): void;The following code will add a runtime module which define __webpack_require__.mock to the "main" chunk:
export default {
entry: './index.js',
plugins: [
{
apply(compiler) {
const { RuntimeModule } = 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 runtime module class, the following methods/properties can be overridden to control the behavior of the runtime module:
name and stage parameters in the constructor to specify the module name and the insertion stage.generate() method to control the generated code of the module.shouldIsolate() method to control whether the module is wrapped in an IIFE.attach() method to modify the behavior when the module is added.fullHash or dependentHash properties to control whether the module can be cached.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'),
);
compilation.rebuildModule(oldModule, (err, m) => {
console.log(`Rebuilt ${m.identifier()}.`);
});
});
});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}`);
}
});
});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;Type: RspackOptionsNormalized
The normalized options used by this Compilation, see Configure Rspack for details.
Type: Compiler
Current compiler object.
The Compilation hooks.
Type: Readonly<string | null>
The hash of this compilation.
Type: Record<string, Source>
The mapping from asset filenames and content sources.
Type: ReadonlyArray<ChunkGroup>
The list of chunk group objects, with the structure as follows:
Type: ReadonlyMap<string, Entrypoint>
The mapping from name to entrypoint, which is a special chunk group and include a runtime chunk.
Type: ReadonlyMap<string, Readonly<ChunkGroup>>
The mapping from names to chunk groups.
Type: ReadonlySet<Module>
List of all modules, with the structure as follows:
Type: ReadonlySet<Module>
List of built modules that were not be cached, with the structure as follows:
Type: ReadonlySet<Chunk>
List of all chunks, with the structure as follows:
Type: ReadonlyMap<string, Readonly<Chunk>>
The mapping from names to chunks.
Type: CompilationDependencies
List of files this compilation depends on.
Type: CompilationDependencies
List of directories this compilation depends on.
Type: CompilationDependencies
List of not existing files this compilation depends on.
Type: CompilationDependencies
List of build dependencies this compilation depends on.
Type: RspackError[]
List of emitted errors during this compilation, with the structure as follows:
Type: RspackError[]
List of emitted warnings during this compilation.