Rsbuild instance

This section describes all the properties and methods on the Rsbuild instance object.

rsbuild.context

rsbuild.context is a read-only object that provides some context information.

context.version

The version of @rsbuild/core currently in use.

  • Type:
type Version = string;

context.rootPath

The root path of current build, corresponding to the cwd option of createRsbuild method.

  • Type:
type RootPath = string;

context.distPath

The absolute path of the output directory, corresponding to the output.distPath.root config in RsbuildConfig.

When there are multiple environments, Rsbuild will try to get the parent distPath of all environments as context.distPath.

If you want to get the absolute path to the output directory of a specified environment, it is recommended to use environment.distPath.

  • Type:
type DistPath = string;

context.cachePath

The absolute path of the build cache files.

  • Type:
type CachePath = string;

context.devServer

Dev server information, including the current dev server hostname and port number.

  • Type:
type DevServer = {
  hostname: string;
  port: number;
};

context.bundlerType

The bundler type of current build.

  • Type:
type bundlerType = 'rspack' | 'webpack';

Rsbuild internally supports switching to webpack for comparative testing, so this field is provided for differentiation. Usually, you do not need to use this field.

rsbuild.build

Perform a production mode build. This method will generate optimized production bundles and emit them to the output directory.

  • Type:
type BuildOptions = {
  /**
   * Whether to watch for file changes and rebuild.
   * @default false
   */
  watch?: boolean;
  /**
   * Using a custom Rspack Compiler object.
   */
  compiler?: Compiler | MultiCompiler;
};

function Build(options?: BuildOptions): Promise<{
  /**
   * Rspack's [stats](https://rspack.dev/api/javascript-api/stats) object.
   */
  stats?: Rspack.Stats | Rspack.MultiStats;
  /**
   * Stop watching when in watch mode.
   */
  close: () => Promise<void>;
}>;
  • Example:
import { logger } from '@rsbuild/core';

// Example 1: run build
await rsbuild.build();

// Example 2: build and handle the error
try {
  await rsbuild.build();
} catch (err) {
  logger.error('Failed to build.');
  logger.error(err);
  process.exit(1);
}

// Example 3: build and get all assets
const { stats } = await rsbuild.build();

if (stats) {
  const { assets } = stats.toJson({
    // exclude unused fields to improve performance
    all: false,
    assets: true,
  });
  console.log(assets);
}

Monitor file changes

To watch file changes and re-build, set the watch option to true.

await rsbuild.build({
  watch: true,
});

In watch mode, the rsbuild.build() returns a close method, which can be used to stop watching:

const result = await rsbuild.build({
  watch: true,
});

await result.close();

Stats object

In non-watch mode, the rsbuild.build() returns an Rspack stats object.

For example, use the stats.toJson() method to get all assets information:

const result = await rsbuild.build();
const { stats } = result;

if (stats) {
  const { assets } = stats.toJson({
    // exclude unused fields to improve performance
    all: false,
    assets: true,
  });
  console.log(assets);
}

Custom compiler

In some cases, you may want to use a custom compiler:

import { rspack } from '@rsbuild/core';

const compiler = rspack({
  // ...
});
await rsbuild.build({
  compiler,
});

rsbuild.startDevServer

Start the local dev server. This method will:

  1. Start a development server that serves your application.
  2. Watch for file changes and trigger recompilation.
  • Type:
type StartDevServerOptions = {
  /**
   * Using a custom Rspack Compiler object.
   */
  compiler?: Compiler | MultiCompiler;
  /**
   * Whether to get port silently and not print any logs.
   * @default false
   */
  getPortSilently?: boolean;
};

type StartServerResult = {
  urls: string[];
  port: number;
  server: Server;
};

function StartDevServer(
  options?: StartDevServerOptions,
): Promise<StartServerResult>;
  • Example:

Start dev server:

import { logger } from '@rsbuild/core';

// Start dev server
await rsbuild.startDevServer();

// Start dev server and handle the error
try {
  await rsbuild.startDevServer();
} catch (err) {
  logger.error('Failed to start dev server.');
  logger.error(err);
  process.exit(1);
}

After successfully starting dev server, you can see the following logs:

➜ Local: http://localhost:3000 ➜ Network: http://192.168.0.1:3000

startDevServer returns the following parameters:

  • urls: URLs to access dev server.
  • port: The actual listening port number.
  • server: Server instance object.
const { urls, port, server } = await rsbuild.startDevServer();
console.log(urls); // ['http://localhost:3000', 'http://192.168.0.1:3000']
console.log(port); // 3000

// Close the dev server
await server.close();

Custom compiler

In some cases, you may want to use a custom compiler:

import { rspack } from '@rsbuild/core';

const compiler = rspack({
  // ...
});
await rsbuild.startDevServer({
  compiler,
});

Get port silently

In some cases, the default startup port number is already occupied. In this situation, Rsbuild will automatically increment the port number until it finds an available one. This process will output a prompt log. If you do not want this log, you can set getPortSilently to true.

await rsbuild.startDevServer({
  getPortSilently: true,
});

rsbuild.createDevServer

Rsbuild includes a built-in dev server designed to improve the development experience. When you run the rsbuild dev command, the server starts automatically and provides features such as page preview, routing, and hot module reloading.

If you want to integrate the Rsbuild dev server into a custom server, you can use the createDevServer method to create a dev server instance. Please refer to Dev server API for all available APIs.

If you want to use Rsbuild dev server to start the project directly, you can use the Rsbuild - startDevServer method directly. startDevServer is actually syntactic sugar for the following code:

const server = await rsbuild.createDevServer();

await server.listen();

rsbuild.preview

Start a server to preview the production build locally. This method should be executed after rsbuild.build.

  • Type:
type PreviewOptions = {
  /**
   * Whether to get port silently
   * @default false
   */
  getPortSilently?: boolean;
  /**
   * Whether to check if the dist directory exists and is not empty.
   * @default true
   */
  checkDistDir?: boolean;
};

type StartServerResult = {
  urls: string[];
  port: number;
  server: {
    close: () => Promise<void>;
  };
};

function preview(options?: PreviewOptions): Promise<StartServerResult>;
  • Example:

Start the server:

import { logger } from '@rsbuild/core';

// Start preview server
await rsbuild.preview();

// Start preview server and handle the error
try {
  await rsbuild.preview();
} catch (err) {
  logger.error('Failed to start preview server.');
  logger.error(err);
  process.exit(1);
}

preview returns the following parameters:

  • urls: URLs to access server.
  • port: The actual listening port number.
  • server: Server instance object.
const { urls, port, server } = await rsbuild.preview();
console.log(urls); // ['http://localhost:3000', 'http://192.168.0.1:3000']
console.log(port); // 3000

// Close the server
await server.close();

rsbuild.createCompiler

Create an Rspack Compiler instance. If there are multiple environments for this build, the return value is MultiCompiler.

  • Type:
function CreateCompiler(): Promise<Compiler | MultiCompiler>;
  • Example:
const compiler = await rsbuild.createCompiler();

You do not need to use this API unless you need to custom the dev server or other advanced scenarios.

rsbuild.addPlugins

Register one or more Rsbuild plugins, which can be called multiple times.

This method needs to be called before compiling. If it is called after compiling, it will not affect the compilation result.

  • Type:
type AddPluginsOptions = { before?: string; environment?: string };

function AddPlugins(
  plugins: Array<RsbuildPlugin | Falsy>,
  options?: AddPluginsOptions,
): void;
  • Example:
rsbuild.addPlugins([pluginFoo(), pluginBar()]);

// Insert before the bar plugin
rsbuild.addPlugins([pluginFoo()], { before: 'bar' });

// Add plugin for node environment
rsbuild.addPlugins([pluginFoo()], { environment: 'node' });

rsbuild.getPlugins

Get all the Rsbuild plugins registered in the current Rsbuild instance.

  • Type:
function GetPlugins(): RsbuildPlugin[];
  • Example:
console.log(rsbuild.getPlugins());

rsbuild.removePlugins

Removes one or more Rsbuild plugins, which can be called multiple times.

This method needs to be called before compiling. If it is called after compiling, it will not affect the compilation result.

  • Type:
function RemovePlugins(pluginNames: string[]): void;
  • Example:
// add plugin
const pluginFoo = pluginFoo();
rsbuild.addPlugins(pluginFoo);

// remove plugin
rsbuild.removePlugins([pluginFoo.name]);

rsbuild.isPluginExists

Determines if a plugin has been registered in the current Rsbuild instance.

  • Type:
function IsPluginExists(pluginName: string): boolean;
  • Example:
rsbuild.addPlugins([pluginFoo()]);

rsbuild.isPluginExists(pluginFoo().name); // true

rsbuild.initConfigs

Initialize and return the internal Rspack configurations used by Rsbuild. This method processes all plugins and configurations to generate the final Rspack configs.

Note: You typically don't need to call this method directly since it's automatically invoked by methods like rsbuild.build and rsbuild.startDevServer.

  • Type:
function InitConfigs(): Promise<{
  rspackConfigs: Rspack.Configuration[];
}>;
  • Example:
const rspackConfigs = await rsbuild.initConfigs();

console.log(rspackConfigs);

rsbuild.inspectConfig

Inspect and debug Rsbuild's internal configurations. It provides access to:

  • The resolved Rsbuild configuration
  • The environment-specific Rsbuild configurations
  • The generated Rspack configurations

The method serializes these configurations to strings and optionally writes them to disk for inspection.

  • Type:
type InspectConfigOptions = {
  // View the config in the specified environment
  // defaults to "development", can be set to "production"
  mode?: RsbuildMode;
  // Whether to enable verbose mode, display the complete content of the function in the config
  // defaults to `false`
  verbose?: boolean;
  // Specify the output path
  // defaults to the value of `output.distPath.root`
  outputPath?: string;
  // Whether to write the result to disk
  // defaults to `false`
  writeToDisk?: boolean;
};

async function InspectConfig(options?: InspectConfigOptions): Promise<{
  rsbuildConfig: string;
  bundlerConfigs: string[];
  environmentConfigs: string[];
  origin: {
    rsbuildConfig: RsbuildConfig;
    environmentConfigs: Record<string, EnvironmentConfig>;
    bundlerConfigs: BundlerConfigs[];
  };
}>;
TIP

To view the Rsbuild and Rspack configurations during the build process, use debug mode, or obtain them through hooks such as onBeforeBuild, onBeforeCreateCompile.

Example

Get the content of configs in string format:

const { rsbuildConfig, bundlerConfigs } = await rsbuild.inspectConfig();

console.log(rsbuildConfig, bundlerConfigs);

Write the config content to disk:

await rsbuild.inspectConfig({
  writeToDisk: true,
});

Output path

You can set the output path using outputPath. The default value is output.distPath.root.

If outputPath is a relative path, it will be concatenated relative to the value of output.distPath.root. You can also set outputPath to an absolute path, in which case the files will be written directly to that path. For example:

import path from 'node:path';

await rsbuild.inspectConfig({
  writeToDisk: true,
  outputPath: path.join(__dirname, 'custom-dir'),
});

rsbuild.onBeforeCreateCompiler

A callback function that is triggered after the Compiler instance has been created, but before the build process begins. This hook is called when you run rsbuild.startDevServer, rsbuild.build, or rsbuild.createCompiler.

You can access the Rspack configuration array through the bundlerConfigs parameter. The array may contain one or more Rspack configurations. It depends on whether multiple environments are configured.

  • Type:
function OnBeforeCreateCompiler(
  callback: (params: {
    bundlerConfigs: Rspack.Configuration[];
    environments: Record<string, EnvironmentContext>;
  }) => Promise<void> | void,
): void;
  • Example:
rsbuild.onBeforeCreateCompiler(({ bundlerConfigs }) => {
  console.log('the Rspack config is ', bundlerConfigs);
});

rsbuild.onAfterCreateCompiler

A callback function that is triggered after the compiler instance has been created, but before the build process. This hook is called when you run rsbuild.startDevServer, rsbuild.build, or rsbuild.createCompiler.

You can access the Compiler instance through the compiler parameter:

  • Type:
function OnAfterCreateCompiler(callback: (params: {
  compiler: Compiler | MultiCompiler;
  environments: Record<string, EnvironmentContext>;
}) => Promise<void> | void;): void;
  • Example:
rsbuild.onAfterCreateCompiler(({ compiler }) => {
  console.log('the compiler is ', compiler);
});

rsbuild.onBeforeBuild

A callback function that is triggered before the production build is executed.

You can access the Rspack configuration array through the bundlerConfigs parameter. The array may contain one or more Rspack configurations. It depends on whether multiple environments are configured.

Moreover, you can use isWatch to determine whether it is watch mode, and use isFirstCompile to determine whether it is the first build on watch mode.

  • Type:
function OnBeforeBuild(
  callback: (params: {
    isWatch: boolean;
    isFirstCompile: boolean;
    bundlerConfigs?: Rspack.Configuration[];
    environments: Record<string, EnvironmentContext>;
  }) => Promise<void> | void,
): void;
  • Example:
rsbuild.onBeforeBuild(({ bundlerConfigs }) => {
  console.log('the Rspack config is ', bundlerConfigs);
});

rsbuild.onAfterBuild

A callback function that is triggered after running the production build. You can access the build result information via the stats parameter.

Moreover, you can use isWatch to determine whether it is watch mode, and use isFirstCompile to determine whether it is the first build on watch mode.

  • Type:
function OnAfterBuild(
  callback: (params: {
    isFirstCompile: boolean;
    isWatch: boolean;
    stats?: Stats | MultiStats;
    environments: Record<string, EnvironmentContext>;
  }) => Promise<void> | void,
): void;
  • Example:
rsbuild.onAfterBuild(({ stats }) => {
  console.log(stats?.toJson());
});

rsbuild.onCloseBuild

Called when closing the build instance. Can be used to perform cleanup operations when the building is closed.

Rsbuild CLI will automatically call this hook after running rsbuild build, while users of the JavaScript API need to manually call the rsbuild.close() method to trigger this hook.

  • Type:
function onCloseBuild(callback: () => Promise<void> | void): void;
  • Example:
rsbuild.onCloseBuild(async () => {
  console.log('close build!');
});

rsbuild.onBeforeStartDevServer

Called before starting the dev server.

Use the server parameter to get the dev server instance, see Dev server API for more information.

  • Type:
type OnBeforeStartDevServerFn = (params: {
  /**
   * The dev server instance, the same as the return value of `createDevServer`.
   */
  server: RsbuildDevServer;
  /**
   * A read-only object that provides some context information about different environments.
   */
  environments: Record<string, EnvironmentContext>;
}) => MaybePromise<void>;

function OnBeforeStartDevServer(callback: OnBeforeStartDevServerFn): void;
  • Example:
rsbuild.onBeforeStartDevServer(({ server, environments }) => {
  console.log('before starting dev server.');
  console.log('the server is ', server);
  console.log('the environments contexts are: ', environments);
});

See Plugin hooks - onBeforeStartDevServer for more details.

rsbuild.onAfterStartDevServer

Called after starting the dev server, you can get the port number with the port parameter, and the page routes info with the routes parameter.

  • Type:
type Routes = Array<{
  entryName: string;
  pathname: string;
}>;

function OnAfterStartDevServer(
  callback: (params: {
    port: number;
    routes: Routes;
    environments: Record<string, EnvironmentContext>;
  }) => Promise<void> | void,
): void;
  • Example:
rsbuild.onAfterStartDevServer(({ port, routes }) => {
  console.log('this port is: ', port);
  console.log('this routes is: ', routes);
});

rsbuild.onCloseDevServer

Called when closing the dev server. Can be used to perform cleanup operations when the dev server is closed.

  • Type:
function onCloseDevServer(callback: () => Promise<void> | void): void;
  • Example:
rsbuild.onCloseDevServer(async () => {
  console.log('close dev server!');
});

rsbuild.onBeforeStartProdServer

Called before starting the production preview server.

  • Type:
function OnBeforeStartProdServer(callback: () => Promise<void> | void): void;
  • Example:
rsbuild.onBeforeStartProdServer(() => {
  console.log('before start!');
});

rsbuild.onAfterStartProdServer

Called after starting the production preview server, you can get the port number with the port parameter, and the page routes info with the routes parameter.

  • Type:
type Routes = Array<{
  entryName: string;
  pathname: string;
}>;

function OnAfterStartProdServer(
  callback: (params: {
    port: number;
    routes: Routes;
    environments: Record<string, EnvironmentContext>;
  }) => Promise<void> | void,
): void;
  • Example:
rsbuild.onAfterStartProdServer(({ port, routes }) => {
  console.log('this port is: ', port);
  console.log('this routes is: ', routes);
});

rsbuild.onDevCompileDone

Called after each development mode build, you can use isFirstCompile to determine whether it is the first build.

  • Type:
function OnDevCompileDone(
  callback: (params: {
    isFirstCompile: boolean;
    stats: Stats | MultiStats;
    environments: Record<string, EnvironmentContext>;
  }) => Promise<void> | void,
): void;
  • Example:
rsbuild.onDevCompileDone(({ isFirstCompile }) => {
  if (isFirstCompile) {
    console.log('first compile!');
  } else {
    console.log('re-compile!');
  }
});

rsbuild.onExit

Called when the process is going to exit, this hook can only execute synchronous code.

  • Type:
function OnExit(callback: () => void): void;
  • Example:
rsbuild.onExit(() => {
  console.log('exit!');
});

rsbuild.getRsbuildConfig

Get the Rsbuild config, this method must be called after the modifyRsbuildConfig hook is executed.

  • Type:
type GetRsbuildConfig = {
  (): Readonly<RsbuildConfig>;
  (type: 'original' | 'current'): Readonly<RsbuildConfig>;
  (type: 'normalized'): NormalizedConfig;
};
  • Parameters:

You can specify the type of Rsbuild config to read by using the type parameter:

// Get the original Rsbuild config defined by the user.
getRsbuildConfig('original');

// Get the current Rsbuild config.
// The content of this config will change at different execution stages of Rsbuild.
// For example, the content of the current Rsbuild config will be modified after running the `modifyRsbuildConfig` hook.
getRsbuildConfig('current');

// Get the normalized Rsbuild config.
// This method must be called after the `modifyRsbuildConfig` hook has been executed.
// It is equivalent to the `getNormalizedConfig` method.
getRsbuildConfig('normalized');
  • Example:
rsbuild.onBeforeBuild(() => {
  const config = rsbuild.getRsbuildConfig();
  console.log(config.html?.title);
});

rsbuild.getNormalizedConfig

Get the all normalized Rsbuild config or the Rsbuild config of a specified environment, this method must be called after the modifyRsbuildConfig hook is executed.

Compared with the api.getRsbuildConfig method, the config returned by this method has been normalized, and the type definition of the config will be narrowed. For example, the undefined type of config.html will be removed.

It is recommended to use this method to get the Rsbuild config.

  • Type:
/** Get the Rsbuild configuration of the specified environment */
function GetNormalizedConfig(options: {
  environment: string;
}): Readonly<NormalizedEnvironmentConfig>;

/** Get all Rsbuild configurations */
function GetNormalizedConfig(): Readonly<NormalizedConfig>;
  • Example:
rsbuild.onBeforeBuild(() => {
  const config = api.getNormalizedConfig();
  console.log(config.html.title);
});