Plugin Core

This section describes the core plugin types and APIs.

RsbuildPlugin

The type of the plugin object. The plugin object contains the following properties:

  • name: The name of the plugin, a unique identifier.
  • setup: The setup function of the plugin, which can be an async function. This function is called once when the plugin is initialized. The plugin API provides the context info, utility functions and lifecycle hooks. For a complete introduction to lifecycle hooks, please read the Plugin Hooks chapter.
  • pre: Declare the names of pre-plugins, which will be executed before the current plugin.
  • post: Declare the names of post-plugins, which will be executed after the current plugin.
  • remove: Declare the plugins that need to be removed, you can pass an array of plugin names.

The type of the plugin object, which contains the following properties:

type RsbuildPlugin = {
  name: string;
  pre?: string[];
  post?: string[];
  remove?: string[];
  setup: (api: RsbuildPluginAPI) => Promise<void> | void;
};

You can import this type from @rsbuild/core:

import type { RsbuildPlugin } from '@rsbuild/core';

export default (): RsbuildPlugin => ({
  name: 'plugin-foo',

  pre: ['plugin-bar'],

  setup: (api) => {
    api.onAfterBuild(() => {
      console.log('after build!');
    });
  },
});

Pre-Plugins

By default, plugins are executed in the order they are added. You can declare pre-execution plugins using the pre field.

For example, consider the following two plugins:

const pluginFoo = {
  name: 'plugin-foo',
};

const pluginBar = {
  name: 'plugin-bar',
  pre: ['plugin-foo'],
};

The Bar plugin is configured with the Foo plugin in its pre field, so the Foo plugin will always be executed before the Bar plugin.

Post-Plugins

Similarly, you can declare post-execution plugins using the post field.

const pluginFoo = {
  name: 'plugin-foo',
};

const pluginBar = {
  name: 'plugin-bar',
  post: ['plugin-foo'],
};

The Bar plugin is configured with the Foo plugin in its post field, so the Foo plugin will always be executed after the Bar plugin.

Removing Plugins

You can remove other plugins within a plugin using the remove field.

const pluginFoo = {
  name: 'plugin-foo',
};

const pluginBar = {
  name: 'plugin-bar',
  remove: ['plugin-foo'],
};

For example, if you register both the Foo and Bar plugins mentioned above, the Foo plugin will not take effect because the Bar plugin declares the removal of the Foo plugin.

api.context

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

The content of api.context is exactly the same as rsbuild.context, please refer to rsbuild.context.

  • Example:
const pluginFoo = () => ({
  setup(api) {
    console.log(api.context.distPath);
  },
});

api.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:
const pluginFoo = () => ({
  setup(api) {
    const config = api.getRsbuildConfig();
    console.log(config.html?.title);
  },
});

api.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:
const pluginFoo = () => ({
  setup(api) {
    const config = api.getNormalizedConfig();
    console.log(config.html.title);
  },
});

api.isPluginExists

Determines whether a plugin has been registered.

  • Type:
function IsPluginExists(pluginName: string): boolean;
  • Example:
export default () => ({
  setup: (api) => {
    console.log(api.isPluginExists('plugin-foo'));
  },
});

api.transform

Used to transform the code of modules.

  • Version: >= 0.6.0
  • Type:
function Transform(
  descriptor: TransformDescriptor,
  handler: TransformHandler,
): void;

api.transform accepts two params:

  • descriptor: an object describing the module's matching conditions.
  • handler: a transformation function that takes the current module code and returns the transformed code.

Example

For example, match modules with the .pug extension and transform them to JavaScript code:

import pug from 'pug';

const pluginPug = () => ({
  name: 'my-pug-plugin',
  setup(api) {
    api.transform({ test: /\.pug$/ }, ({ code }) => {
      const templateCode = pug.compileClient(code, {});
      return `${templateCode}; module.exports = template;`;
    });
  },
});

Descriptor Param

The descriptor param is an object describing the module's matching conditions.

  • Type:
type TransformDescriptor = {
  test?: RuleSetCondition;
  targets?: RsbuildTarget[];
  environments?: string[];
  resourceQuery?: RuleSetCondition;
  raw?: boolean;
};

The descriptor param supports the following matching conditions:

  • test: matches module's path (without query), the same as Rspack's Rule.test.
api.transform({ test: /\.pug$/ }, ({ code }) => {
  // ...
});
  • targets: matches the Rsbuild output.target, and applies the current transform function only to the matched targets.
api.transform({ test: /\.pug$/, targets: ['web'] }, ({ code }) => {
  // ...
});
  • environments: matches the Rsbuild environment name, and applies the current transform function only to the matched environments.
api.transform({ test: /\.pug$/, environments: ['web'] }, ({ code }) => {
  // ...
});
api.transform({ resourceQuery: /raw/ }, ({ code }) => {
  // ...
});
  • raw: if raw is true, the transform handler will receive the Buffer type code instead of the string type.
api.transform({ test: /\.node$/, raw: true }, ({ code }) => {
  // ...
});

Handler Param

The handler param is a transformation function that takes the current module code and returns the transformed code.

  • Type:
type TransformContext = {
  code: string;
  resource: string;
  resourcePath: string;
  resourceQuery: string;
  environment: EnvironmentContext;
  addDependency: (file: string) => void;
  emitFile: (
    name: string,
    content: string | Buffer,
    sourceMap?: string,
    assetInfo?: Record<string, any>,
  ) => void;
};

type TransformResult =
  | string
  | {
      code: string;
      map?: string | RspackSourceMap | null;
    };

type TransformHandler = (
  context: TransformContext,
) => MaybePromise<TransformResult>;

The handler function provides the following params:

  • code: The code of the module.
  • resource: The absolute path of the module, including the query.
  • resourcePath: The absolute path of the module, without the query.
  • resourceQuery: The query of the module.
  • environment: The environment context for current build.
  • addDependency: Add an additional file as the dependency. The file will be watched and changes to the file will trigger rebuild.
  • emitFile: Emits a file to the build output.

For example:

api.transform(
  { test: /\.pug$/ },
  ({ code, resource, resourcePath, resourceQuery }) => {
    console.log(code); // -> some code
    console.log(resource); // -> '/home/user/project/src/template.pug?foo=123'
    console.log(resourcePath); // -> '/home/user/project/src/template.pug'
    console.log(resourceQuery); // -> '?foo=123'
  },
);

Difference with loader

api.transform can be thought of as a lightweight implementation of Rspack loader. It provides a simple and easy to use API and automatically calls Rspack loader at the backend to transform the code.

In Rsbuild plugins, you can quickly implement code transformation functions using api.transform, which can handle the majority of common scenarios without having to learn how to write an Rspack loader.

Note that for some complex code transformation scenarios, api.transform may not be sufficient. In such situations, you can implement it using the Rspack loader.

api.processAssets

Modify assets before emitting, the same as Rspack's compilation.hooks.processAssets hook.

  • Version: >= 1.0.0
  • Type:
function processAssets(
  descriptor: ProcessAssetsDescriptor,
  handler: ProcessAssetsHandler,
): void;

api.processAssets accepts two params:

  • descriptor: an object to describes the stage and matching conditions that trigger processAssets.
  • handler: A callback function that receives the assets object and allows you to modify it.

Example

  • Emit a new asset in the additional stage:
api.processAssets(
  { stage: 'additional' },
  ({ assets, sources, compilation }) => {
    const source = new sources.RawSource('This is a new asset!');
    compilation.emitAsset('new-asset.txt', source);
  },
);
  • Updating an existing asset:
api.processAssets(
  { stage: 'additions' },
  ({ assets, sources, compilation }) => {
    const asset = assets['foo.js'];
    if (!asset) {
      return;
    }

    const oldContent = asset.source();
    const newContent = oldContent + '\nconsole.log("hello world!")';
    const source = new sources.RawSource(newContent);

    compilation.updateAsset(assetName, source);
  },
);
  • Removing an asset:
api.processAssets({ stage: 'stage-optimize' }, ({ assets, compilation }) => {
  const assetName = 'unwanted-script.js';
  if (assets[assetName]) {
    compilation.deleteAsset(assetName);
  }
});

Descriptor Param

The descriptor parameter is an object to describes the stage and matching conditions that trigger processAssets.

  • Type:
type ProcessAssetsDescriptor = {
  stage: ProcessAssetsStage;
  targets?: RsbuildTarget[];
  environments?: string[];
};

The descriptor param supports the following properties:

  • stage: Rspack internally divides processAssets into multiple stages (refer to process assets stages). You can choose the appropriate stage based on the operations you need to perform.
api.processAssets({ stage: 'additional' }, ({ assets }) => {
  // ...
});
  • targets: Matches the Rsbuild output.target, and applies the current processAssets function only to the matched targets.
api.processAssets({ stage: 'additional', targets: ['web'] }, ({ assets }) => {
  // ...
});
  • environments: matches the Rsbuild environment name, and applies the current processAssets function only to the matched environments.
api.processAssets(
  { stage: 'additional', environments: ['web'] },
  ({ assets }) => {
    // ...
  },
);

Handler Param

The handler parameter is a callback function that receives an assets object and allows you to modify it.

  • Type:
type ProcessAssetsHandler = (context: {
  assets: Record<string, Rspack.sources.Source>;
  compiler: Rspack.Compiler;
  compilation: Rspack.Compilation;
  environment: EnvironmentContext;
  sources: RspackSources;
}) => Promise<void> | void;

The handler function provides the following parameters:

  • assets: An object where key is the asset's pathname, and the value is data of the asset represented by the Source.
  • compiler: The Compiler object of Rspack.
  • compilation: The Compilation object of Rspack.
  • environment: The environment context of the current build.
  • sources: The Rspack Sources object, which contains multiple classes which represent a Source.

Process assets stages

Here's the list of supported stages. Rspack will execute these stages sequentially from top to bottom. Please select the appropriate stage based on the operation you need to perform.

  • additional — add additional assets to the compilation.
  • pre-process — basic preprocessing of the assets.
  • derived — derive new assets from the existing assets.
  • additions — add additional sections to the existing assets e.g. banner or initialization code.
  • optimize — optimize existing assets in a general way.
  • optimize-count — optimize the count of existing assets, e.g. by merging them.
  • optimize-compatibility — optimize the compatibility of existing assets, e.g. add polyfills or vendor prefixes.
  • optimize-size — optimize the size of existing assets, e.g. by minimizing or omitting whitespace.
  • dev-tooling — add development tooling to the assets, e.g. by extracting a source map.
  • optimize-inline — optimize the numbers of existing assets by inlining assets into other assets.
  • summarize — summarize the list of existing assets.
  • optimize-hash — optimize the hashes of the assets, e.g. by generating real hashes of the asset content.
  • optimize-transfer — optimize the transfer of existing assets, e.g. by preparing a compressed (gzip) file as separate asset.
  • analyse — analyze the existing assets.
  • report — creating assets for the reporting purposes.

api.expose

Used for plugin communication.

api.expose can explicitly expose some properties or methods of the current plugin, and other plugins can get these APIs through api.useExposed.

  • Type:
/**
 * @param id Unique identifier, using Symbol can avoid naming conflicts
 * @param api Properties or methods to be exposed, it is recommended to use object format
 */
function expose<T = any>(id: string | symbol, api: T): void;
  • Example:
const pluginParent = () => ({
  name: 'plugin-parent',
  setup(api) {
    api.expose('plugin-parent', {
      value: 1,
      double: (val: number) => val * 2,
    });
  },
});

api.useExposed

Used for plugin communication.

api.useExposed can get the properties or methods exposed by other plugins.

  • Type:
/**
 * @param id Unique identifier
 * @returns The properties or methods obtained
 */
function useExposed<T = any>(id: string | symbol): T | undefined;
  • Example:
const pluginChild = () => ({
  name: 'plugin-child',
  pre: ['plugin-parent'],
  setup(api) {
    const parentApi = api.useExposed('plugin-parent');
    if (parentApi) {
      console.log(parentApi.value); // -> 1
      console.log(parentApi.double(1)); // -> 2
    }
  },
});

Identifiers

You can use Symbol as a unique identifier to avoid potential naming conflicts:

// pluginParent.ts
export const PARENT_API_ID = Symbol('plugin-parent');

const pluginParent = () => ({
  name: 'plugin-parent',
  setup(api) {
    api.expose(PARENT_API_ID, {
      // some api
    });
  },
});

// pluginChild.ts
import { PARENT_API_ID } from './pluginParent';

const pluginChild = () => ({
  name: 'plugin-child',
  setup(api) {
    const parentApi = api.useExposed(PARENT_API_ID);
    if (parentApi) {
      console.log(parentApi);
    }
  },
});

Type Declaration

You can declare types through the generics of the function:

// pluginParent.ts
export type ParentAPI = {
  // ...
};

// pluginChild.ts
import type { ParentAPI } from './pluginParent';

const pluginChild = () => ({
  name: 'plugin-child',
  setup(api) {
    const parentApi = api.useExposed<ParentAPI>(PARENT_API_ID);
    if (parentApi) {
      console.log(parentApi);
    }
  },
});

Execution Order

When communicating between plugins, you need to be aware of the order in which the plugins are executed.

For example, in the above example, if pluginParent is not registered, or registers after pluginChild, then api.useExposed('plugin-parent') will return an undefined.

You can use the pre, post options of the plugin object, and the order option of the plugin hook to ensure the order is correct.