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 infos.

rsbuild.context.entry

The entry object from the source.entry option.

  • Type
type RsbuildEntry = Record<string, string | string[]>;

rsbuild.context.target

Build target type, corresponding to the target option of createRsbuild method.

  • Type
type RsbuildTarget = 'web' | 'node' | 'web-worker';

type Context = {
  target: RsbuildTarget | RsbuildTarget[];
};

rsbuild.context.rootPath

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

  • Type
type RootPath = string;

rsbuild.context.srcPath

The absolute path to the src directory.

  • Type
type SrcPath = string;

rsbuild.context.distPath

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

  • Type
type DistPath = string;

rsbuild.context.cachePath

The absolute path of the build cache files.

  • Type
type CachePath = string;

rsbuild.context.configPath

The absolute path to the config file of higher-level solution, corresponding to the configPath option of createRsbuild method.

  • Type
type ConfigPath = string | undefined;

rsbuild.context.tsconfigPath

The absolute path of the tsconfig.json file, or undefined if the tsconfig.json file does not exist in current project.

  • Type
type TsconfigPath = string | undefined;

rsbuild.context.devServer

Dev Server information, including the current Dev Server hostname and port number.

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

rsbuild.context.bundlerType

The bundler type of current build.

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

rsbuild.build

Perform a production build.

  • Type
type BuildOptions = {
  mode?: 'development' | 'production';
  watch?: boolean;
  // custom Compiler object
  compiler?: Compiler | MultiCompiler;
};

function Build(options?: BuildOptions): Promise<void>;
  • Example
await rsbuild.build();

Development environment build

If you need to perform a development build, you can set the mode option to 'development'.

await rsbuild.build({
  mode: 'development',
});

Monitor file changes

If you need to watch file changes and re-build, you can set the watch option to true.

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

Custom Compiler

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

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

rsbuild.startDevServer

Start the local dev server.

  • Type
type StartDevServerOptions = {
  // Whether to open the page in browser on startup
  open?: boolean;
  // Whether to output URL infos, the default is true
  printURLs?: boolean | Function;
  // Whether to throw an exception when the port is occupied, the default is false
  strictPort?: boolean;
  // custom Compiler object
  compiler?: Compiler | MultiCompiler;
  // Whether to get the port silently, the default is false
  getPortSliently?: boolean;
  // custom logger
  logger?: Logger;
};

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

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

Start Dev Server:

await rsbuild.startDevServer();

After successfully starting Dev Server, you can see the following logs:

  > Local:    http://localhost:8080
  > Network:  http://192.168.0.1:8080

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:8080', 'http://192.168.0.1:8080']
console.log(port); // 8080

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

Disable Print URLs

Setting printURLs to false to disable the default URL output, so you can custom the logs.

await rsbuild.startDevServer({
  printURLs: false,
});

You can also directly configure printURLs as a function to modify URLs, such as adding a subpath to each URL:

await rsbuild.startDevServer({
  printURLs: (urls) => {
    return urls.map(({ label, url }) => ({
      label,
      url: `${url}/path`,
    }));
  },
});

Strict Port

When a port is occupied, Rsbuild will automatically increment the port number until an available port is found.

Set strictPort to true and Rsbuild will throw an exception when the port is occupied.

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

Custom Compiler

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

const compiler = webpack({
  // ...
});
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 getPortSliently to true.

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

Custom Logger

By default, Rsbuild uses rslog to output logs. You can customize the log output object through the logger parameter.

const customLogger = {
  // You need to define the following methods
  info(msg: string) {
    console.log(msg);
  },
  error(msg: string) {
    console.error(msg);
  },
  warn(msg: string) {
    console.warn(msg);
  },
  success(msg: string) {
    console.log(`✅ msg`);
  },
  debug(msg: string) {
    if (process.env.DEBUG) {
      console.log(msg);
    }
  },
  log(msg: string) {
    console.log(msg);
  };
}

await rsbuild.startDevServer({
  logger: customLogger,
});

Then Rsbuild will use the custom logger to output logs.

rsbuild.preview

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

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

function server(): Promise<StartServerResult>;
  • Example

Start the server:

await rsbuild.preview();

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:8080', 'http://192.168.0.1:8080']
console.log(port); // 8080

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

rsbuild.createCompiler

Create a Compiler object.

When the target option of createRsbuild contains only one value, the return value is Compiler; when target contains multiple values, the return value is MultiCompiler.

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

In most scenarios, 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 } | { after?: string };

function AddPlugins(
  plugins: RsbuildPlugins[],
  options?: AddPluginsOptions,
): Promise<void>;
  • Example
rsbuild.addPlugins([pluginFoo(), pluginBar()]);

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

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

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 whether a plugin has been registered.

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

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

rsbuild.inspectConfig

Inspect the final generated Rsbuild config and bundler config.

TIP

The inspectConfig method does not support simultaneous use with the startDevServer / build method.

When you need to view the complete Rsbuild and bundler configurations during the build process, you can use the debug mode or obtain them through hooks such as onBeforeBuild and onBeforeCreateCompile.

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

async function InspectConfig(options?: InspectConfigOptions): Promise<{
  rsbuildConfig: string;
  bundlerConfigs: string[];
  origin: {
    rsbuildConfig: RsbuildConfig;
    bundlerConfigs: BundlerConfigs[];
  };
}>;
  • Example

Get the config content in string format:

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

console.log(rsbuildConfig, bundlerConfigs);

Write the config content to disk:

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

rsbuild.onBeforeCreateCompiler

onBeforeCreateCompiler is 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 Compiler instance object through the compiler parameter:

  • If the current bundler is webpack, you will get the webpack Compiler object.

  • If the current bundler is Rspack, you will get the Rspack Compiler object.

  • Type

function OnBeforeCreateCompiler(
  callback: (params: {
    bundlerConfigs: WebpackConfig[] | RspackConfig[];
  }) => Promise<void> | void,
): void;
  • Example
rsbuild.onBeforeCreateCompiler(({ bundlerConfigs }) => {
  console.log('the bundler config is ', bundlerConfigs);
});

rsbuild.onAfterCreateCompiler

onAfterCreateCompiler is 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 object through the compiler parameter:

  • If the current bundler is webpack, you will get the webpack Compiler object.

  • If the current bundler is Rspack, you will get the Rspack Compiler object.

  • Type

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

rsbuild.onBeforeBuild

onBeforeBuild is a callback function that is triggered before the production build is executed. You can access the final configuration array of the underlying bundler through the `bundlerConfigs' parameter:

  • If the current bundler is webpack, you will get a webpack configuration array.

  • If the current bundler is Rspack, you will get an Rspack configuration array.

  • The configuration array can contain one or more configurations, depending on the current target config of Rsbuild.

  • Type

function OnBeforeBuild(
  callback: (params: {
    bundlerConfigs?: WebpackConfig[] | RspackConfig[];
  }) => Promise<void> | void,
): void;
  • Example
rsbuild.onBeforeBuild(({ bundlerConfigs }) => {
  console.log('the bundler config is ', bundlerConfigs);
});

rsbuild.onAfterBuild

onAfterBuild is a callback function that is triggered after running the production build. You can access the build result information via the `stats' parameter:

  • If the current bundler is webpack, you will get webpack Stats.

  • If the current bundler is Rspack, you will get Rspack Stats.

  • Type

function OnAfterBuild(
  callback: (params: { stats?: Stats | MultiStats }) => Promise<void> | void,
): void;
  • Example
rsbuild.onAfterBuild(({ stats }) => {
  console.log(stats?.toJson());
});

rsbuild.onBeforeStartDevServer

Called before starting the development server.

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

rsbuild.onAfterStartDevServer

Called after starting the development server, you can get the port number through the port parameter.

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

rsbuild.onDevCompileDone

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

  • Type
function OnDevCompileDone(
  callback: (params: { isFirstCompile: boolean }) => 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
function GetRsbuildConfig(): Readonly<RsbuildConfig>;
  • Example
rsbuild.onBeforeBuild(() => {
  const config = rsbuild.getRsbuildConfig();
  console.log(config.html?.title);
});

rsbuild.getNormalizedConfig

Get the normalized Rsbuild config, 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
function GetNormalizedConfig(): Readonly<NormalizedConfig>;
  • Example
rsbuild.onBeforeBuild(() => {
  const config = api.getNormalizedConfig();
  console.log(config.html.title);
});

rsbuild.getHTMLPaths

Get path information for all HTML assets.

This method will return an object, the key is the entry name and the value is the relative path of the HTML file in the dist directory.

  • Type
function GetHTMLPaths(): Record<string, string>;
  • Example
rsbuild.onBeforeBuild(() => {
  const htmlPaths = api.getHTMLPaths();
  console.log(htmlPaths); // { main: 'html/main/index.html' };
});