The Compiler is a core object in Rspack. A Compiler instance is created when you call Rspack's JavaScript API or CLI.
It provides methods like run and watch to start builds, and exposes Compiler hooks that allow plugins to hook into different stages of the build process.
Starts a compilation and calls the callback when compilation completes or fails with an error.
function run(
callback: (
error: Error, // Only includes compiler-related errors, such as configuration errors, not compilation errors
stats: Stats, // Detailed information generated during compilation
) => void,
options?: {
modifiedFiles?: ReadonlySet<string>; // Modified files included in this compilation
removedFiles?: ReadonlySet<string>; // Deleted files included in this compilation
},
): void;If you need to call the run method on the same compiler object multiple times, note the following:
compiler.close() in the compiler.run callback and wait for it to finish before calling compiler.run again. Running multiple compilations simultaneously can produce unexpected output files.modifiedFiles and removedFiles parameters. When caching is enabled and you're using a custom watcher, pass these values to Rspack via the options parameter.compiler.run((err, stats) => {
// Deal with the compiler errors
handleCompilerError(err);
// Deal with the compilation errors
handleModuleErrors(stats.toJson().errors);
// Deal with the result
handleBuildResult(stats);
// End this compilation
compiler.close(closeErr => {
// Start a new compilation
compiler.run((err, stats) => {});
});
});Watches files and directories, starting a compilation after they change. Calls the handler after each compilation completes or fails.
function watch(
watchOptions: WatchOptions, // Options for starting the watcher
handler: (error: Error, stats: Stats) => void, // Callback after each compilation
): Watching; // Watching controller
This API only supports one compilation at a time. Call compiler.close in the compiler.watch callback and wait for it to finish before calling compiler.watch again. Concurrent compilations will corrupt output files.
const watching = compiler.watch(
{
aggregateTimeout: 300,
poll: undefined,
},
(err, stats) => {
// Deal with the result
handleBuildResult(stats);
},
);The Watching object provides the following methods:
watch:
(files: string[], dirs: string[], missing: string[]): voidinvalidate:
(callback: () => void): voidsuspend:
(): voidresume:
(): voidclose:
(callback: () => void): voidCloses the compiler and handles low-priority tasks like caching.
function close(
callback: (err: Error) => void, // Callback after closing
): void;Create a logger object that is not associated with any compilation, which is used to print global logs.
function getInfrastructureLogger(name: string): Logger;Creates a cache object to share data during the build process.
function getCache(name: string): CacheFacade;Stops the input file system read loop, which contains an internal timer that may prevent the process from exiting after calling compiler.close.
function purgeInputFileSystem(): void;Runs another Rspack instance inside Rspack as a child compiler with different settings. Copies all hooks and plugins from the parent (or top-level) compiler and creates a child Compiler instance. Returns the created Compiler.
function createChildCompiler(
compilation: Compilation,
compilerName: string,
compilerIndex: number,
outputOptions: OutputOptions,
plugins: RspackPlugin[],
): Compiler;Runs the child compiler, performing a complete compilation and generating assets.
function runAsChild(
callback(
err: Error, // Error related to the child compiler
entries: Chunk[], // Chunks generated by the child compiler
compilation: Compilation, // The compilation created by the child compiler
): void;
): void;Whether this compiler is a child compiler.
function isChild(): boolean;See compiler hooks for more details.
typeof rspackGet the exports of @rspack/core to obtain the associated internal objects. This is especially useful when you cannot directly reference @rspack/core or there are multiple Rspack instances.
A common example is accessing the sources object in a Rspack plugin:
const { RawSource } = compiler.rspack.sources;
const source = new RawSource('console.log("Hello, world!");');typeof rspackEquivalent to compiler.rspack, this property is used for compatibility with webpack plugins.
If the Rspack plugin you are developing needs to be webpack compatible, you can use this property instead of compiler.rspack.
console.log(compiler.webpack === compiler.rspack); // truestringGet the name:
name.createChildCompiler.Current project root directory:
new Compiler, it is the value passed in.rspack({}), it is context configuration.CompilerGet the root of the child compiler tree.
RspackOptionsNormalizedGet the full options used by this compiler.
booleanWhether started through compiler.watch.
WatchingGet the watching object, see watch method for more details.
booleanWhether the compilation is currently being executed.
InputFileSystemGet the proxy object used for reading from the file system, which has optimizations such as caching inside to reduce duplicate reading of the same file.
OutputFileSystemGet the proxy object used for writing to the file system, fs by default.
WatchFileSystemGet the proxy object used for watching files or directories changes, which provides a watch method to start watching, and passes in the changed and removed items in the callback.
The MultiCompiler module allows Rspack to run multiple configurations in separate compilers. If the options parameter in the Rspack's JavaScript API is an array of options, Rspack applies separate compilers and calls the callback after all compilers have been executed.
const { rspack } = require('@rspack/core');
rspack(
[
{ entry: './index1.js', output: { filename: 'bundle1.js' } },
{ entry: './index2.js', output: { filename: 'bundle2.js' } },
],
(err, stats) => {
process.stdout.write(stats.toString() + '\n');
},
);It can also be created through new MultiCompiler:
const compiler1 = new Compiler({
/* */
});
const compiler2 = new Compiler({
/* */
});
new MultiCompiler([compiler1, compiler2]);
new MultiCompiler([compiler1, compiler2], {
parallelism: 1, // the maximum number of parallel compilers
});
new MultiCompiler({
name1: compiler1,
name2: compiler2,
});MultiCompiler also provides some methods and attributes of the Compiler.
Specify the dependency relationship between the compilers, using compiler.name as the identifier, to ensure the execution order of the compilers.
setDependencies(compiler: Compiler, dependencies: string[]): void;Check whether the dependency relationship between the compilers is legal. If there is a cycle or a missing dependency, it will trigger the callback.
validateDependencies(
callback: (err: Error) => void; // callback when there is an error
): booleanExecute the run method of each compiler according to the dependency relationship to start the compilation process.
run(
callback: (err: Error, stats: MultiStats) => void,
options?: {
modifiedFiles?: ReadonlySet<string>; // Modified files included in this compilation
removedFiles?: ReadonlySet<string>; // Deleted files included in this compilation
},
): void;Execute the watch method of each compiler according to the dependency relationship to start watching, and start a compilation process after the file changes.
function watch(
watchOptions: WatchOptions | WatchOptions[],
handler: (err: Error, stats: MultiStats) => void,
): MultiWatching;Execute the close method of each compiler to close them, and handle low-priority tasks such as caching during this period.
close(callback: (err: Error) => void): void;Execute the purgeInputFileSystem of each compiler to stop the read loop of the file system
purgeInputFileSystem(): void;Create a logger object that is not associated with any compilation, which is used to print global logs.
getInfrastructureLogger(name: string): Logger;Same with
compilers[0].getInfrastructureLogger()
Compiler[]Get all included compilers.
RspackOptionsNormalized[]Get all the full options used by the compilers.
InputFileSystemSet the proxy object used for reading from the file system for each compiler.
OutputFileSystemSet the proxy object used for writing from the file system for each compiler.
WatchFileSystemSet the proxy object used for watching files or directories changes for each compiler.
booleanWhether the compilation is currently being executed.