Plugin Hooks

This chapter introduces the plugin hooks available for Rsbuild plugins.

Overview

Common Hooks

Dev Hooks

Called only when running the rsbuild dev command or the rsbuild.startDevServer() method.

Build Hooks

Called only when running the rsbuild build command or the rsbuild.build() method.

  • onBeforeBuild: Called before running the production build.
  • onAfterBuild: Called after running the production build. You can get the build result information.

Preview Hooks

Called only when running the rsbuild preview command or the rsbuild.preview() method.

Hooks Order

Dev Hooks

When the rsbuild dev command or rsbuild.startDevServer() method is executed, Rsbuild will execute the following hooks in order:

Build Hooks

When the rsbuild build command or rsbuild.build() method is executed, Rsbuild will execute the following hooks in order:

Preview Hooks

When executing the rsbuild preview command or rsbuild.preview() method, Rsbuild will execute the following hooks in order:

Callback Order

Default Behavior

If multiple plugins register the same hook, the callback functions of the hook will execute in the order in which they were registered.

In the following example, the console will output '1' and '2' in sequence:

const plugin1 = () => ({
  setup: (api) => {
    api.modifyRsbuildConfig(() => console.log('1'));
  },
});

const plugin2 = () => ({
  setup: (api) => {
    api.modifyRsbuildConfig(() => console.log('2'));
  },
});

rsbuild.addPlugins([plugin1, plugin2]);

order Field

When registering a hook, you can declare the order of hook through the order field.

type HookDescriptor<T extends (...args: any[]) => any> = {
  handler: T;
  order: 'pre' | 'post' | 'default';
};

In the following example, the console will sequentially output '2' and '1', because order was set to pre when plugin2 called modifyRsbuildConfig.

const plugin1 = () => ({
  setup: (api) => {
    api.modifyRsbuildConfig(() => console.log('1'));
  },
});

const plugin2 = () => ({
  setup: (api) => {
    api.modifyRsbuildConfig({
      handler: () => console.log('2'),
      order: 'pre',
    });
  },
});

rsbuild.addPlugins([plugin1, plugin2]);

Common Hooks

modifyRsbuildConfig

Modify the config passed to the Rsbuild, you can directly modify the config object, or return a new object to replace the previous object.

  • Type:
type ModifyRsbuildConfigUtils = {
  mergeRsbuildConfig: typeof mergeRsbuildConfig;
};

function ModifyRsbuildConfig(
  callback: (
    config: RsbuildConfig,
    utils: ModifyRsbuildConfigUtils,
  ) => MaybePromise<RsbuildConfig | void>,
): void;
  • Example: Setting a default value for a specific config option:
const myPlugin = () => ({
  setup: (api) => {
    api.modifyRsbuildConfig((config) => {
      config.html ||= {};
      config.html.title = 'My Default Title';
    });
  },
});
  • Example: Using mergeRsbuildConfig to merge config objects, and return the merged object.
import type { RsbuildConfig } from '@rsbuild/core';

const myPlugin = () => ({
  setup: (api) => {
    api.modifyRsbuildConfig((userConfig, { mergeRsbuildConfig }) => {
      const extraConfig: RsbuildConfig = {
        source: {
          // ...
        },
        output: {
          // ...
        },
      };

      // extraConfig will override fields in userConfig,
      // If you do not want to override the fields in userConfig,
      // you can adjust to `mergeRsbuildConfig(extraConfig, userConfig)`
      return mergeRsbuildConfig(userConfig, extraConfig);
    });
  },
});

modifyRspackConfig

To modify the final Rspack config object, you can directly modify the config object, or return a new object to replace the previous object.

  • Type:
type ModifyRspackConfigUtils = {
  env: NodeEnv;
  isDev: boolean;
  isProd: boolean;
  target: RsbuildTarget;
  isServer: boolean;
  isWebWorker: boolean;
  rspack: Rspack;
};

function ModifyRspackConfig(
  callback: (
    config: RspackConfig,
    utils: ModifyRspackConfigUtils,
  ) => Promise<RspackConfig | void> | RspackConfig | void,
): void;
  • Example:
const myPlugin = () => ({
  setup: (api) => {
    api.modifyRspackConfig((config, utils) => {
      if (utils.env === 'development') {
        config.devtool = 'eval-cheap-source-map';
      }
    });
  },
});

modifyBundlerChain

rspack-chain is a utility library for configuring Rspack. It provides a chaining API, making the configuration of Rspack more flexible. By using rspack-chain, you can more easily modify and extend Rspack configurations without directly manipulating the complex configuration object.

modifyBundlerChain is used to call the rspack-chain to modify the Rspack configuration.

This hook only supports modifying the configuration of the non-differentiated parts of Rspack and webpack. For example, modifying the devtool configuration option (Rspack and webpack have the same devtool property value type), or adding an Rspack-compatible webpack plugin.

  • Type:
type ModifyBundlerChainUtils = {
  env: NodeEnv;
  isDev: boolean;
  isProd: boolean;
  target: RsbuildTarget;
  isServer: boolean;
  isWebWorker: boolean;
  CHAIN_ID: ChainIdentifier;
  HtmlPlugin: typeof import('html-webpack-plugin');
  bundler: {
    BannerPlugin: rspack.BannerPlugin;
    DefinePlugin: rspack.DefinePlugin;
    IgnorePlugin: rspack.IgnorePlugin;
    ProvidePlugin: rspack.ProvidePlugin;
    HotModuleReplacementPlugin: rspack.HotModuleReplacementPlugin;
  };
};

function ModifyBundlerChain(
  callback: (
    chain: RspackChain,
    utils: ModifyBundlerChainUtils,
  ) => Promise<void> | void,
): void;
  • Example:
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';

const myPlugin = () => ({
  setup: (api) => {
    api.modifyBundlerChain((chain, utils) => {
      if (utils.env === 'development') {
        chain.devtool('eval');
      }

      chain.plugin('bundle-analyze').use(BundleAnalyzerPlugin);
    });
  },
});

modifyHTMLTags

Modify the tags that are injected into the HTML.

  • Type:
type HtmlBasicTag = {
  // Tag name
  tag: string;
  // Attributes of the tag
  attrs?: Record<string, string | boolean | null | undefined>;
  // innerHTML of the tag
  children?: string;
};

type HTMLTags = {
  // Tags group inserted into <head>
  headTags: HtmlBasicTag[];
  // Tags group inserted into <body>
  bodyTags: HtmlBasicTag[];
};

type Context = {
  /**
   * The Compilation object of Rspack.
   */
  compilation: Rspack.Compilation;
  /**
   * URL prefix of assets.
   * @example 'https://example.com/'
   */
  assetPrefix: string;
  /**
   * The name of the HTML file, relative to the dist directory.
   * @example 'index.html'
   */
  filename: string;
};

function ModifyHTMLTags(
  callback: (tags: HTMLTags, context: Context) => MaybePromise<HTMLTags>,
): void;
  • Example:
const myPlugin = () => ({
  setup: (api) => {
    api.modifyHTMLTags(({ headTags, bodyTags }) => {
      headTags.push({
        tag: 'script',
        attrs: { src: 'https://example.com/foo.js' },
      });
      bodyTags.push({
        tag: 'script',
        children: 'console.log("hello world!");',
      });

      return { headTags, bodyTags };
    });
  },
});

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 Rspack configuration array through the bundlerConfigs parameter. The array may contain one or more Rspack configurations, depending on the value of the Rsbuild's output.targets configuration.

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

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

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

Build Hooks

onBeforeBuild

onBeforeBuild is 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, depending on the value of the Rsbuild's output.targets configuration.

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

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:

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

  • Type:
function OnAfterBuild(
  callback: (params: {
    isFirstCompile: boolean;
    stats?: Stats | MultiStats;
  }) => Promise<void> | void,
): void;
  • Example:
const myPlugin = () => ({
  setup: (api) => {
    api.onAfterBuild(({ isFirstCompile, stats }) => {
      console.log(stats?.toJson(), isFirstCompile);
    });
  },
});

Dev Hooks

onBeforeStartDevServer

Called before starting the dev server.

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

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 }) => Promise<void> | void,
): void;
  • Example:
const myPlugin = () => ({
  setup: (api) => {
    api.onAfterStartDevServer(({ port, routes }) => {
      console.log('this port is: ', port);
      console.log('this routes is: ', routes);
    });
  },
});

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;
    stats: Stats | MultiStats;
  }) => Promise<void> | void,
): void;
  • Example:
const myPlugin = () => ({
  setup: (api) => {
    api.onDevCompileDone(({ isFirstCompile }) => {
      if (isFirstCompile) {
        console.log('first compile!');
      } else {
        console.log('re-compile!');
      }
    });
  },
});

onCloseDevServer

Called when close the dev server.

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

Preview Hooks

onBeforeStartProdServer

Called before starting the production preview server.

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

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 }) => Promise<void> | void,
): void;
  • Example:
const myPlugin = () => ({
  setup: (api) => {
    api.onAfterStartProdServer(({ port, routes }) => {
      console.log('this port is: ', port);
      console.log('this routes is: ', routes);
    });
  },
});

Other Hooks

onExit

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

  • Type:
function OnExit(callback: () => void): void;
  • Example:
const myPlugin = () => ({
  setup: (api) => {
    api.onExit(() => {
      console.log('exit!');
    });
  },
});