Builtins

Stability: Experimental

Used to set the built-in functions provided by Rspack.

  • Type: Record<string, any>
  • Default: {}
Stability Warning

The built-in functionality provided by builtins may change in the future or be replaced with a better solution, so please note the changes to the builtins when you upgrade and we will highlight them in the Release Notes.

builtins.banner

WARNING

Please migrate to BannerPlugin.

  • Type:
type BannerCondition = string | RegExp | Array<string | RegExp>;

type BannerConfig =
  | string
  | {
      banner: string;
      entryOnly?: boolean;
      footer?: boolean;
      raw?: boolean;
      test?: BannerCondition;
      include?: BannerCondition;
      exclude?: BannerCondition;
    };

export type BannerConfigs = BannerConfig | BannerConfig[];
  • Default: undefined
Name Type Default Description
banner string undefined Specifies the banner, it will be wrapped in a comment.
entryOnly boolean|undefined undefined If true, the banner will only be added to the entry chunks.
footer boolean|undefined undefined If true, banner will be placed at the end of the output.
raw boolean|undefined undefined If true, banner will not be wrapped in a comment.
test BannerConditions|undefined undefined Include all modules that pass test assertion.
include BannerConditions|undefined undefined Include all modules matching any of these conditions.
exclude BannerConditions|undefined undefined Exclude all modules matching any of these conditions.

Adds a banner to the top or bottom of each generated chunk.

rspack.config.js
module.exports = {
  builtins: {
    banner: [
      {
        banner: 'hello world',
        footer: true,
      },
    ],
  },
};

builtins.emotion

WARNING

Please migrate to builtin:swc-loader options.

Using optimization for emotion in compile-time.

  • Type:
type EmotionOptions =
  | boolean
  | {
      sourceMap?: boolean;
      autoLabel?: 'never' | 'dev-only' | 'always';
      labelFormat?: string;
      importMap?: {
        [packageName: string]: {
          [exportName: string]: {
            canonicalImport?: [string, string];
          };
        };
      };
    };
  • Default: false

If you are using emotion in your project, and want functionality which is similar to @emotion/babel-plugin, you can enable builtins.emotion option, Rspack will use swc_emotion plugin to transpile your emotion code.

You can enable default options by specify builtins.emotion: true.

rspack.config.js
module.exports = {
  context: __dirname,
  entry: {
    main: './src/index.js',
  },
  builtins: {
    emotion: true,
  },
};

Each field name is the same with @emotion/babel-plugin, more detailed explanation (content below is from the official document of @emotion/babel-plugin):

autoLabel

  • Type: 'never' | 'dev-only' | 'always'
  • Default: 'dev-only'

This option is used for:

  • Automatically adds the label property to styles so that class names generated by css or styled include the name of the variable the result is assigned to.
  • Please note that non word characters in the variable will be removed (Eg. iconStyles$1 will become iconStyles1) because $ is not validCSS ClassName Selector.

Each possible value for this option produces different output code:

  • 'dev-only' - we optimize the production code, so there are no labels added there, but at the same time we keep labels for development environments,
  • 'always' - we always add labels when possible,
  • 'never' - we disable this entirely and no labels are added.

labelFormat

  • Type: string
  • Default: "[local]"

This option only works when 'autoLabel' is set to 'dev-only' or 'always'. It allows you to define the format of the resulting label. The format is defined via string where variable parts are enclosed in square brackets []. For example labelFormat: "my-classname--[local]", where '[local]' will be replaced with the name of the variable the result is assigned to.

Allowed values:

  • '[local]' - the name of the variable the result of the css or styled expression is assigned to.
  • '[filename]' - name of the file (without extension) where css or styled expression is located.
  • '[dirname]' - name of the directory containing the file where css or styled expression is located.

This format only affects the label property of the expression, meaning that the css prefix and hash will be prepended automatically.

sourceMap

  • Type: boolean

Whether to inject source maps. By default, this will be disabled in production mode, and enabled in development mode.

importMap

  • Type:
export type ImportMap =
  | undefined
  | {
      [packageName: string]: {
        [exportName: string]: {
          canonicalImport?: [string, string];
        };
      };
    };
  • Default: undefined

This option allows you to tell Rspack what imports it should look at to determine what it should transform so if you re-export Emotion's exports, you can still use the Babel transforms

builtins.presetEnv

WARNING

Please migrate to builtin:swc-loader options

This option allows your code to run on older versions of browsers by querying all the browsers that need to be supported through browserslist. If the source code uses APIs that are not supported by these browsers, the same APIs can be provided to these browsers by globally injecting core-js. If the source code uses syntax that is not supported by these browsers, the syntax will also be converted into syntax supported by the browsers.

  • Type:
type PresetEnv =
  | undefined
  | {
      mode?: 'entry'; // `usage` mode will be supported in the near future
      targets?: string[];
      coreJs?: string;
    };
  • Default: undefined
Name Type Default Description
targets string[]|undefined undefined Use browserslist query to specify the ECMAScript version of the user code. Rspack will try to use browserslist config on context directory when value is undefined.
mode 'entry'|undefined undefined This option determine the behavior of polyfill injection, 'entry' means that inject all polyfill that matches your needs, according to browserslist query, set this to undefined will not inject polyfill at all.
coreJs string undefined This option specify the version of core-js
notice about core-js usage

When you use mode = 'entry' or mode = 'usage' to inject core-js, you need to manually install core-js. If you encounter the problem of "failed to resolve 'core-js'" during compilation, you should also configure resolve.alias to point the core-js path to the local core-js as follows:

module.exports = {
  resolve: {
    alias: {
      'core-js': require('path').dirname(require.resolve('core-js')),
    },
  },
};

builtins.html

WARNING

Please migrate to HtmlRspackPlugin.

This configuration simplifies creation of HTML files to serve your Rspack bundles.

  • Type:
type BuiltinsHtml = Array<{
  title?: string;
  filename?: string;
  template?: string;
  templateContent?: string;
  templateParameters?: Record<string, string>;
  inject?: 'head' | 'body';
  publicPath?: string;
  scriptLoading?: 'blocking' | 'defer' | 'module';
  chunks?: string[];
  excludedChunks?: string[];
  sri?: 'sha256' | 'sha384' | 'sha512';
  minify?: boolean;
  favicon?: string;
  meta?: Record<string, string | Record<string, string>>;
}>;
  • Default: []
Name Type Default Description
title string|undefined undefined The title to use for the generated HTML document.
filename string 'index.html' The file to write the HTML to. Defaults to index.html. You can specify a subdirectory here too (eg: pages/index.html).
template string|undefined undefined The template file path.
templateContent string|undefined undefined The template file content, priority is greater than template.
templateParameters Record<string, string> {} Allows to overwrite the parameters used in the template.
inject 'head'|'body'|undefined undefined The script and link tag inject position in template.
publicPath string '' The publicPath used for script and link tags.
scriptLoading 'blocking'|'defer'|'module' 'defer' Modern browsers support non blocking javascript loading ('defer') to improve the page startup performance. Setting to 'module' adds attribute type="module". This also implies "defer", since modules are automatically deferred.
chunks string[]|undefined undefined Allows you to add only some chunks.
excludedChunks string[]|undefined undefined Allows you to skip some chunks.
sri 'sha256'|'sha384'|'sha512'|undefined undefined The sri hash algorithm, disabled by default.
minify boolean false Controls whether to minify the output.
favicon string|undefined undefined Adds the given favicon path to the output HTML.
meta Record<string, string|Record<string, string>> {} Allows to inject meta-tags.
TIP

If the configuration options provided by rspack.HtmlRspackPlugin cannot meet your needs, you can also directly use the community's html-webpack-plugin plugin.

builtins.minifyOptions

WARNING

Please migrate to SwcJsMinimizerRspackPlugin.

Set built-in minimizer options.

  • Type:
type BuiltinsMinifyOptions = {
  passes?: number;
  dropConsole?: boolean;
  keepClassNames?: boolean;
  keepFnNames?: boolean;
  pureFuncs?: Array<string>;
  extractComments: boolean | RegExp;
  asciiOnly?: boolean;
  comments?: false | 'all' | 'some';
};
Name Type Default Description
passes number 1 The maximum number of times to run compress.
dropConsole boolean false Pass true to discard calls to console.* functions.
keepClassNames boolean false Enabling this option will make swc preserve original class names.
keepFnNames boolean false Enabling this option will make swc preserve original function names.
pureFuncs Array<string> [] You can pass an array of names and Rspack will assume that those functions do not produce side effects
extractComments boolean|RegExp false Extract comments that match the configuration to a separate file (fileName: {assetName}.LICENSE.txt). If the option is set to true, use the regular expression /@preserve|@lic|@cc_on|^\**!/.
asciiOnly boolean false Escape Unicode characters in strings and regexps (affects directives with non-ascii characters becoming invalid)
comments false|"all |"some" false By default will omit comments in the output, a regular expression string (e.g. /^!/) or a function, pass "some" to keeps JSDoc-style comments that contain "@license", "@copyright", "@preserve" or start with !, pass "all" to preserve all comments.

builtins.define

WARNING

Please migrate to DefinePlugin.

Replaces variables in your code with other values or expressions at compile time.

  • Type: Record<string, string | boolean | undefined>
  • Default: {}

When using the following configuration:

rspack.config.js
module.exports = {
  builtins: {
    define: {
      'process.env.NODE_ENV': "'development'",
      TRUE: true,
      TRUE_STRING: 'true',
      UNDEFINED: undefined,
      UNDEFINED_STRING: 'undefined',
    },
  },
};

Input:

if (process.env.NODE_ENV === 'development') {
  console.log('run in development mode');
}

console.log(TRUE === TRUE_STRING);
console.log(UNDEFINED === UNDEFINED_STRING);

Output:

if ('development' === 'development') {
  console.log('run in development mode');
}

fetch('/api/test');

console.log(true === true);
console.log(undefined === undefined);

builtins.react

WARNING

Please migrate to builtin:swc-loader options

This configuration can control the code transformation about react.

  • Type:
type ReactOptions = {
  runtime?: 'automatic' | 'classic';
  importSource?: string;
  pragma?: string;
  pragmaFrag?: string;
  throwIfNamespace?: boolean;
  development?: boolean;
  useBuiltins?: boolean;
  useSpread?: boolean;
  refresh?: boolean;
};
  • Default: {}
Name Type Default Description
runtime 'automatic'|'classic' 'automatic' automatic to use a JSX runtime module, classic to use React.createElement instead.
importSource string 'react' When using runtime=automatic, determines the runtime library to import.
pragma string 'React.createElement' When using runtime=classic, replaces the function used when compiling JSX expressions.
pragmaFrag string 'React.Fragment' Replace the component used when compiling JSX fragments.
throwIfNamespace boolean true Toggles whether or not to throw an error if an XML namespaced tag name is used. For example: .
development boolean false Toggles debug props __self and __source on elements generated from JSX, which are used by development tooling such as React Developer Tools.
useBuiltins boolean false Use Object.assign() instead of _extends.
useSpread boolean false Use Object.assign() instead of spreading props.
refresh boolean false Enable react-refresh related transform.

builtins.decorator

WARNING

Please migrate to builtin:swc-loader options

This configuration can be used to control decorator transform behavior, false means to turn off transform.

  • Type:
type BuiltinsDecorator =
  | boolean
  | {
      legacy?: boolean;
      emitMetadata?: boolean;
    };
  • Default: true
Name Type Default Description
legacy boolean true Use the legacy (stage 1) class decorators syntax and behavior.
emitMetadata boolean true Whether to keep metadata information.

builtins.css

Removed in v0.6.0
Stability: Removed

This configuration can be used to control how Rspack handles css.

  • Type:
type BuiltinsCss = {
  modules?: BuiltinsCssModules;
};

builtins.css.modules

Removed in v0.6.0
Stability: Removed

css modules options.

  • Type:
type BuiltinsCssModules = {
  localsConvention?:
    | 'asIs'
    | 'camelCase'
    | 'camelCaseOnly'
    | 'dashes'
    | 'dashesOnly';
  localIdentName?: string;
  exportsOnly?: boolean;
};
Name Type Default Description
localsConvention 'asIs' | 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' 'asIs' asIs Class names will be exported as is.
camelCase Class names will be camelized, the original class name will not to be removed from the locals.
camelCaseOnly Class names will be camelized, the original class name will be removed from the locals.
dashes Only dashes in class names will be camelized.
dashesOnly Dashes in class names will be camelized, the original class name will be removed from the locals.
localIdentName string production: '[hash]'
development: '[path][name][ext]__[local]"
The generated local ident name. Supported template strings:
hash hash string.
hash:<length> hash with hash settings.
path the path of the resource relative to the context option.
name the basename of the resource.
ext extension with leading ..
local original class.
exportsOnly boolean false Only export js object, without css file. Useful in SSR.

builtins.progress

WARNING

Please migrate to ProgressPlugin.

This configuration can be used to control progress, false means to turn off progress.

Name Type Default Description
prefix string 'Rspack' The text displayed before the progress.

builtins.devFriendlySplitChunks

Whether to enable the development-friendly split chunks algorithm.

  • Type: boolean

  • Default: false

builtins.copy

WARNING

Please migrate to CopyRspackPlugin.

CC 4.0 License

The content of this section is derived from the content of the following links and is subject to the CC BY 4.0 license.

The following contents can be assumed to be the result of modifications and deletions based on the original contents if not specifically stated.

Copies individual files or entire directories, which already exist, to the build directory.

  • Type:
export type CopyConfig = {
  patterns: (
    | string // If input is string, it's the same as { from: `your input string` }
    | {
        from: string;
        to?: string; // Determine based on `from`
        context?: string; // Default to `context` in Rspack config
        toType?: 'dir' | 'file' | 'template'; // Determine based on `from`
        noErrorOnMissing?: boolean; // Default to false
        force?: boolean; // Default to false
        priority?: number; // Default to 0
        globOptions?: {
          caseSensitiveMatch?: boolean; // Default to true
          dot?: boolean; // Default to true
          ignore?: string[]; // ignore specific path
        };
      }
  )[];
};
  • Default: undefined
Name Type Default Description
from string undefined The source path of the copy operation, which can be an absolute path, a relative path, or a glob search string. It can refer to a file or a directory. If a relative path is passed, it is relative to the context configuration.
to string undefined The destination of the copy operation, which can be an absolute path, a relative path, or a template string, such as '[name].[hash][ext]'. If not specified, it is equal to output path.
context string undefined This configuration determines how the "from" path is matched and the resulting structure after copying.
toType 'dir'|'file'|'template' undefined Specify the type of to, which can be a directory, a file, or a template name in rspack. If not specified, it will be automatically inferred.
noErrorOnMissing boolean false Ignore error if there are missing files or directories.
force boolean false Whether to overwrite the asset if it already exist
priority number 0 When force is set to true, if a matching file is found, the one with higher priority will overwrite the one with lower priority.
globOptions object undefined The configuration for glob queries: caseSensitiveMatch determines whether the matching is case sensitive, and dot determines whether files starting with . are matched. ignore is an array of strings in glob format that can be used to ignore specific paths.

For example:

rspack.config.js
module.exports = {
  entry: './src/index.js',
  builtins: {
    copy: {
      patterns: [
        {
          from: 'file.txt',
        },
      ],
    },
  },
};

The result of running with the above configuration would be: "dist/file.txt".

rspack.config.js
module.exports = {
  entry: './src/index.js',
  builtins: {
    copy: {
      patterns: [
        {
          from: 'directory',
        },
      ],
    },
  },
};

The result of running with the above configuration would be: files and directories inside directory will be placed at output path.

rspack.config.js
module.exports = {
  entry: './src/index.js',
  builtins: {
    copy: {
      patterns: [
        {
          from: 'directory/**/*',
          to: 'newdirectory',
        },
      ],
    },
  },
};

The result of running with the above configuration would be that the directory folder is moved to the newdirectory folder within the output folder, for example dist/newdirectory/directory/foo.

builtins.relay

WARNING

Please migrate to builtin:swc-loader options

Converted graphql call expression to corresponding require call expression.

  • Type:
export type RelayOptions =
  | undefined
  | boolean
  | {
      artifactDirectory?: string;
      language: 'javascript' | 'typescript' | 'flow'; // Default to 'javascript'
    };
  • Default: undefined

When this configuration is set to true, Rspack will attempt to locate relay.config.json, relay.config.js, and package.json files under the context directory in order, as detailed in the relay-compiler documentation. If none of these files are found, Rspack will use the default configuration. If specific configuration is passed, Rspack will not attempt to locate any relay config file, but use the received configuration directly.

builtins.pluginImport

WARNING

Please migrate to builtin:swc-loader options

Ported from babel-plugin-import, configurations are basically the same.

Function can't be used in configurations, such as customName, customStyleName, they will cause some performance overhead as these functions must be called from Rust , inspired by modularize_imports, some simple function can be replaced by template string instead. Therefore, the function type configuration such as customName, customStyleName can be passed in strings as templates to replace functions and improve performance.

For example:

import { MyButton as Btn } from 'foo';

Apply following configurations:

rspack.config.js
module.exports = {
  builtins: {
    pluginImport: [
      {
        libraryName: 'foo',
        customName: 'foo/es/{{ member }}',
      },
    ],
  },
};

{{ member }} will be replaced by the imported specifier:

import Btn from 'foo/es/MyButton';

Template customName: 'foo/es/{{ member }}' is the same as customName: (member) => `foo/es/${member}` , but template string has no performance overhead of Node-API.

The template used here is handlebars. There are some useful builtin helpers, Take the above import statement as an example:

rspack.config.js
module.exports = {
  builtins: {
    pluginImport: [
      {
        libraryName: 'foo',
        customName: 'foo/es/{{ kebabCase member }}',
      },
    ],
  },
};

Transformed to:

import Btn from 'foo/es/my-button';

In addition to kebabCase, there are camelCase, snakeCase, upperCase and lowerCase can be used as well.

You can check the document of babel-plugin-import for other configurations.

Taking the classic 4.x version of ant-design as an example, we only need to configure it as follows:

rspack.config.js
module.exports = {
  builtins: {
    pluginImport: [
      {
        libraryName: 'antd',
        style: '{{member}}/style/index.css',
      },
    ],
  },
};

The above configuration will transform import { Button } from 'antd'; to:

import Button from 'antd/es/button';
import 'antd/es/button/style/index.css';

Then you can see the style file is automatically imported and applied on the page.

Of course, if you have already configured support for less, you can simply use the following configuration:

rspack.config.js
module.exports = {
  builtins: {
    pluginImport: [
      {
        libraryName: 'antd',
        style: true,
      },
    ],
  },
};

The above configuration will transform import { Button } from 'antd'; to:

import Button from 'antd/es/button';
import 'antd/es/button/style';

builtins.provide

WARNING

Please migrate to ProvidePlugin.

Automatically load modules instead of having to import or require them everywhere.

module.exports = {
  builtins: {
    provide: {
      process: [require.resolve('process/browser')],
    },
  },
};

Which will convert the following code:

console.log(process.version);

To:

import process from 'process/browser';
console.log(process.version);