Tools

This section describes some low-level tools configurations in Rsbuild.

tools.autoprefixer

  • Type: Object | Function
  • Default:
{
  flexbox: 'no-2009',
  // Depends on the browserslist config in the project
  // and the `output.overrideBrowserslist` (higher priority) config
  overrideBrowserslist: browserslist,
}

You can modify the config of autoprefixer by tools.autoprefixer.

Object Type

When tools.autoprefixer is configured as Object type, it is merged with the default config through Object.assign. For example:

export default {
  tools: {
    autoprefixer: {
      flexbox: 'no-2009',
    },
  },
};

Function Type

When tools.autoprefixer is a Function, the default config is passed as the first parameter and can be directly modified or returned as the final result. For example:

export default {
  tools: {
    autoprefixer(config) {
      // modify flexbox config
      config.flexbox = 'no-2009';
    },
  },
};

tools.bundlerChain

  • Type: Function | undefined
  • Default: undefined

You can modify the webpack and Rspack configuration by configuring tools.bundlerChain which is type of Function. The function receives two parameters, the first is the original bundler chain object, and the second is an object containing some utils.

What is BundlerChain

Bundler chain is a subset of webpack chain, which contains part of the webpack chain API that you can use to modify both webpack and Rspack configuration.

Configurations modified via bundler chain will work on both webpack and Rspack builds. Note that the bundler chain only supports modifying the configuration of the non-differentiated parts of webpack and Rspack. For example, modifying the devtool configuration option (webpack and Rspack have the same devtool property value type), or adding an Rspack-compatible webpack plugin.

tools.bundlerChain is executed earlier than tools.webpackChain / tools.webpack / tools.rspack and thus will be overridden by changes in others.

Utils

env

  • Type: 'development' | 'production' | 'test'

The env parameter can be used to determine whether the current environment is development, production or test. For example:

export default {
  tools: {
    bundlerChain: (chain, { env }) => {
      if (env === 'development') {
        chain.devtool('cheap-module-eval-source-map');
      }
    },
  },
};

isProd

  • Type: boolean

The isProd parameter can be used to determine whether the current environment is production. For example:

export default {
  tools: {
    bundlerChain: (chain, { isProd }) => {
      if (isProd) {
        chain.devtool('source-map');
      }
    },
  },
};

target

  • Type: 'web' | 'node' | 'web-worker'

The target parameter can be used to determine the current environment. For example:

export default {
  tools: {
    bundlerChain: (chain, { target }) => {
      if (target === 'node') {
        // ...
      }
    },
  },
};

isServer

  • Type: boolean

Determines whether the target environment is node, equivalent to target === 'node'.

export default {
  tools: {
    bundlerChain: (chain, { isServer }) => {
      if (isServer) {
        // ...
      }
    },
  },
};

isWebWorker

  • Type: boolean

Determines whether the target environment is web-worker, equivalent to target === 'web-worker'.

export default {
  tools: {
    bundlerChain: (chain, { isWebWorker }) => {
      if (isWebWorker) {
        // ...
      }
    },
  },
};

HtmlPlugin

  • Type: typeof import('html-webpack-plugin')

The instance of html-webpack-plugin:

export default {
  tools: {
    bundlerChain: (chain, { HtmlPlugin }) => {
      console.log(HtmlPlugin);
    },
  },
};

CHAIN_ID

Some common Chain IDs are predefined in the Rsbuild, and you can use these IDs to locate the built-in Rule or Plugin.

TIP

Please note that some of the rules or plugins listed below are not available by default. They will only be included in the Rspack or webpack configuration when you enable specific options or register certain plugins.

For example, the RULE.STYLUS rule exists only when the Stylus plugin is registered.

CHAIN_ID.RULE
ID Description
RULE.MJS Rule for mjs
RULE.CSS Rule for css
RULE.LESS Rule for less
RULE.SASS Rule for sass
RULE.STYLUS Rule for stylus
RULE.TOML Rule for toml
RULE.YAML Rule for yaml
RULE.WASM Rule for WASM
RULE.NODE Rule for node

CHAIN_ID.ONE_OF

ONE_OF.XXX can match a certain type of rule in the rule array.

ID Description
ONE_OF.SVG Rules for SVG, automatic choice between data URI and separate file
ONE_OF.SVG_URL Rules for SVG, output as a separate file
ONE_OF.SVG_INLINE Rules for SVG, inlined into bundles as data URIs
ONE_OF.SVG_ASSETS Rules for SVG, automatic choice between data URI and separate file

CHAIN_ID.USE

USE.XXX can match a certain loader.

ID Description
USE.LESS correspond to less-loader
USE.SASS correspond to sass-loader
USE.STYLUS correspond to stylus-loader
USE.VUE correspond to vue-loader
USE.TOML correspond to toml-loader
USE.YAML correspond to yaml-loader
USE.NODE correspond to node-loader
USE.SVGR correspond to @svgr/webpack
USE.POSTCSS correspond to postcss-loader
USE.RESOLVE_URL_LOADER_FOR_SASS correspond to resolve-url-loader

CHAIN_ID.PLUGIN

PLUGIN.XXX can match a certain webpack plugin.

ID Description
PLUGIN.HTML correspond to HtmlPlugin, you need to splice the entry name when using: ${PLUGIN.HTML}-${entryName}
PLUGIN.APP_ICON correspond to AppIconPlugin
PLUGIN.INLINE_HTML correspond to InlineChunkHtmlPlugin
PLUGIN.BUNDLE_ANALYZER correspond to WebpackBundleAnalyzer
PLUGIN.VUE_LOADER_PLUGIN correspond to VueLoaderPlugin
PLUGIN.AUTO_SET_ROOT_SIZE correspond to automatically set root font size plugin in Rsbuild

CHAIN_ID.MINIMIZER

MINIMIZER.XXX can match a certain minimizer.

ID Description
MINIMIZER.JS correspond to TerserWebpackPlugin or SwcJsMinimizerRspackPlugin
MINIMIZER.CSS correspond to CssMinimizerWebpackPlugin

Examples

For usage examples, please refer to: WebpackChain usage examples.

tools.cssLoader

  • Type: Object | Function
  • Default: undefined

The config of css-loader can be modified through tools.cssLoader. The default config is as follows:

{
  modules: {
    auto: true,
    exportLocalsConvention: 'camelCase',
    localIdentName: config.output.cssModules.localIdentName,
    // isServer indicates node (SSR) build
    // isWebWorker indicates web worker build
    exportOnlyLocals: isServer || isWebWorker,
  },
  // CSS Source Map enabled by default in development environment
  sourceMap: isDev,
  // importLoaders is `1` when compiling css files, and is `2` when compiling sass/less files
  importLoaders: 1 || 2,
}
TIP

When using Rspack as the bundler, this configuration is only supported when set disableCssExtract is true.

To modify CSS Modules configuration, it is recommended to use the output.cssModules configuration.

Object Type

When this value is an Object, it is merged with the default config via deep merge. For example:

export default {
  tools: {
    cssLoader: {
      modules: {
        exportOnlyLocals: true,
      },
    },
  },
};

Function Type

When the value is a Function, the default config is passed in as the first parameter. You can modify the config object directly, or return an object as the final config. For example:

export default {
  tools: {
    cssLoader: (config) => {
      config.modules.exportOnlyLocals = true;
      return config;
    },
  },
};

tools.htmlPlugin

  • Type: false | Object | Function
  • Default:
const defaultHtmlPluginOptions = {
  inject, // corresponding to the html.inject config
  favicon, // corresponding to html.favicon config
  filename, // generated based on output.distPath and entryName
  template, // defaults to the built-in HTML template path
  templateParameters, // corresponding to the html.templateParameters config
  chunks: [entryName],
  minify: {
    // generated based on output.disableMinimize
    removeComments: false,
    useShortDoctype: true,
    keepClosingSlash: true,
    collapseWhitespace: true,
    removeRedundantAttributes: true,
    removeScriptTypeAttributes: true,
    removeStyleLinkTypeAttributes: true,
    removeEmptyAttributes: true,
    minifyJS,
    minifyCSS: true,
    minifyURLs: true,
  },
};

The configs of html-webpack-plugin can be modified through tools.htmlPlugin.

Object Type

When tools.htmlPlugin is Object type, the value will be merged with the default config via Object.assign.

export default {
  tools: {
    htmlPlugin: {
      scriptLoading: 'blocking',
    },
  },
};

Function Type

When tools.htmlPlugin is a Function:

  • The first parameter is the default config, which can be modified directly.
  • The second parameter is also an object, containing the entry name and the entry value.
  • The Function can return a new object as the final config.
export default {
  tools: {
    htmlPlugin(config, { entryName, entryValue }) {
      if (entryName === 'main') {
        config.scriptLoading = 'blocking';
      }
    },
  },
};

Boolean Type

The built-in html-webpack-plugin plugins can be disabled by set tools.htmlPlugin to false.

export default {
  tools: {
    htmlPlugin: false,
  },
};

Disable JS/CSS minify

By default, Rsbuild will compresses JavaScript/CSS code inside HTML during the production build to improve the page performance. This ability is often helpful when using custom templates or inserting custom scripts.

However, when output.enableInlineScripts or output.enableInlineStyles is turned on, inline JavaScript/CSS code will be repeatedly compressed, which will have a certain impact on build performance. You can modify the default minify behavior by modifying the tools.htmlPlugin.minify configuration.

export default {
  tools: {
    htmlPlugin: (config) => {
      if (typeof config.minify === 'object') {
        config.minify.minifyJS = false;
        config.minify.minifyCSS = false;
      }
    },
  },
};

tools.less

  • Type: Object | Function
  • Default:
const defaultOptions = {
  lessOptions: {
    javascriptEnabled: true,
  },
  // CSS Source Map enabled by default in development environment
  sourceMap: isDev,
};

You can modify the config of less-loader via tools.less.

Object Type

When tools.less is configured as Object type, it is merged with the default config through Object.assign in a shallow way. It should be noted that lessOptions is merged through deepMerge in a deep way. For example:

export default {
  tools: {
    less: {
      lessOptions: {
        javascriptEnabled: false,
      },
    },
  },
};

Function Type

When tools.less is a Function, the default config is passed as the first parameter, which can be directly modified or returned as the final result. The second parameter provides some utility functions that can be called directly. For example:

export default {
  tools: {
    less(config) {
      // Modify the config of lessOptions
      config.lessOptions = {
        javascriptEnabled: false,
      };
    },
  },
};

Modifying Less Version

In some scenarios, if you need to use a specific version of Less instead of the built-in Less v4 in Rsbuild, you can install the desired Less version in your project and set it up using the implementation option of the less-loader.

export default {
  tools: {
    less: {
      implementation: require('less'),
    },
  },
};

Util Function

addExcludes

  • Type: (excludes: RegExp | RegExp[]) => void

Used to specify which files less-loader does not compile, You can pass in one or more regular expressions to match the path of less files, for example:

export default {
  tools: {
    less(config, { addExcludes }) {
      addExcludes(/node_modules/);
    },
  },
};

tools.postcss

  • Type: Object | Function
  • Default:
const defaultOptions = {
  postcssOptions: {
    plugins: [
      require('postcss-flexbugs-fixes'),
      require('autoprefixer')({ flexbox: 'no-2009' }),
    ],
    // CSS Source Map enabled by default in development environment
    sourceMap: isDev,
  },
};

Rsbuild integrates PostCSS by default, you can configure postcss-loader through tools.postcss.

Function Type

When the value is a Function, the internal default config is passed as the first parameter, and the config object can be modified directly without returning, or an object can be returned as the final result; the second parameter is a set of tool functions for modifying the postcss-loader config.

For example, you need to add a PostCSS plugin on the basis of the original plugin, and push a new plugin to the postcssOptions.plugins array:

export default {
  tools: {
    postcss: (opts) => {
      opts.postcssOptions.plugins.push(require('postcss-px-to-viewport'));
    },
  },
};

When you need to pass parameters to the PostCSS plugin, you can pass them in by function parameters:

export default {
  tools: {
    postcss: (opts) => {
      const viewportPlugin = require('postcss-px-to-viewport')({
        viewportWidth: 375,
      });
      opts.postcssOptions.plugins.push(viewportPlugin);
    },
  },
};

tools.postcss can return a config object and completely replace the default config:

export default {
  tools: {
    postcss: () => {
      return {
        postcssOptions: {
          plugins: [require('postcss-px-to-viewport')],
        },
      };
    },
  },
};

Object Type

When this value is an Object, it is merged with the default config via Object.assign. Note that Object.assign is a shallow copy and will completely overwrite the built-in presets or plugins array, please use it with caution.

export default {
  tools: {
    postcss: {
      // Because `Object.assign` is used, the default postcssOptions will be overwritten.
      postcssOptions: {
        plugins: [require('postcss-px-to-viewport')],
      },
    },
  },
};

Util Functions

addPlugins

  • Type: (plugins: PostCSSPlugin | PostCSSPlugin[]) => void

For adding additional PostCSS plugins, You can pass in a single PostCSS plugin, or an array of PostCSS plugins.

export default {
  tools: {
    postcss: (config, { addPlugins }) => {
      // Add a PostCSS Plugin
      addPlugins(require('postcss-preset-env'));
      // Add multiple PostCSS Plugins
      addPlugins([require('postcss-preset-env'), require('postcss-import')]);
    },
  },
};
TIP

Rsbuild uses the PostCSS v8 version. When you use third-party PostCSS plugins, please pay attention to whether the PostCSS version is compatible. Some legacy plugins may not work in PostCSS v8.

tools.sass

  • Type: Object | Function
  • Default:
const defaultOptions = {
  // CSS Source Map enabled by default in development environment
  sourceMap: isDev,
};

You can modify the config of sass-loader via tools.sass.

Object Type

When tools.sass is Object type, it is merged with the default config through Object.assign. It should be noted that sassOptions is merged through deepMerge in a deep way.

For example:

export default {
  tools: {
    sass: {
      sourceMap: true,
    },
  },
};

Function Type

When tools.sass is a Function, the default config is passed as the first parameter, which can be directly modified or returned as the final result. The second parameter provides some utility functions that can be called directly. For Example:

export default {
  tools: {
    sass(config) {
      // Modify sourceMap config
      config.additionalData = async (content, loaderContext) => {
        // ...
      };
    },
  },
};

Modifying Sass Version

In some scenarios, if you need to use a specific version of Sass instead of the built-in Dart Sass v1 in Rsbuild, you can install the desired Sass version in your project and set it up using the implementation option of the sass-loader.

export default {
  tools: {
    sass: {
      implementation: require('sass'),
    },
  },
};

Utility Function

addExcludes

  • Type: (excludes: RegExp | RegExp[]) => void

Used to specify which files sass-loader does not compile, You can pass in one or more regular expressions to match the path of sass files, for example:

export default {
  tools: {
    sass(config, { addExcludes }) {
      addExcludes(/node_modules/);
    },
  },
};

tools.styleLoader

  • Type: Object | Function
  • Default: {}

The config of style-loader can be set through tools.styleLoader.

It is worth noting that Rsbuild does not enable style-loader by default. You can use output.disableCssExtract config to enable it.

Object Type

When this value is an Object, it is merged with the default config via Object.assign. For example:

export default {
  tools: {
    styleLoader: {
      loaderOptions: {
        insert: 'head',
      },
    },
  },
};

Function Type

When the value is a Function, the default config is passed in as the first parameter. You can modify the config object directly, or return an object as the final config. For example:

export default {
  tools: {
    styleLoader: (config) => {
      config.loaderOptions.insert = 'head';
      return config;
    },
  },
};

tools.rspack

  • Type: Object | Function | undefined
  • Default: undefined
  • Bundler: only support Rspack

tools.rspack is used to configure Rspack.

Object Type

tools.rspack can be configured as an object to be deep merged with the built-in Rspack configuration through webpack-merge.

For example, add resolve.alias configuration:

export default {
  tools: {
    rspack: {
      resolve: {
        alias: {
          '@util': 'src/util',
        },
      },
    },
  },
};

Function Type

tools.rspack can be configured as a function. The first parameter of this function is the built-in Rspack configuration object, you can modify this object, and then return it. For example:

export default {
  tools: {
    rspack: (config) => {
      config.resolve.alias['@util'] = 'src/util';
      return config;
    },
  },
};
TIP

The object returned by the tools.rspack function is used directly as the final Rspack configuration and is not merged with the built-in Rspack configuration.

The second parameter of this function is an object, which contains some utility functions and properties, as follows:

Utils

env

  • Type: 'development' | 'production' | 'test'

The env parameter can be used to determine whether the current environment is development, production or test. For example:

export default {
  tools: {
    rspack: (config, { env }) => {
      if (env === 'development') {
        config.devtool = 'cheap-module-eval-source-map';
      }
      return config;
    },
  },
};

isProd

  • Type: boolean

The isProd parameter can be used to determine whether the current environment is production. For example:

export default {
  tools: {
    rspack: (config, { isProd }) => {
      if (isProd) {
        config.devtool = 'source-map';
      }
      return config;
    },
  },
};

target

  • Type: 'web' | 'node' | 'web-worker'

The target parameter can be used to determine the current target. For example:

export default {
  tools: {
    rspack: (config, { target }) => {
      if (target === 'node') {
        // ...
      }
      return config;
    },
  },
};

isServer

  • Type: boolean

Determines whether the target environment is node, equivalent to target === 'node'.

export default {
  tools: {
    rspack: (config, { isServer }) => {
      if (isServer) {
        // ...
      }
      return config;
    },
  },
};

isWebWorker

  • Type: boolean

Determines whether the target environment is web-worker, equivalent to target === 'web-worker'.

export default {
  tools: {
    rspack: (config, { isWebWorker }) => {
      if (isWebWorker) {
        // ...
      }
      return config;
    },
  },
};

rspack

  • Type: typeof import('@rspack/core')

The Rspack instance. For example:

export default {
  tools: {
    rspack: (config, { rspack }) => {
      config.plugins.push(new rspack.BannerPlugin());
      return config;
    },
  },
};

addRules

  • Type: (rules: RuleSetRule | RuleSetRule[]) => void

Add additional Rspack rules.

For example:

export default {
  tools: {
    rspack: (config, { addRules }) => {
      // add a single rule
      addRules({
        test: /\.foo/,
        loader: require.resolve('foo-loader'),
      });

      // Add multiple rules as an array
      addRules([
        {
          test: /\.foo/,
          loader: require.resolve('foo-loader'),
        },
        {
          test: /\.bar/,
          loader: require.resolve('bar-loader'),
        },
      ]);
    },
  },
};

prependPlugins

  • Type: (plugins: RspackPluginInstance | RspackPluginInstance[]) => void

Add additional plugins to the head of the internal Rspack plugins array, and the plugin will be executed first.

export default {
  tools: {
    rspack: (config, { prependPlugins }) => {
      // add a single plugin
      prependPlugins(new PluginA());

      // Add multiple plugins
      prependPlugins([new PluginA(), new PluginB()]);
    },
  },
};

appendPlugins

  • Type: (plugins: RspackPluginInstance | RspackPluginInstance[]) => void

Add additional plugins at the end of the internal Rspack plugins array, the plugin will be executed last.

export default {
  tools: {
    rspack: (config, { appendPlugins }) => {
      // add a single plugin
      appendPlugins([new PluginA()]);

      // Add multiple plugins
      appendPlugins([new PluginA(), new PluginB()]);
    },
  },
};

removePlugin

  • Type: (name: string) => void

Remove the internal Rspack plugin, the parameter is the constructor.name of the plugin.

For example, remove the internal webpack-bundle-analyzer:

export default {
  tools: {
    rspack: (config, { removePlugin }) => {
      removePlugin('BundleAnalyzerPlugin');
    },
  },
};

mergeConfig

  • Type: (...configs: RspackConfig[]) => RspackConfig

Used to merge multiple Rspack configs, same as webpack-merge.

export default {
  tools: {
    rspack: (config, { mergeConfig }) => {
      return mergeConfig(config, {
        devtool: 'eval',
      });
    },
  },
};

getCompiledPath

  • Type: (name: string) => string

Get the path to the Rsbuild built-in dependencies, such as:

  • sass
  • sass-loader
  • less
  • less-loader
  • babel-loader
  • url-loader
  • file-loader
  • ...

This method is usually used when you need to reuse the same dependency with the rsbuild.

TIP

Rsbuild built-in dependencies are subject to change with version iterations, e.g. generate large version break changes. Please avoid using this API if it is not necessary.

export default {
  tools: {
    rspack: (config, { getCompiledPath }) => {
      const loaderPath = getCompiledPath('less-loader');
      // ...
    },
  },
};