# Table of Contents - [Rsbuild - Rspack based build tool](#rsbuild-rspack-based-build-tool) - [Rsbuild core - Rsbuild](#rsbuild-core-rsbuild) - [Rsbuild types - Rsbuild](#rsbuild-types-rsbuild) - [JavaScript API - Rsbuild](#javascript-api-rsbuild) - [Environment API - Rsbuild](#environment-api-rsbuild) - [Server API - Rsbuild](#server-api-rsbuild) - [Rsbuild instance - Rsbuild](#rsbuild-instance-rsbuild) - [Rsbuild blogs - Rsbuild](#rsbuild-blogs-rsbuild) - [Announcing Rsbuild 0.2 - Rsbuild](#announcing-rsbuild-0-2-rsbuild) - [Announcing Rsbuild 0.3 - Rsbuild](#announcing-rsbuild-0-3-rsbuild) - [Announcing Rsbuild 0.4 - Rsbuild](#announcing-rsbuild-0-4-rsbuild) - [Announcing Rsbuild 0.5 - Rsbuild](#announcing-rsbuild-0-5-rsbuild) - [Announcing Rsbuild 0.6 - Rsbuild](#announcing-rsbuild-0-6-rsbuild) - [Announcing Rsbuild 1.0 - Rsbuild](#announcing-rsbuild-1-0-rsbuild) - [Announcing Rsbuild 0.7 - Rsbuild](#announcing-rsbuild-0-7-rsbuild) - [Announcing Rsbuild 2.1 - Rsbuild](#announcing-rsbuild-2-1-rsbuild) - [Announcing Rsbuild 2.0 - Rsbuild](#announcing-rsbuild-2-0-rsbuild) - [customLogger - Rsbuild](#customlogger-rsbuild) - [Announcing Rsbuild 0.1 - Rsbuild](#announcing-rsbuild-0-1-rsbuild) - [Rsbuild 0.1 发布 - Rsbuild](#rsbuild-0-1-rsbuild) - [Rsbuild 0.2 发布 - Rsbuild](#rsbuild-0-2-rsbuild) - [Rsbuild 0.3 发布 - Rsbuild](#rsbuild-0-3-rsbuild) - [Rsbuild 0.5 发布 - Rsbuild](#rsbuild-0-5-rsbuild) - [Rsbuild 0.6 发布 - Rsbuild](#rsbuild-0-6-rsbuild) - [Rsbuild types - Rsbuild](#rsbuild-types-rsbuild) - [JavaScript API - Rsbuild](#javascript-api-rsbuild) - [Rsbuild 0.4 发布 - Rsbuild](#rsbuild-0-4-rsbuild) - [Rsbuild 2.1 发布 - Rsbuild](#rsbuild-2-1-rsbuild) - [Rsbuild 0.7 发布 - Rsbuild](#rsbuild-0-7-rsbuild) - [Rsbuild 1.0 发布 - Rsbuild](#rsbuild-1-0-rsbuild) - [Rsbuild 博客 - Rsbuild](#rsbuild-rsbuild) - [Server API - Rsbuild](#server-api-rsbuild) - [Rsbuild - 基于 Rspack 的构建工具](#rsbuild-rspack-) - [Plugin list - Rsbuild](#plugin-list-rsbuild) - [Preact plugin - Rsbuild](#preact-plugin-rsbuild) - [Svelte plugin - Rsbuild](#svelte-plugin-rsbuild) - [Less plugin - Rsbuild](#less-plugin-rsbuild) - [Environment API - Rsbuild](#environment-api-rsbuild) - [Vue plugin - Rsbuild](#vue-plugin-rsbuild) - [Sass plugin - Rsbuild](#sass-plugin-rsbuild) - [Solid plugin - Rsbuild](#solid-plugin-rsbuild) - [Rsbuild core - Rsbuild](#rsbuild-core-rsbuild) - [Tailwind CSS plugin - Rsbuild](#tailwind-css-plugin-rsbuild) - [Rsbuild 2.0 发布 - Rsbuild](#rsbuild-2-0-rsbuild) - [React plugin - Rsbuild](#react-plugin-rsbuild) - [SVGR plugin - Rsbuild](#svgr-plugin-rsbuild) - [Plugin development - Rsbuild](#plugin-development-rsbuild) - [总览 - Rsbuild](#-rsbuild) - [Preact 插件 - Rsbuild](#preact-rsbuild) - [Vue 插件 - Rsbuild](#vue-rsbuild) - [Svelte 插件 - Rsbuild](#svelte-rsbuild) - [Less 插件 - Rsbuild](#less-rsbuild) - [Sass 插件 - Rsbuild](#sass-rsbuild) - [Rsbuild instance - Rsbuild](#rsbuild-instance-rsbuild) - [Babel plugin - Rsbuild](#babel-plugin-rsbuild) - [Tailwind CSS 插件 - Rsbuild](#tailwind-css-rsbuild) - [Solid 插件 - Rsbuild](#solid-rsbuild) - [Plugin API - Rsbuild](#plugin-api-rsbuild) - [React 插件 - Rsbuild](#react-rsbuild) - [SVGR 插件 - Rsbuild](#svgr-rsbuild) - [插件开发 - Rsbuild](#-rsbuild) - [Plugin hooks - Rsbuild](#plugin-hooks-rsbuild) - [Babel 插件 - Rsbuild](#babel-rsbuild) - [插件 API - Rsbuild](#-api-rsbuild) - [插件 hooks - Rsbuild](#-hooks-rsbuild) - [Debug mode - Rsbuild](#debug-mode-rsbuild) - [JSON - Rsbuild](#json-rsbuild) - [Build profiling - Rsbuild](#build-profiling-rsbuild) - [General FAQ - Rsbuild](#general-faq-rsbuild) - [Testing - Rsbuild](#testing-rsbuild) - [Glossary - Rsbuild](#glossary-rsbuild) - [Wasm - Rsbuild](#wasm-rsbuild) - [Use Rsdoctor - Rsbuild](#use-rsdoctor-rsbuild) - [Module Federation - Rsbuild](#module-federation-rsbuild) - [Upgrading Rsbuild - Rsbuild](#upgrading-rsbuild-rsbuild) - [Logging - Rsbuild](#logging-rsbuild) - [HMR FAQ - Rsbuild](#hmr-faq-rsbuild) - [Hot module replacement - Rsbuild](#hot-module-replacement-rsbuild) - [Deployment - Rsbuild](#deployment-rsbuild) - [Svelte - Rsbuild](#svelte-rsbuild) - [Code splitting - Rsbuild](#code-splitting-rsbuild) - [Path aliases - Rsbuild](#path-aliases-rsbuild) - [Preact - Rsbuild](#preact-rsbuild) - [Solid - Rsbuild](#solid-rsbuild) - [TypeScript - Rsbuild](#typescript-rsbuild) - [Configure Rsbuild - Rsbuild](#configure-rsbuild-rsbuild) - [Introduction - Rsbuild](#introduction-rsbuild) - [dev.assetPrefix - Rsbuild](#dev-assetprefix-rsbuild) - [Vue - Rsbuild](#vue-rsbuild) - [Bundle size optimization - Rsbuild](#bundle-size-optimization-rsbuild) - [Features FAQ - Rsbuild](#features-faq-rsbuild) - [CSS-in-JS - Rsbuild](#css-in-js-rsbuild) - [UnoCSS - Rsbuild](#unocss-rsbuild) - [Configure SWC - Rsbuild](#configure-swc-rsbuild) - [Browser compatibility - Rsbuild](#browser-compatibility-rsbuild) - [CSS Modules - Rsbuild](#css-modules-rsbuild) - [Browserslist - Rsbuild](#browserslist-rsbuild) - [Inline static assets - Rsbuild](#inline-static-assets-rsbuild) - [React - Rsbuild](#react-rsbuild) - [Tailwind CSS v3 - Rsbuild](#tailwind-css-v3-rsbuild) - [Web Workers - Rsbuild](#web-workers-rsbuild) - [Tailwind CSS v4 - Rsbuild](#tailwind-css-v4-rsbuild) - [Configure Rspack - Rsbuild](#configure-rspack-rsbuild) - [Quick start - Rsbuild](#quick-start-rsbuild) - [Vite plugin - Rsbuild](#vite-plugin-rsbuild) - [通用类问题 - Rsbuild](#-rsbuild) - [CLI - Rsbuild](#cli-rsbuild) - [Server-side rendering (SSR) - Rsbuild](#server-side-rendering-ssr-rsbuild) - [Multi-environment builds - Rsbuild](#multi-environment-builds-rsbuild) - [构建性能分析 - Rsbuild](#-rsbuild) - [开启调试模式 - Rsbuild](#-rsbuild) - [TanStack Start - Rsbuild](#tanstack-start-rsbuild) - [JSON - Rsbuild](#json-rsbuild) - [名词解释 - Rsbuild](#-rsbuild) - [升级 Rsbuild - Rsbuild](#-rsbuild-rsbuild) - [Output files - Rsbuild](#output-files-rsbuild) - [Improve build performance - Rsbuild](#improve-build-performance-rsbuild) - [Wasm - Rsbuild](#wasm-rsbuild) - [热更新问题 - Rsbuild](#-rsbuild) - [使用 Rsdoctor - Rsbuild](#-rsdoctor-rsbuild) - [测试 - Rsbuild](#-rsbuild) - [Exceptions FAQ - Rsbuild](#exceptions-faq-rsbuild) - [代码分割 - Rsbuild](#-rsbuild) - [Svelte - Rsbuild](#svelte-rsbuild) - [CSS - Rsbuild](#css-rsbuild) - [模块联邦 - Rsbuild](#-rsbuild) - [日志 - Rsbuild](#-rsbuild) - [Preact - Rsbuild](#preact-rsbuild) - [模块热更新 - Rsbuild](#-rsbuild) - [TypeScript - Rsbuild](#typescript-rsbuild) - [Solid - Rsbuild](#solid-rsbuild) - [Vue - Rsbuild](#vue-rsbuild) - [介绍 - Rsbuild](#-rsbuild) - [部署 - Rsbuild](#-rsbuild) - [功能类问题 - Rsbuild](#-rsbuild) - [路径别名 - Rsbuild](#-rsbuild) - [异常类问题 - Rsbuild](#-rsbuild) - [产物体积优化 - Rsbuild](#-rsbuild) - [配置 Rsbuild - Rsbuild](#-rsbuild-rsbuild) - [UnoCSS - Rsbuild](#unocss-rsbuild) - [CSS-in-JS - Rsbuild](#css-in-js-rsbuild) - [CSS Modules - Rsbuild](#css-modules-rsbuild) - [Upgrading from 0.x to v1 - Rsbuild](#upgrading-from-0-x-to-v1-rsbuild) - [配置 SWC - Rsbuild](#-swc-rsbuild) - [AI - Rsbuild](#ai-rsbuild) - [React - Rsbuild](#react-rsbuild) - [Tailwind CSS v3 - Rsbuild](#tailwind-css-v3-rsbuild) - [浏览器兼容性 - Rsbuild](#-rsbuild) - [静态资源内联 - Rsbuild](#-rsbuild) - [Tailwind CSS v4 - Rsbuild](#tailwind-css-v4-rsbuild) - [快速上手 - Rsbuild](#-rsbuild) - [配置 Rspack - Rsbuild](#-rspack-rsbuild) --- # Rsbuild - Rspack based build tool For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /index.md. ![background](https://assets.rspack.rs/rspack/assets/landingpage-background-compressed.png) ![logo](https://assets.rspack.rs/rsbuild/rsbuild-logo.svg) Rsbuild ======= The Rspack Powered Build Tool Build your web application instantly Quick start[GitHubGitHub](https://github.com/web-infra-dev/rsbuild) 🚀 Rspack-based ------------ Using Rspack to bring you the ultimate development experience. 🦄 Batteries Included ------------------ Out-of-the-box integration with the most practical building features in the ecosystem. 🎯 Framework Agnostic ------------------ Supports React, Vue, Svelte, and more frameworks. 🛠️ Deep Optimization ----------------- Automatically optimize static assets to maximizing production performance. 🎨 Highly Pluggable ---------------- Comes with a lightweight plugin system and a set of high quality plugins. 🍭 Easy To Configure ----------------- Start with zero configuration and everything is configurable. Lightning Fast ============== Combining Rust and TypeScript with a parallelized architecture to bring you the ultimate developer experience Rsbuild 1.36s dev 3.35s build 160ms hmr Vite 6.50s dev 1.98s build 130ms hmr webpack 21.40s dev 28.10s build 2.78s hmr Rstack ====== The fast, unified JavaScript toolchain for developers and agents [![Rspack](https://assets.rspack.rs/rspack/rspack-logo.svg)\ \ Rspack\ \ A fast Rust-based bundler for the web, with a modernized webpack API\ \ rspack.rs](https://rspack.rs/) [![Rsbuild](https://assets.rspack.rs/rsbuild/rsbuild-logo.svg)\ \ Rsbuild\ \ A fast, extensible build tool for modern web development, powered by Rspack\ \ rsbuild.rs](https://rsbuild.rs/) [![Rslib](https://assets.rspack.rs/rslib/rslib-logo.svg)\ \ Rslib\ \ An Rsbuild-based library development tool for creating libraries and UI components\ \ rslib.rs](https://rslib.rs/) [![Rspress](https://assets.rspack.rs/rspress/rspress-logo-480x480.png)\ \ Rspress\ \ An Rsbuild-based static site generator for creating documentation sites\ \ rspress.rs](https://rspress.rs/) [![Rsdoctor](https://assets.rspack.rs/rsdoctor/rsdoctor-logo-480x480.png)\ \ Rsdoctor\ \ An AI-friendly build analyzer that makes the build process transparent\ \ rsdoctor.rs](https://rsdoctor.rs/) [![Rstest](https://assets.rspack.rs/rstest/rstest-logo.svg)\ \ Rstest\ \ A JavaScript testing framework powered by Rspack, with a Jest-compatible API\ \ rstest.rs](https://rstest.rs/) [![Rslint](https://assets.rspack.rs/rslint/rslint-logo.svg)\ \ Rslint\ \ A high-performance, ESLint-compatible linter for JavaScript and TypeScript\ \ rslint.rs](https://rslint.rs/) Guide ----- * [Introduction](https://rsbuild.rs/guide/start/) * [Quick start](https://rsbuild.rs/guide/start/quick-start) * [Features](https://rsbuild.rs/guide/start/features) * [Migration](https://rsbuild.rs/guide/migration/webpack) API --- * [CLI](https://rsbuild.rs/guide/basic/cli) * [Configuration](https://rsbuild.rs/guide/configuration/rsbuild) * [Plugin API](https://rsbuild.rs/plugins/dev/) * [JavaScript API](https://rsbuild.rs/api/start/) Ecosystem --------- * [Rspack](https://rspack.rs/) * [Rspress](https://rspress.rs/) * [Rsdoctor](https://rsdoctor.rs/) * [Rslib](https://rslib.rs/) * [Rstest](https://rstest.rs/) Community --------- * [GitHub](https://github.com/web-infra-dev/rsbuild) * [Discord](https://discord.gg/sYK4QjyZ4V) * [Twitter (X)](https://twitter.com/rspack_dev) * [Bluesky](https://bsky.app/profile/rspack.rs) * [Awesome Rstack](https://github.com/rstackjs/awesome-rstack) --- # Rsbuild core - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/javascript-api/core.md. MenuON THIS PAGE [#](https://rsbuild.rs/api/javascript-api/core#rsbuild-core) Rsbuild core ========================================================================= Copy Markdown Rsbuild offers these core methods. [#](https://rsbuild.rs/api/javascript-api/core#creatersbuild) createRsbuild --------------------------------------------------------------------------- Create an [Rsbuild instance](https://rsbuild.rs/api/javascript-api/instance) . * **Type:** function createRsbuild( options?: CreateRsbuildOptions, ): Promise; * **Example:** import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild({ config: { // Rsbuild configuration }, }); ### [#](https://rsbuild.rs/api/javascript-api/core#options) Options The first parameter of `createRsbuild` is an `options` object with the following properties: type CreateRsbuildOptions = { cwd?: string; callerName?: string; environment?: string[]; loadEnv?: boolean | LoadEnvOptions; config?: | RsbuildConfig | LoadConfigResult | (() => Promise); restart?: RestartFn; }; * `cwd`: The root path of the current build, defaults to `process.cwd()`. * `callerName`: The name of the framework or tool currently invoking Rsbuild, defaults to `'rsbuild'`, see [Specify caller name](https://rsbuild.rs/api/javascript-api/core#specify-caller-name) . * `environment`: Build only specified [environments](https://rsbuild.rs/guide/advanced/environments) . If not specified or an empty array is passed, all environments will be built. * `loadEnv`:Whether to call the [loadEnv](https://rsbuild.rs/api/javascript-api/core#loadenv) method to load environment variables and define them as global variables via [source.define](https://rsbuild.rs/config/source/define) . * `config`: Rsbuild configuration object or the result returned by [`loadConfig`](https://rsbuild.rs/api/javascript-api/core#loadconfig) . Refer to [Config overview](https://rsbuild.rs/config/) for all available configuration options. * `restart`: A function that handles restart requests for the current dev server or watch build. See [restart](https://rsbuild.rs/api/javascript-api/core#restart-handling) . ### [#](https://rsbuild.rs/api/javascript-api/core#pass-configuration) Pass configuration You can pass an Rsbuild configuration object to the `config` option: import { createRsbuild, type RsbuildConfig } from '@rsbuild/core'; const config: RsbuildConfig = { // Rsbuild configuration }; const rsbuild = await createRsbuild({ config }); You can also pass the complete result returned by [`loadConfig`](https://rsbuild.rs/api/javascript-api/core#loadconfig) to `config`: import { createRsbuild, loadConfig } from '@rsbuild/core'; const result = await loadConfig(); const rsbuild = await createRsbuild({ config: result, }); When the complete `loadConfig` result is passed, the absolute paths of the config file and its imported dependencies are stored in [`rsbuild.context.configFile`](https://rsbuild.rs/api/javascript-api/instance#contextconfigfile) and [`rsbuild.context.configFileDependencies`](https://rsbuild.rs/api/javascript-api/instance#contextconfigfiledependencies) , respectively. When persistent build cache is enabled, these files are also used as build dependencies. See [Configuration file watching](https://rsbuild.rs/guide/configuration/rsbuild#configuration-file-watching) for how Rsbuild watches them for restart requests. Tip `config` was introduced in Rsbuild 1.6. In earlier versions, use `rsbuildConfig` as an alternative. ### [#](https://rsbuild.rs/api/javascript-api/core#load-configuration-async) Load configuration async `config` can also be an async function for dynamically loading Rsbuild configuration and performing custom operations. import { createRsbuild, loadConfig } from '@rsbuild/core'; const rsbuild = await createRsbuild({ config: async () => { const result = await loadConfig(); someFunctionToUpdateConfig(result.content); return result; }, }); ### [#](https://rsbuild.rs/api/javascript-api/core#load-environment-variables) Load environment variables The `loadEnv` option in `createRsbuild` calls the [loadEnv](https://rsbuild.rs/api/javascript-api/core#loadenv) method to load environment variables: const rsbuild = await createRsbuild({ loadEnv: true, }); Setting `loadEnv: true` automatically completes these steps: 1. Call the `loadEnv` method to load environment variables. 2. Add [source.define](https://rsbuild.rs/config/source/define) configuration, defining the `publicVars` returned by `loadEnv` as global variables. 3. Watch the `.env` file for changes, restart the dev server when the file changes, and invalidate the build cache. 4. Automatically call the `cleanup` method returned by `loadEnv` when closing the build or dev server. You can also pass in the options of the [loadEnv](https://rsbuild.rs/api/javascript-api/core#loadenv) method, for example: const rsbuild = await createRsbuild({ loadEnv: { prefixes: ['PUBLIC_', 'REACT_APP_'], }, }); ### [#](https://rsbuild.rs/api/javascript-api/core#restart-handling) Restart handling * **Version:** Added in v2.1.7 The `restart` option allows the caller to control how Rsbuild restarts the current dev server or watch build. This is useful when the restart flow needs to be managed outside Rsbuild. > See [Configuration file watching](https://rsbuild.rs/guide/configuration/rsbuild#configuration-file-watching) > to learn what triggers a restart. When a restart is requested, Rsbuild calls the [onRestart hook](https://rsbuild.rs/plugins/dev/hooks#onrestart) , closes the current task resources, and then calls `restart`. The `restart` callback receives the options passed to the current `rsbuild.build()` or `rsbuild.startDevServer()` call. The function should return `true` when the replacement task starts successfully. If it returns `false` or throws an error, the restart watcher remains active so later file changes can retry the restart. import { createRsbuild, type RestartFn } from '@rsbuild/core'; async function createInstance() { return createRsbuild({ restart, }); } const restart: RestartFn = async (context) => { const rsbuild = await createInstance(); if (context.action === 'build') { await rsbuild.build(context.options); } else { await rsbuild.startDevServer(context.options); } return true; }; const rsbuild = await createInstance(); await rsbuild.startDevServer(); ### [#](https://rsbuild.rs/api/javascript-api/core#specify-caller-name) Specify caller name You can specify the name of the framework or tool that is currently invoking Rsbuild, which can be accessed by Rsbuild plugins through [context.callerName](https://rsbuild.rs/api/javascript-api/instance#contextcallername) , and execute different logic based on this identifier. import { myPlugin } from './myPlugin'; const rsbuild = await createRsbuild({ callerName: 'rslib', config: { plugins: [myPlugin], }, }); myPlugin.ts export const myPlugin = { name: 'my-plugin', setup(api) { const { callerName } = api.context; if (callerName === 'rslib') { // ... } else if (callerName === 'rsbuild') { // ... } }, }; [#](https://rsbuild.rs/api/javascript-api/core#loadconfig) loadConfig --------------------------------------------------------------------- Load Rsbuild configuration file. * **Type:** function loadConfig(params?: { // Default is process.cwd() cwd?: string; // Specify the configuration file (relative or absolute path) path?: string; // Config file names to search when path is not specified configFileNames?: string[]; /** * The export name to read from the config file * Set to `false` to execute the config file without reading exports * @default 'default' */ exportName?: string | false; meta?: Record; envMode?: string; /** * The command passed to the config function. * @default process.argv[2] */ command?: string; /** * Specify the config loader, can be `auto`, `jiti` or `native`. * - 'auto': Use native Node.js loader first, fallback to jiti if failed * - 'jiti': Use jiti as loader, which supports TypeScript and ESM out of the box * - 'native': Use native Node.js loader. TypeScript config files require * native TypeScript support, such as Node.js 22.6+. * @default 'auto' */ loader?: 'auto' | 'jiti' | 'native'; }): Promise<{ content: Config; filePath: string | null; dependencies: string[]; }>; * **Example:** import { loadConfig } from '@rsbuild/core'; // Load `rsbuild.config.*` from cwd using the default lookup order const result = await loadConfig(); console.log(result.content); // -> Rsbuild config object const rsbuild = await createRsbuild({ config: result, }); If the Rsbuild config file does not exist in the cwd directory, the return value of the loadConfig method is `{ content: {}, filePath: null }`. When `path` is not specified, `loadConfig` searches for config files in the following order: * `rsbuild.config.ts` * `rsbuild.config.js` * `rsbuild.config.mts` * `rsbuild.config.mjs` * `rsbuild.config.cts` * `rsbuild.config.cjs` If multiple config files exist at the same time, `loadConfig` uses the first matching file in this list. ### [#](https://rsbuild.rs/api/javascript-api/core#customize-config-file-names) Customize config file names Use the `configFileNames` option to replace the default lookup list. The file names are resolved relative to `cwd`, and this option is ignored when `path` is specified. import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ configFileNames: ['framework.config.ts', 'framework.config.mjs'], }); ### [#](https://rsbuild.rs/api/javascript-api/core#specify-the-configuration-file) Specify the configuration file Use the `path` option to load the `my-config.ts` configuration file: import { join } from 'node:path'; import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ path: join(__dirname, 'my-config.ts'), }); ### [#](https://rsbuild.rs/api/javascript-api/core#specify-the-export-name) Specify the export name By default, `loadConfig` reads the default export from the config file. Use `exportName` to read a named export instead: rsbuild.config.ts export const rsbuildConfig = { // ... }; import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ exportName: 'rsbuildConfig', }); Set `exportName` to `false` when the config file only needs to be executed and no export should be read. In this case, `content` is `{}`. import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ exportName: false, }); ### [#](https://rsbuild.rs/api/javascript-api/core#passing-meta-object) Passing meta object Load the configuration file and pass in a custom meta object: import { join } from 'node:path'; import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ meta: { foo: 'bar', }, }); In the `defineConfig` configuration function, you can access the `foo` variable through the `meta` object: rsbuild.config.ts export default defineConfig(({ meta }) => { console.log(meta.foo); // bar return config; }); ### [#](https://rsbuild.rs/api/javascript-api/core#passing-command) Passing command By default, `loadConfig` passes `process.argv[2]` as the `command` value to the config function. Use the `command` option to explicitly set this value. import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ command: 'build', }); [#](https://rsbuild.rs/api/javascript-api/core#loadenv) loadEnv --------------------------------------------------------------- Load the [.env](https://rsbuild.rs/guide/advanced/env-vars#env-file) file and return all environment variables starting with the specified prefixes. * **Type:** type LoadEnvOptions = { /** * The root path to load the env file * @default process.cwd() */ cwd?: string; /** * Used to specify the name of the .env.[mode] file * Equivalent to Rsbuild CLI's `--env-mode` option * @default process.env.NODE_ENV */ mode?: string; /** * The prefix of public variables * @default ['PUBLIC_'] */ prefixes?: string[]; /** * Specify a target object to store environment variables. * If not provided, variables will be added to `process.env`. * @default process.env */ processEnv?: Record; }; type LoadEnvResult = { /** All environment variables in the .env file */ parsed: Record; /** The absolute paths to all env files */ filePaths: string[]; /** * Environment variables that start with prefixes. * * @example * ```ts * { * PUBLIC_FOO: 'bar', * } * ``` **/ rawPublicVars: Record; /** * Formatted environment variables that start with prefixes. * The keys contain the prefixes `process.env.*` and `import.meta.env.*`. * The values are processed by `JSON.stringify`. * * @example * ```ts * { * 'process.env.PUBLIC_FOO': '"bar"', * 'import.meta.env.PUBLIC_FOO': '"bar"', * } * ``` **/ publicVars: Record; /** Clear the environment variables mounted on `process.env` */ cleanup: () => void; }; function loadEnv(options?: LoadEnvOptions): LoadEnvResult; * **Example:** import { loadEnv, mergeRsbuildConfig } from '@rsbuild/core'; const { parsed, publicVars } = loadEnv(); const mergedConfig = mergeRsbuildConfig( { source: { define: publicVars, }, }, userConfig, ); This method will also load files such as `.env.local` and `.env.[mode]`, see [Environment variables](https://rsbuild.rs/guide/advanced/env-vars) for details. Tip * Rsbuild CLI will automatically call the `loadEnv()` method. If you are using the Rsbuild CLI, you can set the `mode` parameter through the [\--env-mode](https://rsbuild.rs/guide/advanced/env-vars#env-mode) option. * The `loadEnv` option in [createRsbuild](https://rsbuild.rs/api/javascript-api/core#creatersbuild) will help you call the `loadEnv()` method and handle related operations. ### [#](https://rsbuild.rs/api/javascript-api/core#specify-the-target-object) Specify the target object By default, `loadEnv` uses the `process.env` object to store environment variables. You can specify a target object to store environment variables through the `processEnv` option: import { loadEnv } from '@rsbuild/core'; // Pass an empty object to avoid modifying `process.env` loadEnv({ processEnv: {} }); // Pass a copy of the `process.env` object to avoid modifying the original object loadEnv({ processEnv: { ...process.env } }); [#](https://rsbuild.rs/api/javascript-api/core#mergersbuildconfig) mergeRsbuildConfig ------------------------------------------------------------------------------------- Used to merge multiple Rsbuild configuration objects. The `mergeRsbuildConfig` function takes multiple configuration objects as parameters. It deeply merges each configuration object, automatically combining multiple function values into an array of sequentially executed functions, and returns a new merged configuration object without modifying the input configuration objects. * **Type:** function mergeRsbuildConfig( ...configs: (RsbuildConfig | undefined)[] ): RsbuildConfig; ### [#](https://rsbuild.rs/api/javascript-api/core#basic-example) Basic example import { mergeRsbuildConfig } from '@rsbuild/core'; const config1 = { server: { compress: false, }, }; const config2 = { server: { compress: true, }, }; const mergedConfig = mergeRsbuildConfig(config1, config2); console.log(mergedConfig); // { server: { compress: true } } > This method will not modify the config object in the input parameter. ### [#](https://rsbuild.rs/api/javascript-api/core#merge-rules) Merge rules In addition to deep merging, the `mergeRsbuildConfig` function also handles some options in a special way. For example, [tools.rspack](https://rsbuild.rs/config/tools/rspack) can be set as a function. When multiple configuration objects contain `tools.rspack`, `mergeRsbuildConfig` will not simply retain the last function. On the contrary, it will merge all `tools.rspack` functions or objects into an array. import { mergeRsbuildConfig } from '@rsbuild/core'; const config1 = { tools: { rspack: { someOption: true, }, }, }; const config2 = { tools: { rspack: (config) => { console.log('function 1'); return config; }, }, }; const config3 = { tools: { rspack: (config) => { console.log('function 2'); return config; }, }, }; const mergedConfig = mergeRsbuildConfig(config1, config2, config3); In the above example, the merged configuration is in the following format. The array first contains an object `{ someOption: true }`, followed by two functions in the order they were merged. Each item in the array will be executed in sequence, and the output of the previous function will serve as the input to the next one, ultimately generating an Rspack configuration. const mergedConfig = { tools: { rspack: [\ {\ someOption: true,\ },\ (config) => {\ console.log('function 1');\ return config;\ },\ (config) => {\ console.log('function 2');\ return config;\ },\ ], }, }; By this way, we can ensure that when merging multiple configuration objects, the same multiple `tools.rspack` fields can all be effective. In Rsbuild, most options that support function values use this rule, such as `tools.postcss`, `tools.less`, `tools.bundlerChain`, etc. [#](https://rsbuild.rs/api/javascript-api/core#createlogger) createLogger ------------------------------------------------------------------------- Creates an isolated logger instance. The created logger can also be passed to the [customLogger](https://rsbuild.rs/config/custom-logger) config option. > See [Logging](https://rsbuild.rs/guide/advanced/logging) > for more details. * **Example:** import { createLogger } from '@rsbuild/core'; const logger = createLogger({ level: 'warn' }); logger.warn('This is a warning message'); logger.error('This is an error message'); // Will not print logger.info('This is an info message'); [#](https://rsbuild.rs/api/javascript-api/core#logger) logger ------------------------------------------------------------- A global logger instance that can be used to output logs in a format consistent with Rsbuild. > See [Logging](https://rsbuild.rs/guide/advanced/logging) > for more details. * **Example:** import { logger } from '@rsbuild/core'; logger.info('This is an info message'); [#](https://rsbuild.rs/api/javascript-api/core#rspack) rspack ------------------------------------------------------------- If you need to access the API or plugins exported by [@rspack/core](https://npmjs.com/package/@rspack/core) , you can directly import the `rspack` object from `@rsbuild/core` without installing the `@rspack/core` package separately. * **Type:** `Rspack` * **Example:** // the same as `import { rspack } from '@rspack/core'` import { rspack } from '@rsbuild/core'; console.log(rspack.rspackVersion); // a.b.c console.log(rspack.util.createHash); console.log(rspack.BannerPlugin); Tip * Refer to [Rspack plugins](https://rspack.rs/plugins/) and [Rspack JavaScript API](https://rspack.rs/api/javascript-api/) to learn more about the available Rspack APIs. * It's not recommended to manually install the `@rspack/core` package, as it may conflict with the version that Rsbuild depends on. [#](https://rsbuild.rs/api/javascript-api/core#version) version --------------------------------------------------------------- The version of `@rsbuild/core` currently in use. * **Type:** `string` * **Example:** import { version } from '@rsbuild/core'; console.log(version); // 1.0.0 [#](https://rsbuild.rs/api/javascript-api/core#ensureassetprefix) ensureAssetPrefix ----------------------------------------------------------------------------------- The `ensureAssetPrefix` function is used to prepend a given `assetPrefix` to a string that might be a URL. If the input string is already a complete URL, it returns the string directly. * **Type:** function ensureAssetPrefix( // URL string to be processed, can be a relative path or an absolute URL url: string, // URL prefix to be appended assetPrefix?: Rspack.PublicPath, ) => string; If `assetPrefix` is not passed, Rsbuild uses the default asset prefix `/`. If `assetPrefix` is `'auto'` or a function, this helper returns the input URL unchanged. * **Example:** import { ensureAssetPrefix } from '@rsbuild/core'; ensureAssetPrefix('foo/bar.js', '/static/'); // -> '/static/foo/bar.js' ensureAssetPrefix('foo/bar.js', 'https://example.com/static/'); // -> 'https://example.com/static/foo/bar.js' ensureAssetPrefix( 'https://example.com/index.html', 'https://example.com/static/', ); // -> 'https://example.com/index.html' --- # Rsbuild types - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/javascript-api/types.md. MenuON THIS PAGE [#](https://rsbuild.rs/api/javascript-api/types#rsbuild-types) Rsbuild types ============================================================================ Copy Markdown This section describes some of the type definitions provided by the Rsbuild. [#](https://rsbuild.rs/api/javascript-api/types#rsbuildinstance) RsbuildInstance -------------------------------------------------------------------------------- The type of Rsbuild instance, corresponding to the return value of the [createRsbuild](https://rsbuild.rs/api/javascript-api/core#creatersbuild) method. import type { RsbuildInstance } from '@rsbuild/core'; let rsbuild: RsbuildInstance; [#](https://rsbuild.rs/api/javascript-api/types#rsbuildconfig) RsbuildConfig ---------------------------------------------------------------------------- The type of Rsbuild configuration. import type { RsbuildConfig } from '@rsbuild/core'; const config: RsbuildConfig = { // ... }; You can also import the type definitions of each field in the Rsbuild config: import type { DevConfig, HtmlConfig, ToolsConfig, SourceConfig, ServerConfig, OutputConfig, SecurityConfig, PerformanceConfig, ModuleFederationConfig, } from '@rsbuild/core'; [#](https://rsbuild.rs/api/javascript-api/types#normalizedconfig) NormalizedConfig ---------------------------------------------------------------------------------- The type of Rsbuild configuration after normalization, corresponding to the return value of the [getNormalizedConfig](https://rsbuild.rs/plugins/dev/core#apigetnormalizedconfig) method. import type { NormalizedConfig } from '@rsbuild/core'; const config: NormalizedConfig = api.getNormalizedConfig(); You can also import the type definitions of each field in the normalized config: import type { NormalizedDevConfig, NormalizedHtmlConfig, NormalizedToolsConfig, NormalizedSourceConfig, NormalizedServerConfig, NormalizedOutputConfig, NormalizedSecurityConfig, NormalizedPerformanceConfig, NormalizedModuleFederationConfig, } from '@rsbuild/core'; [#](https://rsbuild.rs/api/javascript-api/types#normalizedenvironmentconfig) NormalizedEnvironmentConfig -------------------------------------------------------------------------------------------------------- The type of Rsbuild environment configuration after normalization, corresponding to the return value of the [`getNormalizedConfig({ environment })`](https://rsbuild.rs/plugins/dev/core#apigetnormalizedconfig) method. import type { NormalizedEnvironmentConfig } from '@rsbuild/core'; const config: NormalizedEnvironmentConfig = api.getNormalizedConfig({ environment, }); [#](https://rsbuild.rs/api/javascript-api/types#rsbuildcontext) RsbuildContext ------------------------------------------------------------------------------ The type of the [context property](https://rsbuild.rs/api/javascript-api/instance#rsbuildcontext) in the Rsbuild instance. import type { RsbuildContext } from '@rsbuild/core'; const context: RsbuildContext = rsbuild.context; [#](https://rsbuild.rs/api/javascript-api/types#rsbuildplugin) RsbuildPlugin ---------------------------------------------------------------------------- Defines the structure and behavior of an Rsbuild plugin. Rsbuild plugins provide a standardized way to extend build functionality through lifecycle hooks and configuration modifications. import type { RsbuildPlugin } from '@rsbuild/core'; const myPlugin: RsbuildPlugin = { name: 'my-plugin', setup() {}, }; [#](https://rsbuild.rs/api/javascript-api/types#rsbuildpluginapi) RsbuildPluginAPI ---------------------------------------------------------------------------------- The API interface that Rsbuild exposes to plugins through the `setup` function. It allows plugins to interact with the build process, modify configurations, register hooks, and access context information. import type { RsbuildPluginAPI } from '@rsbuild/core'; const myPlugin = { name: 'my-plugin', setup(api: RsbuildPluginAPI) {}, }; [#](https://rsbuild.rs/api/javascript-api/types#rsbuildtarget) RsbuildTarget ---------------------------------------------------------------------------- The type of build target. import type { RsbuildTarget } from '@rsbuild/core'; [#](https://rsbuild.rs/api/javascript-api/types#creatersbuildoptions) CreateRsbuildOptions ------------------------------------------------------------------------------------------ The param type of [createRsbuild](https://rsbuild.rs/api/javascript-api/core#creatersbuild) method. import type { CreateRsbuildOptions } from '@rsbuild/core'; [#](https://rsbuild.rs/api/javascript-api/types#inspectconfigoptions) InspectConfigOptions ------------------------------------------------------------------------------------------ The param type of [rsbuild.inspectConfig](https://rsbuild.rs/api/javascript-api/instance#rsbuildinspectconfig) method. import type { InspectConfigOptions } from '@rsbuild/core'; [#](https://rsbuild.rs/api/javascript-api/types#rspack) Rspack -------------------------------------------------------------- Includes all types exported by `@rspack/core`, such as `Rspack.Configuration`. import type { Rspack } from '@rsbuild/core'; const rspackConfig: Rspack.Configuration = {}; [#](https://rsbuild.rs/api/javascript-api/types#others) Others -------------------------------------------------------------- See [@rsbuild/core - src/index.ts](https://github.com/web-infra-dev/rsbuild/blob/main/packages/core/src/index.ts) for all exported types. --- # JavaScript API - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/start/index.md. MenuON THIS PAGE [#](https://rsbuild.rs/api/start/#javascript-api) JavaScript API ================================================================ Copy Markdown Rsbuild provides a comprehensive JavaScript API for developers to build higher-level tools or frameworks on top of Rsbuild. Rsbuild's JavaScript API can be used in Node.js, Deno, or Bun. [#](https://rsbuild.rs/api/start/#getting-started) Getting started ------------------------------------------------------------------ This basic example demonstrates how to use the Rsbuild JavaScript API. ### [#](https://rsbuild.rs/api/start/#1-install-rsbuild) 1\. Install Rsbuild Install the `@rsbuild/core` package: npm yarn pnpm bun deno npm add @rsbuild/core -D yarn add @rsbuild/core -D pnpm add @rsbuild/core -D bun add @rsbuild/core -D deno add npm:@rsbuild/core -D ### [#](https://rsbuild.rs/api/start/#2-create-an-rsbuild-instance) 2\. Create an Rsbuild instance Call the [createRsbuild](https://rsbuild.rs/api/javascript-api/core#creatersbuild) method to create an Rsbuild instance: import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild(); The `createRsbuild` method accepts various options. Learn more in the [API - createRsbuild](https://rsbuild.rs/api/javascript-api/core#creatersbuild) documentation. ### [#](https://rsbuild.rs/api/start/#3-call-rsbuild-instance-methods) 3\. Call Rsbuild instance methods The Rsbuild instance provides several methods for different scenarios. For local development, use the [rsbuild.startDevServer](https://rsbuild.rs/api/javascript-api/instance#rsbuildstartdevserver) method to start a local dev server: await rsbuild.startDevServer(); Once the dev server starts successfully, these logs will appear: ➜ Local: http://localhost:3000 ➜ Network: use --host to expose For production deployment, use the [rsbuild.build](https://rsbuild.rs/api/javascript-api/instance#rsbuildbuild) method to build production outputs: await rsbuild.build(); > For more information about Rsbuild instance methods, see the [Rsbuild instance](https://rsbuild.rs/api/javascript-api/instance) > documentation. These three steps cover the basic usage of Rsbuild. Next, you can customize the build process with Rsbuild plugins and configurations. --- # Environment API - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/javascript-api/environment-api.md. MenuON THIS PAGE [#](https://rsbuild.rs/api/javascript-api/environment-api#environment-api) Environment API ========================================================================================== Copy Markdown Here you can find all environment APIs. > See [Multi-environment builds](https://rsbuild.rs/guide/advanced/environments) > for more details. [#](https://rsbuild.rs/api/javascript-api/environment-api#environment-context) Environment context -------------------------------------------------------------------------------------------------- Environment context is a read-only object that provides context information about the current environment. * **Type:** type EnvironmentContext = { index: number; name: string; browserslist: string[]; config: NormalizedEnvironmentConfig; distPath: string; entry: RsbuildEntry; htmlPaths: Record; tsconfigPath?: string; manifest?: Record | ManifestData; webSocketToken: string; }; You can get the environment context in the following ways: 1. In Rsbuild's [Plugin hooks](https://rsbuild.rs/plugins/dev/hooks#plugin-hooks) , you can get the environment context object through the `environment` or `environments` parameter. 2. In the [Environment API](https://rsbuild.rs/api/javascript-api/environment-api#environment-api-1) , it is available via `environments[name].context`. ### [#](https://rsbuild.rs/api/javascript-api/environment-api#index) index The zero-based index of the current environment. * **Type:** `number` ### [#](https://rsbuild.rs/api/javascript-api/environment-api#name) name The unique name of the current environment, used to distinguish and locate the environment. Corresponds to the key in the [environments](https://rsbuild.rs/config/environments) configuration. * **Type:** `string` * **Example:** api.modifyRspackConfig((config, { environment }) => { if (environment.name === 'node') { // modify config for node environment } return config; }); ### [#](https://rsbuild.rs/api/javascript-api/environment-api#browserslist) browserslist The browserslist configuration of the current environment. See [Browserslist](https://rsbuild.rs/guide/advanced/browserslist) for more details. * **Type:** `string[]` * **Example:** api.modifyRspackConfig((config, { environment }) => { console.log(environment.browserslist); return config; }); ### [#](https://rsbuild.rs/api/javascript-api/environment-api#config) config The normalized Rsbuild config for the current environment. * **Type:** type NormalizedEnvironmentConfig = TwoLevelReadonly<{ mode: RsbuildMode; root: string; dev: NormalizedDevConfig; server: NormalizedServerConfig; html: NormalizedHtmlConfig; tools: NormalizedToolsConfig; resolve: NormalizedResolveConfig; source: NormalizedSourceConfig; output: NormalizedOutputConfig; plugins?: RsbuildPlugins; security: NormalizedSecurityConfig; performance: NormalizedPerformanceConfig; splitChunks: NormalizedSplitChunksConfig | false; moduleFederation?: ModuleFederationConfig; }>; * **Example:** api.modifyRspackConfig((config, { environment }) => { // Rspack config console.log(config); // Rsbuild config for current environment console.log(environment.config); return config; }); ### [#](https://rsbuild.rs/api/javascript-api/environment-api#distpath) distPath The absolute path of the output directory, corresponding to the [output.distPath.root](https://rsbuild.rs/config/output/dist-path) config of Rsbuild. * **Type:** `string` api.modifyRspackConfig((config, { environment }) => { console.log(environment.distPath); return config; }); ### [#](https://rsbuild.rs/api/javascript-api/environment-api#entry) entry The entry object from the [source.entry](https://rsbuild.rs/config/source/entry) option. * **Type:** type RsbuildEntry = Record; * **Example:** api.modifyRspackConfig((config, { environment }) => { console.log(environment.entry); return config; }); ### [#](https://rsbuild.rs/api/javascript-api/environment-api#htmlpaths) htmlPaths The path information for all HTML assets. This value is an object, the key is the entry name and the value is the relative path of the HTML file in the dist directory. * **Type:** type htmlPaths = Record; * **Example:** api.modifyRspackConfig((config, { environment }) => { console.log(environment.htmlPaths); return config; }); ### [#](https://rsbuild.rs/api/javascript-api/environment-api#tsconfigpath) 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; * **Example:** api.modifyRspackConfig((config, { environment }) => { console.log(environment.tsconfigPath); return config; }); ### [#](https://rsbuild.rs/api/javascript-api/environment-api#manifest) manifest The manifest data. Only available when the [output.manifest](https://rsbuild.rs/config/output/manifest) config is enabled. * **Type:** `Record | ManifestData | undefined` * **Example:** api.onAfterBuild(({ environments }) => { // Get the manifest data of web environment console.log(environments.web.manifest); }); api.onAfterDevCompile(({ environments }) => { console.log(environments.web.manifest); }); api.onAfterEnvironmentCompile(({ environment }) => { console.log(environment.manifest); }); The manifest data is only available after the build has completed, you can access it in the following hooks: * [onAfterBuild](https://rsbuild.rs/plugins/dev/hooks#onafterbuild) * [onAfterEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onafterenvironmentcompile) * [onCloseBuild](https://rsbuild.rs/plugins/dev/hooks#onclosebuild) * [onCloseDevServer](https://rsbuild.rs/plugins/dev/hooks#onclosedevserver) * [onAfterDevCompile](https://rsbuild.rs/plugins/dev/hooks#onafterdevcompile) * [onExit](https://rsbuild.rs/plugins/dev/hooks#onexit) ### [#](https://rsbuild.rs/api/javascript-api/environment-api#websockettoken) webSocketToken WebSocket authentication token, used to authenticate WebSocket connections and prevent unauthorized access. It contains a token when Rsbuild runs the `dev` action and is an empty string for other actions. * **Type:** `string` * **Version:** Added in v1.4.4 When you need to establish a WebSocket connection with the Rsbuild dev server in the browser, you need to use this token as a query parameter. const { webSocketToken } = environments.web.context; const webSocketUrl = `ws://localhost:${port}${pathname}?token=${webSocketToken}`; [#](https://rsbuild.rs/api/javascript-api/environment-api#environment-api-1) Environment API -------------------------------------------------------------------------------------------- Environment API provides some APIs related to the multi-environment build. You can use environment API via [rsbuild.createDevServer()](https://rsbuild.rs/api/javascript-api/instance#rsbuildcreatedevserver) or [server.setup](https://rsbuild.rs/config/server/setup) , which allows you to get the build outputs information for a specific environment in the server side. type EnvironmentAPI = { [name: string]: { context: EnvironmentContext; getStats: () => Promise; loadBundle: (entryName: string) => Promise; getTransformedHtml: (entryName: string) => Promise; hot: { send: HotSend; }; }; }; ### [#](https://rsbuild.rs/api/javascript-api/environment-api#context) context You can get context information related to the current environment through the Environment API. * **Type:** [EnvironmentContext](https://rsbuild.rs/api/javascript-api/environment-api#environment-context) * **Example:** const webManifest = environments.web.context.manifest; console.log(webManifest.entries); ### [#](https://rsbuild.rs/api/javascript-api/environment-api#getstats) getStats Get the build stats of current environment. * **Type:** type GetStats = () => Promise; * **Example:** const webStats = await environments.web.getStats(); console.log(webStats.toJson({ all: false })); ### [#](https://rsbuild.rs/api/javascript-api/environment-api#loadbundle) loadBundle Loads and executes the compiled bundle on the server. This method returns the exported content of the specified entry module and is typically used to run bundles generated by Rsbuild in a server-side environment. `loadBundle` resolves only after the build process has finished and the [onAfterDevCompile](https://rsbuild.rs/plugins/dev/hooks#onafterdevcompile) hook has completed. As a result, it cannot be called within the `onAfterDevCompile` hook. * **Type:** /** * @param entryName - Entry name, corresponding to a key in Rsbuild `source.entry` * @returns The return value of the entry module */ type LoadBundle = (entryName: string) => Promise; * **Example:** // Load the bundle of `main` entry const result = await environments.node.loadBundle('main'); ### [#](https://rsbuild.rs/api/javascript-api/environment-api#gettransformedhtml) getTransformedHtml Get the HTML template content after compilation and transformation. * **Type:** type GetTransformedHtml = (entryName: string) => Promise; * **Example:** // Get the HTML content of main entry const html = await environments.web.getTransformedHtml('main'); This method returns the complete HTML string, including all resources and content injected through HTML plugins. ### [#](https://rsbuild.rs/api/javascript-api/environment-api#hotsend) hot.send Send an HMR message to the client of the current environment only. This works the same as [server.sockWrite](https://rsbuild.rs/api/javascript-api/server-api#sockwrite) , but it only affects the matched environment. * **Type:** type HotSend = { (type: 'full-reload', data?: { path?: string }): void; (type: 'static-changed'): void; (type: 'custom', data: { event: string; data?: any }): void; }; #### [#](https://rsbuild.rs/api/javascript-api/environment-api#full-reload) full-reload If you send a `'full-reload'` message, the page will reload. if (someCondition) { environments.web.hot.send('full-reload'); } When `path` is provided and ends with `.html`, Rsbuild only reloads the page whose current URL matches that HTML path in the current environment. When `path` is `'*'`, Rsbuild reloads all pages in the current environment. The HTML path should be relative to the dev server root and should not include `server.base`. environments.web.hot.send('full-reload', { path: '/foo.html', }); > `'static-changed'` is an alias of `'full-reload'`. #### [#](https://rsbuild.rs/api/javascript-api/environment-api#custom) custom You can also send custom messages via `custom` type with optional data to the browser and handle them via HMR events: environments.web.hot.send('custom', { event: 'count', data: { value: 1 }, }); Rsbuild extends the `on()` method on Rspack’s [import.meta.webpackHot](https://rspack.rs/api/runtime-api/hmr) object. It allows you to listen for custom events in the browser and handle the associated data: client.js if (import.meta.webpackHot) { import.meta.webpackHot.on('count', (data) => { console.log('count update', data.value); }); import.meta.webpackHot.accept(); } --- # Server API - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/javascript-api/server-api.md. MenuON THIS PAGE [#](https://rsbuild.rs/api/javascript-api/server-api#server-api) Server API =========================================================================== Copy Markdown Rsbuild provides server APIs for both dev and preview servers, available through configuration, plugin hooks, and JavaScript API. [#](https://rsbuild.rs/api/javascript-api/server-api#how-to-use) How to use --------------------------------------------------------------------------- ### [#](https://rsbuild.rs/api/javascript-api/server-api#configuration) Configuration Rsbuild provides the [server.setup](https://rsbuild.rs/config/server/setup) option to access dev and preview server instances. rsbuild.config.ts export default { server: { setup: ({ server }) => { console.log('the server is ', server); }, }, }; ### [#](https://rsbuild.rs/api/javascript-api/server-api#plugin-hooks) Plugin hooks Plugin authors can access dev and preview server instances through the [onBeforeStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartdevserver) and [onBeforeStartPreviewServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartpreviewserver) hooks. const myPlugin = () => ({ setup(api) { api.onBeforeStartDevServer(({ server }) => { console.log('the dev server is ', server); }); api.onBeforeStartPreviewServer(({ server }) => { console.log('the preview server is ', server); }); }, }); ### [#](https://rsbuild.rs/api/javascript-api/server-api#javascript-api) JavaScript API * Create a dev server instance via [rsbuild.createDevServer](https://rsbuild.rs/api/javascript-api/instance#rsbuildcreatedevserver) : const devServer = await rsbuild.createDevServer(); console.log('the dev server is ', devServer); * Get the dev server instance via [rsbuild.startDevServer](https://rsbuild.rs/api/javascript-api/instance#rsbuildstartdevserver) : const { server } = await rsbuild.startDevServer(); console.log('the dev server is ', server); * Get the preview server instance via [rsbuild.preview](https://rsbuild.rs/api/javascript-api/instance#rsbuildpreview) : const { server } = await rsbuild.preview(); console.log('the preview server is ', server); [#](https://rsbuild.rs/api/javascript-api/server-api#example) Example --------------------------------------------------------------------- ### [#](https://rsbuild.rs/api/javascript-api/server-api#integrate-with-custom-server) Integrate with custom server Here is an example of integrating [express](https://expressjs.com/) with Rsbuild dev server: import { createRsbuild } from '@rsbuild/core'; import express from 'express'; async function startDevServer() { // Init Rsbuild const rsbuild = await createRsbuild({ config: { server: { middlewareMode: true, }, }, }); const app = express(); // Create Rsbuild dev server instance const rsbuildServer = await rsbuild.createDevServer(); // Apply Rsbuild's built-in middleware app.use(rsbuildServer.middlewares); const server = app.listen(rsbuildServer.port, async () => { // Notify Rsbuild that the custom server has started await rsbuildServer.afterListen(); }); // Activate WebSocket connection rsbuildServer.connectWebSocket({ server }); } For detailed usage, see: * [Example code](https://github.com/rstackjs/rstack-examples/blob/main/rsbuild/express/server.mjs) . * [rsbuild.createDevServer](https://rsbuild.rs/api/javascript-api/instance#rsbuildcreatedevserver) * [server.middlewareMode](https://rsbuild.rs/config/server/middleware-mode) [#](https://rsbuild.rs/api/javascript-api/server-api#shared-api) Shared API --------------------------------------------------------------------------- Common methods and properties that are available in both dev and preview servers. ### [#](https://rsbuild.rs/api/javascript-api/server-api#close) close * **Type:** `() => Promise` Calling the `close()` method to perform necessary cleanup operations. In the dev server, this will also trigger the [onCloseDevServer](https://rsbuild.rs/plugins/dev/hooks#onclosedevserver) hook. import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild(); const rsbuildServer = await rsbuild.createDevServer(); await rsbuildServer.close(); ### [#](https://rsbuild.rs/api/javascript-api/server-api#httpserver) httpServer * **Type:** `import('node:http').Server | import('node:http2').Http2SecureServer | null` The Node.js HTTP server instance. * If [server.https](https://rsbuild.rs/config/server/https) is enabled, this is an `Http2SecureServer`. * If [server.middlewareMode](https://rsbuild.rs/config/server/middleware-mode) is enabled, this is `null`. ### [#](https://rsbuild.rs/api/javascript-api/server-api#middlewares) middlewares * **Type:** `Connect.Server` The `connect` instance. Can be used to attach custom middleware to the server. const rsbuildServer = await rsbuild.createDevServer(); rsbuildServer.middlewares.use((req, res, next) => { if (req.url === '/foo') { res.end('ok'); return; } next(); }); > See [Middleware](https://rsbuild.rs/guide/basic/server#middleware) > to learn more. ### [#](https://rsbuild.rs/api/javascript-api/server-api#open) open * **Type:** `() => Promise` Open URL in the browser after starting the server. const { server } = await rsbuild.startDevServer(); await server.open(); ### [#](https://rsbuild.rs/api/javascript-api/server-api#port) port * **Type:** `number` The resolved port number. It starts from [server.port](https://rsbuild.rs/config/server/port) by default, and automatically increments to an available port when occupied. const { server } = await rsbuild.startDevServer(); console.log(server.port); ### [#](https://rsbuild.rs/api/javascript-api/server-api#printurls) printUrls * **Type:** `() => void` Print the server URLs. const { server } = await rsbuild.startDevServer(); server.printUrls(); [#](https://rsbuild.rs/api/javascript-api/server-api#dev-server-api) Dev server API ----------------------------------------------------------------------------------- Additional methods and properties that are only available in dev servers. ### [#](https://rsbuild.rs/api/javascript-api/server-api#afterlisten) afterListen * **Type:** `() => Promise` Notifies Rsbuild that the custom server has successfully started. Rsbuild will trigger the [onAfterStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onafterstartdevserver) hook at this stage. For example: import express from 'express'; import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild(); const rsbuildServer = await rsbuild.createDevServer(); const app = express(); const server = app.listen(rsbuildServer.port, async () => { await rsbuildServer.afterListen(); }); ### [#](https://rsbuild.rs/api/javascript-api/server-api#connectwebsocket) connectWebSocket * **Type:** type ConnectWebSocket = (options: { server: import('node:http').Server | import('node:http2').Http2SecureServer; }) => void; Activates the WebSocket connection. This ensures that HMR works properly. Rsbuild has a built-in WebSocket handler to support HMR: 1. When a user accesses a page through browser, a WebSocket connection request is automatically initiated to the server. 2. After the Rsbuild dev server detects the connection request, it instructs the built-in WebSocket handler to process it. 3. After the browser successfully establishes a connection with the Rsbuild WebSocket handler, real-time communication is possible. 4. The Rsbuild WebSocket handler notifies the browser after each recompilation is complete. The browser then sends a `hot-update.(js|json)` request to the dev server to load the new compiled module. When you use a custom server, you may encounter HMR connection error problems. This is because the custom server does not forward WebSocket connection requests to Rsbuild's WebSocket handler. At this time, you need to use the `connectWebSocket` method to enable Rsbuild to sense and process the WebSocket connection request from the browser. import express from 'express'; import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild(); const rsbuildServer = await rsbuild.createDevServer(); const app = express(); const httpServer = app.listen(rsbuildServer.port); rsbuildServer.connectWebSocket({ server: httpServer }); ### [#](https://rsbuild.rs/api/javascript-api/server-api#environments) environments * **Type:** [EnvironmentAPI](https://rsbuild.rs/api/javascript-api/environment-api#environment-api) Provides Rsbuild's [environment API](https://rsbuild.rs/api/javascript-api/environment-api#environment-api) , which allows you to get the build outputs information for a specific environment in the server side. rsbuild.config.ts const rsbuildServer = await rsbuild.createDevServer(); const webStats = await rsbuildServer.environments.web.getStats(); console.log(webStats.toJson({ all: false })); ### [#](https://rsbuild.rs/api/javascript-api/server-api#listen) listen * **Type:** `() => Promise<{ port: number; urls: string[]; server: RsbuildDevServer }>` Starts the server and returns the listening result. If you are using [server.middlewareMode](https://rsbuild.rs/config/server/middleware-mode) , you usually don't need to call this method. const rsbuildServer = await rsbuild.createDevServer(); const { port, urls } = await rsbuildServer.listen(); console.log(port, urls); ### [#](https://rsbuild.rs/api/javascript-api/server-api#sockwrite) sockWrite * **Type:** type HotSend = { (type: 'full-reload', data?: { path?: string }): void; (type: 'static-changed'): void; (type: 'custom', data: { event: string; data?: any }): void; }; Sends some message to HMR client, and then the HMR client will take different actions depending on the message type. const rsbuildServer = await rsbuild.createDevServer(); if (someCondition) { rsbuildServer.sockWrite('full-reload'); } Tip `sockWrite` is not the recommended API for sending messages. Prefer [hot.send](https://rsbuild.rs/api/javascript-api/environment-api#hotsend) instead. --- # Rsbuild instance - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/javascript-api/instance.md. MenuON THIS PAGE [#](https://rsbuild.rs/api/javascript-api/instance#rsbuild-instance) Rsbuild instance ===================================================================================== Copy Markdown This section describes all the properties and methods on the Rsbuild instance object. [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildcontext) rsbuild.context ---------------------------------------------------------------------------------- `rsbuild.context` is a read-only object that provides some context information, which can be accessed in two ways: 1. Access through the `context` property of the Rsbuild instance: import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild({ // ... }); console.log(rsbuild.context); 2. Access through the [api.context](https://rsbuild.rs/plugins/dev/core#apicontext) of the Rsbuild plugin: export const myPlugin = { name: 'my-plugin', setup(api) { console.log(api.context); }, }; ### [#](https://rsbuild.rs/api/javascript-api/instance#contextversion) context.version The version of `@rsbuild/core` currently in use. * **Type:** type Version = string; ### [#](https://rsbuild.rs/api/javascript-api/instance#contextrootpath) context.rootPath The root path of the current build, corresponding to the `cwd` option of the [createRsbuild](https://rsbuild.rs/api/javascript-api/core#creatersbuild) method. * **Type:** type RootPath = string; ### [#](https://rsbuild.rs/api/javascript-api/instance#contextconfigfile) context.configFile The absolute path to the configuration file loaded by [loadConfig](https://rsbuild.rs/api/javascript-api/core#loadconfig) . It is `undefined` when no configuration file is loaded. * **Type:** `string | undefined` ### [#](https://rsbuild.rs/api/javascript-api/instance#contextconfigfiledependencies) context.configFileDependencies The absolute paths of files imported by the configuration file. The dependencies are collected by [loadConfig](https://rsbuild.rs/api/javascript-api/core#loadconfig) . * **Type:** `readonly string[]` * **Default:** `[]` ### [#](https://rsbuild.rs/api/javascript-api/instance#contextdistpath) context.distPath The absolute path of the output directory, corresponding to the [output.distPath.root](https://rsbuild.rs/config/output/dist-path) config in `RsbuildConfig`. When multiple environments exist, Rsbuild attempts to find the parent distPath of all environments as `context.distPath`. To get the absolute path to a specific environment's output directory, use [environment.distPath](https://rsbuild.rs/api/javascript-api/environment-api#distpath) . * **Type:** type DistPath = string; ### [#](https://rsbuild.rs/api/javascript-api/instance#contextcachepath) context.cachePath The absolute path of the build cache files. * **Type:** type CachePath = string; ### [#](https://rsbuild.rs/api/javascript-api/instance#contextcallername) context.callerName The name of the framework or tool that is currently invoking Rsbuild, the same as the [callerName](https://rsbuild.rs/api/javascript-api/core#specify-caller-name) option in the [createRsbuild](https://rsbuild.rs/api/javascript-api/core#creatersbuild) method. * **Type:** `string` * **Default:** `'rsbuild'` * **Example:** myPlugin.ts export const myPlugin = { name: 'my-plugin', setup(api) { const { callerName } = api.context; if (callerName === 'rslib') { // ... } else if (callerName === 'rsbuild') { // ... } }, }; Here are some tools based on Rsbuild that have already set the `callerName` value: | Name | callerName | | --- | --- | | [Rslib](https://github.com/web-infra-dev/rslib) | `'rslib'` | | [Rstest](https://github.com/web-infra-dev/rstest) | `'rstest'` | | [Rspress](https://github.com/web-infra-dev/rspress) | `'rspress'` | | [Rspeedy](https://lynxjs.org/rspeedy) | `'rspeedy'` | ### [#](https://rsbuild.rs/api/javascript-api/instance#contextdevserver) context.devServer Dev server information when running in dev mode. Available after the dev server has been created. * **Type:** type DevServer = { /** The hostname the server is running on. */ hostname: string; /** The actual port number the server is listening on. */ port: number; /** Whether the server is using HTTPS protocol. */ https: boolean; }; * **Example:** import { createRsbuild } from '@rsbuild/core'; async function main() { const rsbuild = await createRsbuild({ // ... }); await rsbuild.startDevServer(); // { hostname: 'localhost', port: 3000, https: false } console.log(rsbuild.context.devServer); } ### [#](https://rsbuild.rs/api/javascript-api/instance#contextaction) context.action The current action type. * **Type:** type Action = 'dev' | 'build' | 'preview' | undefined; `context.action` is set when running CLI commands or calling Rsbuild instance methods: * `dev`: set when running [rsbuild dev](https://rsbuild.rs/guide/basic/cli#rsbuild) or [rsbuild.startDevServer()](https://rsbuild.rs/api/javascript-api/instance#rsbuildstartdevserver) * `build`: set when running [rsbuild build](https://rsbuild.rs/guide/basic/cli#rsbuild-build) or [rsbuild.build()](https://rsbuild.rs/api/javascript-api/instance#rsbuildbuild) * `preview`: set when running [rsbuild preview](https://rsbuild.rs/guide/basic/cli#rsbuild-preview) or [rsbuild.preview()](https://rsbuild.rs/api/javascript-api/instance#rsbuildpreview) For example: if (rsbuild.context.action === 'dev') { // do something } [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildlogger) rsbuild.logger -------------------------------------------------------------------------------- `rsbuild.logger` is the logger associated with the current Rsbuild instance. See [Logging](https://rsbuild.rs/guide/advanced/logging) for more details. * **Type:** [Logger](https://rsbuild.rs/api/javascript-api/core#logger) * **Example:** const rsbuild = await createRsbuild(); rsbuild.logger.info('build started'); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildbuild) rsbuild.build ------------------------------------------------------------------------------ Runs a production build, generating optimized production bundles and writing them to the output directory. * **Type:** type BuildOptions = { /** * Whether to watch for file changes and rebuild. * @default false */ watch?: boolean; }; function Build(options?: BuildOptions): Promise<{ /** * Rspack's [stats](https://rspack.rs/api/javascript-api/stats) object. */ stats?: Rspack.Stats | Rspack.MultiStats; /** * Close the build and call the `onCloseBuild` hook. * In watch mode, this method will stop watching. */ close: () => Promise; }>; * **Example:** import { logger } from '@rsbuild/core'; // Example 1: run build await rsbuild.build(); // Example 2: build and handle the error try { await rsbuild.build(); } catch (err) { logger.error('Failed to build.'); logger.error(err); process.exit(1); } // Example 3: build and get all assets const { stats } = await rsbuild.build(); if (stats) { const { assets } = stats.toJson({ // exclude unused fields to improve performance all: false, assets: true, }); console.log(assets); } ### [#](https://rsbuild.rs/api/javascript-api/instance#monitor-file-changes) Monitor file changes To watch file changes and re-build, set the `watch` option to `true`. await rsbuild.build({ watch: true, }); ### [#](https://rsbuild.rs/api/javascript-api/instance#close-build) Close build `rsbuild.build()` returns a `close()` method that stops the build process. In watch mode, calling the `close()` method will stop watching: const buildResult = await rsbuild.build({ watch: true, }); await buildResult.close(); In non-watch mode, also call the `close()` method to end the build, which triggers the [onCloseBuild](https://rsbuild.rs/plugins/dev/hooks#onclosebuild) hook for cleanup operations. const buildResult = await rsbuild.build(); await buildResult.close(); ### [#](https://rsbuild.rs/api/javascript-api/instance#stats-object) Stats object In non-watch mode, `rsbuild.build()` returns an Rspack [stats](https://rspack.rs/api/javascript-api/stats) object. For example, use the `stats.toJson()` method to get asset information: const result = await rsbuild.build(); const { stats } = result; if (stats) { const { assets } = stats.toJson({ // exclude unused fields to improve performance all: false, assets: true, }); console.log(assets); } [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildstartdevserver) rsbuild.startDevServer ------------------------------------------------------------------------------------------------ Starts the local dev server. This method will: 1. Start a development server to serve your application 2. Watch for file changes and trigger recompilation * **Type:** type StartDevServerOptions = { /** * Whether to get port silently and not print any logs. * @default false */ getPortSilently?: boolean; }; type StartDevServerResult = { /** * The URLs that server is listening on. */ urls: string[]; /** * The actual port used by the server. */ port: number; server: RsbuildDevServer; }; function StartDevServer( options?: StartDevServerOptions, ): Promise; * **Example:** Start dev server: import { logger } from '@rsbuild/core'; // Start dev server await rsbuild.startDevServer(); // Start dev server and handle the error try { await rsbuild.startDevServer(); } catch (err) { logger.error('Failed to start dev server.'); logger.error(err); process.exit(1); } Once the dev server starts successfully, these logs appear: ➜ Local: http://localhost:3000 ➜ Network: use --host to expose `startDevServer` returns these parameters: * `urls`: URLs to access dev server. * `port`: The actual listening port number. * `server`: Server instance, see [Server API](https://rsbuild.rs/api/javascript-api/server-api) for more details. const { urls, port } = await rsbuild.startDevServer(); console.log(urls); // ['http://localhost:3000', 'http://192.168.0.1:3000'] console.log(port); // 3000 ### [#](https://rsbuild.rs/api/javascript-api/instance#close-server) Close server Call the `server.close()` method to close the dev server, trigger the [onCloseDevServer](https://rsbuild.rs/plugins/dev/hooks#onclosedevserver) hook, and perform cleanup operations. const { server } = await rsbuild.startDevServer(); await server.close(); ### [#](https://rsbuild.rs/api/javascript-api/instance#get-port-silently) Get port silently When the default startup port is occupied, Rsbuild automatically increments the port number until it finds an available one. This process outputs a prompt log. To suppress this log, set `getPortSilently` to `true`. await rsbuild.startDevServer({ getPortSilently: true, }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildcreatedevserver) rsbuild.createDevServer -------------------------------------------------------------------------------------------------- * **Type:** type CreateDevServerOptions = { /** * Whether to get port silently and not print any logs. * @default false */ getPortSilently?: boolean; /** * Whether to trigger Rsbuild compilation * @default true */ runCompile?: boolean; }; function createDevServer( options?: CreateDevServerOptions, ): Promise; Rsbuild includes a built-in dev server designed to improve the development experience. When you run the `rsbuild dev` command, the server starts automatically and provides features such as page preview, routing, and hot module reloading. * To integrate the Rsbuild dev server into a custom server, you can use the `createDevServer` method to create a dev server instance. Refer to [Server API](https://rsbuild.rs/api/javascript-api/server-api) for all available APIs. * To use Rsbuild dev server to start the project directly, you can use the [rsbuild.startDevServer](https://rsbuild.rs/api/javascript-api/instance#rsbuildstartdevserver) method directly. `rsbuild.startDevServer` is actually syntactic sugar for the following code: const server = await rsbuild.createDevServer(); await server.listen(); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildpreview) rsbuild.preview ---------------------------------------------------------------------------------- Starts a server to preview the production build locally. This method should be executed after [rsbuild.build](https://rsbuild.rs/api/javascript-api/instance#rsbuildbuild) . * **Type:** type PreviewOptions = { /** * Whether to get port silently * @default false */ getPortSilently?: boolean; /** * Whether to check if the dist directory exists and is not empty. * @default true */ checkDistDir?: boolean; }; type StartPreviewServerResult = { /** * The URLs that server is listening on. */ urls: string[]; /** * The actual port used by the server. */ port: number; server: RsbuildPreviewServer; }; function preview(options?: PreviewOptions): Promise; * **Example:** Start the server: import { logger } from '@rsbuild/core'; // Start preview server await rsbuild.preview(); // Start preview server and handle the error try { await rsbuild.preview(); } catch (err) { logger.error('Failed to start preview server.'); logger.error(err); process.exit(1); } `preview` returns the following parameters: * `urls`: URLs to access server. * `port`: The actual listening port number. * `server`: Server instance, see [Server API](https://rsbuild.rs/api/javascript-api/server-api) for more details. const { urls, port } = await rsbuild.preview(); console.log(urls); // ['http://localhost:3000', 'http://192.168.0.1:3000'] console.log(port); // 3000 ### [#](https://rsbuild.rs/api/javascript-api/instance#close-server-1) Close server Calling the `close()` method will close the preview server. const { server } = await rsbuild.preview(); await server.close(); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildcreatecompiler) rsbuild.createCompiler ------------------------------------------------------------------------------------------------ Creates an Rspack [Compiler](https://rspack.rs/api/javascript-api/compiler) instance. If there are multiple [environments](https://rsbuild.rs/config/environments) for this build, the return value is [MultiCompiler](https://rspack.rs/api/javascript-api/compiler#multicompiler) . * **Type:** function CreateCompiler(): Promise; * **Example:** const compiler = await rsbuild.createCompiler(); > You do not need to use this API unless you need to custom the dev server or other advanced scenarios. [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildaddplugins) rsbuild.addPlugins ---------------------------------------------------------------------------------------- Registers 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; environment?: string }; function AddPlugins( plugins: Array, options?: AddPluginsOptions, ): void; * **Example:** rsbuild.addPlugins([pluginFoo(), pluginBar()]); // Insert before the bar plugin rsbuild.addPlugins([pluginFoo()], { before: 'bar' }); // Add plugin for node environment rsbuild.addPlugins([pluginFoo()], { environment: 'node' }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildgetplugins) rsbuild.getPlugins ---------------------------------------------------------------------------------------- Gets all the Rsbuild plugins registered in the current Rsbuild instance. * **Type:** function GetPlugins(options?: { /** * Get the plugins in the specified environment. * If environment is not specified, get the global plugins. */ environment: string; }): RsbuildPlugin[]; * **Example:** // get all plugins console.log(rsbuild.getPlugins()); // get plugins in `web` environment console.log(rsbuild.getPlugins({ environment: 'web' })); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildremoveplugins) 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[], options?: { /** * Remove the plugin in the specified environment. * If environment is not specified, remove it in all environments. */ environment?: string; }, ): void; * **Example:** // add plugin const foo = pluginFoo(); rsbuild.addPlugins([foo]); // remove plugin rsbuild.removePlugins([foo.name]); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildispluginexists) rsbuild.isPluginExists ------------------------------------------------------------------------------------------------ Determines if a plugin has been registered in the current Rsbuild instance. * If the `environment` parameter is not specified, it checks if the plugin exists in the globally registered plugins. * If the `environment` parameter is specified, it checks if the plugin exists in the specified environment. * **Type:** function IsPluginExists( pluginName: string, options?: { /** * Whether it exists in the specified environment. * If environment is not specified, determine whether the plugin is a global plugin. */ environment: string; }, ): boolean; * **Example:** const pluginFoo = { name: 'plugin-foo', setup(api) { // ... }, }; const rsbuild = await createRsbuild({ config: { plugins: [pluginFoo], }, }); rsbuild.isPluginExists(pluginFoo.name); // true Or check if a plugin exists in a specified environment: const rsbuild = await createRsbuild({ config: { environments: { web: { plugins: [pluginFoo], }, }, }, }); rsbuild.isPluginExists(pluginFoo.name, { environment: 'web', }); // true [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildinitconfigs) rsbuild.initConfigs ------------------------------------------------------------------------------------------ Initialize and return the internal Rspack configurations used by Rsbuild. This method processes all plugins and configurations to generate the final Rspack configs. > Note: You typically do not need to call this method directly since it is automatically invoked by methods like [rsbuild.build](https://rsbuild.rs/api/javascript-api/instance#rsbuildbuild) > and [rsbuild.startDevServer](https://rsbuild.rs/api/javascript-api/instance#rsbuildstartdevserver) > . * **Type:** type InitConfigsOptions = { /** * The current action type. * - dev: will be set when running `rsbuild dev` or `rsbuild.startDevServer()` * - build: will be set when running `rsbuild build` or `rsbuild.build()` * - preview: will be set when running `rsbuild preview` or `rsbuild.preview()` */ action?: 'dev' | 'build' | 'preview'; }; function InitConfigs( options?: InitConfigsOptions, ): Promise; * **Example:** const rspackConfigs = await rsbuild.initConfigs(); console.log(rspackConfigs); const buildConfigs = await rsbuild.initConfigs({ action: 'build', }); console.log(buildConfigs); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildinspectconfig) rsbuild.inspectConfig ---------------------------------------------------------------------------------------------- Inspects and debugs Rsbuild's internal configurations. It provides access to: * The resolved Rsbuild configuration * The environment-specific Rsbuild configurations * The generated Rspack configurations The method serializes these configurations to strings and optionally writes them to disk for inspection. * **Type:** type InspectConfigOptions = { /** * Inspect the config in the specified mode. * Available options: 'development', 'production', or 'none'. * @default Inferred from `process.env.NODE_ENV`: 'development' when unset, * 'development' or 'production' when matching, otherwise 'none'. */ mode?: RsbuildMode; /** * Enables verbose mode to display the complete function * content in the configuration. * @default false */ verbose?: boolean; /** * Specify the output path for inspection results. * @default '/.rsbuild' */ outputPath?: string; /** * Whether to write the inspection results to disk. * @default false */ writeToDisk?: boolean; /** * Extra configurations to be output. * - key: The name of the configuration * - value: The configuration object */ extraConfigs?: Record; }; async function InspectConfig(options?: InspectConfigOptions): Promise<{ rsbuildConfig: string; bundlerConfigs: string[]; environmentConfigs: string[]; origin: { rsbuildConfig: Omit; environmentConfigs: Record; bundlerConfigs: Rspack.Configuration[]; }; }>; Tip To view the Rsbuild and Rspack configurations during the build process, use [debug mode](https://rsbuild.rs/guide/debug/debug-mode) , or obtain them through hooks such as [onBeforeBuild](https://rsbuild.rs/api/javascript-api/instance#rsbuildonbeforebuild) , [onBeforeCreateCompiler](https://rsbuild.rs/api/javascript-api/instance#rsbuildonbeforecreatecompiler) . ### [#](https://rsbuild.rs/api/javascript-api/instance#example) Example Get the content of configs in string format: const { rsbuildConfig, bundlerConfigs } = await rsbuild.inspectConfig(); console.log(rsbuildConfig, bundlerConfigs); Write the config content to disk: await rsbuild.inspectConfig({ writeToDisk: true, }); ### [#](https://rsbuild.rs/api/javascript-api/instance#output-path) Output path You can set the output path using `outputPath`. By default, the files are written to the `.rsbuild` directory under [context.distPath](https://rsbuild.rs/api/javascript-api/instance#contextdistpath) . If `outputPath` is a relative path, it will be resolved relative to `context.distPath`. You can also set `outputPath` to an absolute path, in which case the files will be written directly to that path. For example: import path from 'node:path'; await rsbuild.inspectConfig({ writeToDisk: true, outputPath: path.join(__dirname, 'custom-dir'), }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonbeforecreatecompiler) rsbuild.onBeforeCreateCompiler ---------------------------------------------------------------------------------------------------------------- > Provides the same functionality as the [onBeforeCreateCompiler](https://rsbuild.rs/plugins/dev/hooks#onbeforecreatecompiler) > plugin hook. A callback function that is triggered before the Rspack Compiler instance is created. 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](https://rspack.rs/config/) . It depends on whether multiple [environments](https://rsbuild.rs/config/environments) are configured. * **Type:** function OnBeforeCreateCompiler( callback: (params: { bundlerConfigs: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **Example:** rsbuild.onBeforeCreateCompiler(({ bundlerConfigs }) => { console.log('the Rspack config is ', bundlerConfigs); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonaftercreatecompiler) rsbuild.onAfterCreateCompiler -------------------------------------------------------------------------------------------------------------- > Provides the same functionality as the [onAfterCreateCompiler](https://rsbuild.rs/plugins/dev/hooks#onaftercreatecompiler) > plugin hook. A callback function that is triggered after the Rspack 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](https://rspack.rs/api/javascript-api/compiler) through the `compiler` parameter: * **Type:** function OnAfterCreateCompiler( callback: (params: { compiler: Compiler | MultiCompiler; environments: Record; }) => Promise | void, ): void; * **Example:** rsbuild.onAfterCreateCompiler(({ compiler }) => { console.log('the compiler is ', compiler); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonbeforebuild) rsbuild.onBeforeBuild ---------------------------------------------------------------------------------------------- > Provides the same functionality as the [onBeforeBuild](https://rsbuild.rs/plugins/dev/hooks#onbeforebuild) > plugin hook. 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](https://rspack.rs/config/) . It depends on whether multiple [environments](https://rsbuild.rs/config/environments) are configured. Moreover, you can use `isWatch` to determine whether it is watch mode, and use `isFirstCompile` to determine whether it is the first build on watch mode. * **Type:** function OnBeforeBuild( callback: (params: { isWatch: boolean; isFirstCompile: boolean; bundlerConfigs?: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **Example:** rsbuild.onBeforeBuild(({ bundlerConfigs }) => { console.log('the Rspack config is ', bundlerConfigs); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonafterbuild) rsbuild.onAfterBuild -------------------------------------------------------------------------------------------- > Provides the same functionality as the [onAfterBuild](https://rsbuild.rs/plugins/dev/hooks#onafterbuild) > plugin hook. A callback function that is triggered after running the production build. You can access the build result information via the [stats](https://rspack.rs/api/javascript-api/stats) parameter. Moreover, you can use `isWatch` to determine whether it is watch mode, and use `isFirstCompile` to determine whether it is the first build on watch mode. * **Type:** function OnAfterBuild( callback: (params: { isFirstCompile: boolean; isWatch: boolean; stats?: Stats | MultiStats; environments: Record; }) => Promise | void, ): void; * **Example:** rsbuild.onAfterBuild(({ stats }) => { console.log(stats?.toJson()); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonclosebuild) rsbuild.onCloseBuild -------------------------------------------------------------------------------------------- > Provides the same functionality as the [onCloseBuild](https://rsbuild.rs/plugins/dev/hooks#onclosebuild) > plugin hook. Called when closing the build instance. Can be used to perform cleanup operations when the building is closed. Rsbuild CLI will automatically call this hook after running [rsbuild build](https://rsbuild.rs/guide/basic/cli#rsbuild-build) , while users of the JavaScript API need to manually call the [build.close()](https://rsbuild.rs/api/javascript-api/instance#close-build) method to trigger this hook. * **Type:** function onCloseBuild(callback: () => Promise | void): void; * **Example:** rsbuild.onCloseBuild(async () => { console.log('close build!'); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonbeforestartdevserver) rsbuild.onBeforeStartDevServer ---------------------------------------------------------------------------------------------------------------- > Provides the same functionality as the [onBeforeStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartdevserver) > plugin hook. Called before starting the dev server. Use the `server` parameter to get the dev server instance, see [Server API](https://rsbuild.rs/api/javascript-api/server-api) for more information. * **Type:** type MaybePromise = T | Promise; type OnBeforeStartDevServerFn = (params: { /** * The dev server instance, the same as the return value of `createDevServer`. */ server: RsbuildDevServer; /** * Context information for all environments. */ environments: Record; }) => MaybePromise<(() => MaybePromise) | void>; function OnBeforeStartDevServer(callback: OnBeforeStartDevServerFn): void; * **Example:** rsbuild.onBeforeStartDevServer(({ server, environments }) => { console.log('before starting dev server.'); console.log('the server is ', server); console.log('the environments contexts are: ', environments); }); > See [Plugin hooks - onBeforeStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartdevserver) > for more details. [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonafterstartdevserver) rsbuild.onAfterStartDevServer -------------------------------------------------------------------------------------------------------------- > Provides the same functionality as the [onAfterStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onafterstartdevserver) > plugin hook. 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; environments: Record; }) => Promise | void, ): void; * **Example:** rsbuild.onAfterStartDevServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonclosedevserver) rsbuild.onCloseDevServer ---------------------------------------------------------------------------------------------------- > Provides the same functionality as the [onCloseDevServer](https://rsbuild.rs/plugins/dev/hooks#onclosedevserver) > plugin hook. Called when closing the dev server. Can be used to perform cleanup operations when the dev server is closed. Rsbuild CLI will automatically call this hook at the appropriate time, while users of the JavaScript API need to manually call the [server.close()](https://rsbuild.rs/api/javascript-api/instance#close-server) method to trigger this hook. * **Type:** function onCloseDevServer(callback: () => Promise | void): void; * **Example:** rsbuild.onCloseDevServer(async () => { console.log('close dev server!'); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonbeforestartpreviewserver) rsbuild.onBeforeStartPreviewServer ------------------------------------------------------------------------------------------------------------------------ > Provides the same functionality as the [onBeforeStartPreviewServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartpreviewserver) > plugin hook. Called before starting the preview server. Use the `server` parameter to access the preview server and register custom middlewares. * **Type:** type MaybePromise = T | Promise; type OnBeforeStartPreviewServerFn = (params: { /** * The preview server instance. */ server: RsbuildPreviewServer; /** * Context information for all environments. */ environments: Record; }) => MaybePromise; function OnBeforeStartPreviewServer( callback: OnBeforeStartPreviewServerFn, ): void; * **Example:** rsbuild.onBeforeStartPreviewServer(({ server, environments }) => { console.log('before start!'); console.log('the server is ', server); console.log('the environments contexts are: ', environments); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonafterstartpreviewserver) rsbuild.onAfterStartPreviewServer ---------------------------------------------------------------------------------------------------------------------- > Provides the same functionality as the [onAfterStartPreviewServer](https://rsbuild.rs/plugins/dev/hooks#onafterstartpreviewserver) > plugin hook. Called after starting the 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 OnAfterStartPreviewServer( callback: (params: { port: number; routes: Routes; environments: Record; }) => Promise | void, ): void; * **Example:** rsbuild.onAfterStartPreviewServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonbeforedevcompile) rsbuild.onBeforeDevCompile -------------------------------------------------------------------------------------------------------- > Provides the same functionality as the [onBeforeDevCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforedevcompile) > plugin hook. A callback function that is triggered before the dev compile is executed. You can access the Rspack configuration array through the `bundlerConfigs` parameter. The array may contain one or more [Rspack configurations](https://rspack.rs/config/) . It depends on whether multiple [environments](https://rsbuild.rs/config/environments) are configured. Moreover, you can use `isFirstCompile` to determine whether it is the first compile. * **Type:** function OnBeforeDevCompile( callback: (params: { isWatch: boolean; isFirstCompile: boolean; bundlerConfigs?: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **Version:** Added in v1.5.0 * **Example:** rsbuild.onBeforeDevCompile(({ bundlerConfigs }) => { console.log('the Rspack configs are ', bundlerConfigs); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonafterdevcompile) rsbuild.onAfterDevCompile ------------------------------------------------------------------------------------------------------ > Provides the same functionality as the [onAfterDevCompile](https://rsbuild.rs/plugins/dev/hooks#onafterdevcompile) > plugin hook. Called after each development mode build, you can use `isFirstCompile` to determine whether it is the first build. * **Type:** function OnAfterDevCompile( callback: (params: { isFirstCompile: boolean; stats: Stats | MultiStats; environments: Record; }) => Promise | void, ): void; Tip The `onAfterDevCompile` hook was added in Rsbuild v1.5.0. For earlier versions, you can use the functionally identical `onDevCompileDone` hook. * **Example:** rsbuild.onAfterDevCompile(({ isFirstCompile }) => { if (isFirstCompile) { console.log('first compile!'); } else { console.log('re-compile!'); } }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonbeforeenvironmentcompile) rsbuild.onBeforeEnvironmentCompile ------------------------------------------------------------------------------------------------------------------------ > Provides the same functionality as the [onBeforeEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforeenvironmentcompile) > plugin hook. * **Version:** Added in v1.5.7 * **Example:** rsbuild.onBeforeEnvironmentCompile(({ bundlerConfig, environment }) => { console.log( `the bundler config for the ${environment.name} is `, bundlerConfig, ); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonafterenvironmentcompile) rsbuild.onAfterEnvironmentCompile ---------------------------------------------------------------------------------------------------------------------- > Provides the same functionality as the [onAfterEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onafterenvironmentcompile) > plugin hook. * **Version:** Added in v1.5.7 * **Example:** rsbuild.onAfterEnvironmentCompile(({ isFirstCompile, stats }) => { console.log(stats?.toJson(), isFirstCompile); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonrestart) rsbuild.onRestart -------------------------------------------------------------------------------------- > Provides the same functionality as the [onRestart](https://rsbuild.rs/plugins/dev/hooks#onrestart) > plugin hook. Called when a restart is requested for the dev server or watch build. The hook is triggered in the following cases: * The Rsbuild CLI detects changes to the config file or one of its dependencies. * A configured file event occurs for a file watched by [`dev.watchFiles`](https://rsbuild.rs/config/dev/watch-files) with `type: 'restart'`. * The dev server is manually restarted through a [CLI shortcut](https://rsbuild.rs/config/dev/cli-shortcuts) . > This hook is not triggered for regular rebuilds. When using the JavaScript API, restart watchers are installed by `rsbuild.startDevServer()`, `rsbuild.createDevServer()`, and `rsbuild.build({ watch: true })`. The hook is called when a configured file event occurs. By default, Rsbuild does not close or restart the current task; you can pass the [`restart` option](https://rsbuild.rs/api/javascript-api/core#restart-handling) to handle restart requests. * **Type:** type WatchFileEvent = 'add' | 'change' | 'unlink'; type RestartContext = { filePath?: string; event?: WatchFileEvent; } & ( | { action: 'build'; options: BuildOptions; } | { action: 'dev'; options: StartDevServerOptions; } ); function OnRestart( callback: (context: RestartContext) => Promise | void, ): void; * `action`: The current Rsbuild action being restarted. * `filePath`: The absolute path of the file that triggered the restart. It is `undefined` when the restart is manually triggered. * `event`: The file event that triggered the restart. It is `undefined` when the restart is manually triggered. Available in v2.1.8 or later. * `options`: The options passed to the current `rsbuild.build()` or `rsbuild.startDevServer()` call. * **Version:** Added in v2.1.7 * **Example:** rsbuild.onRestart(async ({ action, filePath }) => { console.log('restart!', action, filePath); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildonexit) rsbuild.onExit -------------------------------------------------------------------------------- > Provides the same functionality as the [onExit](https://rsbuild.rs/plugins/dev/hooks#onexit) > plugin hook. Called when the process is going to exit, this hook can only execute synchronous code. * **Type:** function OnExit(callback: (context: { exitCode: number }) => void): void; * **Example:** rsbuild.onExit(({ exitCode }) => { console.log('exit: ', exitCode); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildgetrsbuildconfig) rsbuild.getRsbuildConfig ---------------------------------------------------------------------------------------------------- > Provides the same functionality as the [getRsbuildConfig](https://rsbuild.rs/plugins/dev/core#apigetrsbuildconfig) > plugin API. Get the Rsbuild config, this method must be called after the `modifyRsbuildConfig` hook is executed. * **Type:** type GetRsbuildConfig = { (): Readonly; (type: 'original' | 'current'): Readonly; (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:** rsbuild.onBeforeBuild(() => { const config = rsbuild.getRsbuildConfig(); console.log(config.html?.title); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildgetnormalizedconfig) rsbuild.getNormalizedConfig ---------------------------------------------------------------------------------------------------------- > Provides the same functionality as the [getNormalizedConfig](https://rsbuild.rs/plugins/dev/core#apigetnormalizedconfig) > plugin API. Returns either the complete normalized Rsbuild config, including all environments, or the normalized config for a specific environment. You can call this method only after the [modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) hook has completed. Unlike [`getRsbuildConfig`](https://rsbuild.rs/plugins/dev/core#apigetrsbuildconfig) , this method returns a normalized config with narrower types. For example, the type of `config.html` no longer includes `undefined`. Use `getNormalizedConfig()` to get the complete config, including all environments. To get the config for a specific environment, use `getNormalizedConfig({ environment: name })`. * **Type:** type GetNormalizedConfig = { /** Get the complete normalized config, including all environments */ (): NormalizedConfig; /** Get the normalized config for a specific environment */ (options: { environment: string }): NormalizedEnvironmentConfig; }; * **Example:** rsbuild.onBeforeBuild(() => { const config = rsbuild.getNormalizedConfig(); console.log(config.html.title); }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildexpose) rsbuild.expose -------------------------------------------------------------------------------- > Provides the same functionality as the [expose](https://rsbuild.rs/plugins/dev/core#apiexpose) > plugin API. * **Version:** Added in v1.5.0 * **Example:** rsbuild.expose('my-id', { value: 1, double: (val: number) => val * 2, }); You can also expose an API for a specific Rsbuild environment (the key of `config.environments`): rsbuild.expose( 'my-id', { value: 1, double: (val: number) => val * 2, }, { environment: 'web', }, ); When a plugin registered in the same environment calls `api.useExposed`, Rsbuild will first resolve the environment-scoped API, then fall back to the global API. [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildmodifyrsbuildconfig) rsbuild.modifyRsbuildConfig ---------------------------------------------------------------------------------------------------------- > Provides the same functionality as the [modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) > plugin API. * **Version:** Added in v1.5.0 * **Example:** rsbuild.modifyRsbuildConfig((config) => { config.html ||= {}; config.html.title = 'My Default Title'; }); [#](https://rsbuild.rs/api/javascript-api/instance#rsbuildmodifyenvironmentconfig) rsbuild.modifyEnvironmentConfig ------------------------------------------------------------------------------------------------------------------ > Provides the same functionality as the [modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) > plugin API. * **Version:** Added in v1.5.0 * **Example:** rsbuild.modifyEnvironmentConfig((config, { name }) => { if (name !== 'web') { return config; } config.html.title = 'My Default Title'; }); --- # Rsbuild blogs - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/index.md. ON THIS PAGE Rsbuild blogs[#](https://rsbuild.rs/blog/#rsbuild-blogs) ========================================================= Copy Markdown This page collects blog posts about Rsbuild. Minor Rsbuild releases are also usually covered on the [Rspack blog](https://rspack.rs/blog/) . [June 26, 2026\ \ Announcing Rsbuild 2.1\ \ Rsbuild 2.1 is out, featuring the Rust-based React Compiler, TanStack Start support, a Tailwind CSS v4 plugin, and support for CSS URL imports and Worker query imports.\ \ ![](https://github.com/chenjiahan.png)\ \ Jiahan Chen](https://rsbuild.rs/blog/v2-1) [April 22, 2026\ \ Announcing Rsbuild 2.0\ \ Rsbuild 2.0 is out, featuring Rspack 2.0, RSC support, and more modern defaults.\ \ ![](https://github.com/chenjiahan.png)\ \ Jiahan Chen](https://rsbuild.rs/blog/v2-0) [September 10, 2024\ \ Announcing Rsbuild 1.0\ \ Rsbuild 1.0 officially launches with faster builds, simpler configuration, a growing plugin ecosystem, and broader adoption across Rstack.\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/blog/v1-0) [May 28, 2024\ \ Announcing Rsbuild 0.7\ \ Rsbuild 0.7 adds Storybook support, faster Sass compilation, and typed CSS Modules.\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/blog/v0-7) [April 10, 2024\ \ Announcing Rsbuild 0.6\ \ Rsbuild 0.6 enables the error overlay by default, adds Vue JSX HMR, and introduces a new transform API.\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/blog/v0-6) [March 19, 2024\ \ Announcing Rsbuild 0.5\ \ Rsbuild 0.5 adds Lightning CSS, custom server support, and more flexible minify options.\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/blog/v0-5) [February 6, 2024\ \ Announcing Rsbuild 0.4\ \ Rsbuild 0.4 adds built-in Module Federation config and updates plugin hook ordering and default behavior.\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/blog/v0-4) [January 10, 2024\ \ Announcing Rsbuild 0.3\ \ Rsbuild 0.3 adds Module Federation support and updates TOML/YAML plugins, the JavaScript API, and Node target behavior.\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/blog/v0-3) [December 11, 2023\ \ Announcing Rsbuild 0.2\ \ Rsbuild 0.2 updates core configuration such as targets and entry, and redesigns the Babel plugin API.\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/blog/v0-2) [November 22, 2023\ \ Announcing Rsbuild 0.1\ \ Rsbuild 0.1 introduces an Rspack-based build tool with faster builds, simpler configuration, and multi-framework support.\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/blog/v0-1) --- # Announcing Rsbuild 0.2 - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/v0-2.md. ON THIS PAGE [Back to blog](https://rsbuild.rs/blog/) [#](https://rsbuild.rs/blog/v0-2#announcing-rsbuild-02) Announcing Rsbuild 0.2 ============================================================================== Copy Markdown _December 11, 2023_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-2.png) The Rsbuild 0.2 contains some incompatible API changes. Please refer to the current documentation for upgrading. [#](https://rsbuild.rs/blog/v0-2#targets) Targets ------------------------------------------------- We will move the `target` option of `createRsbuild` to rsbuild config, this change allows user to configure `targets` in the rsbuild config file. * before: const rsbuild = await createRsbuild({ target: ['web', 'node'], }); * after: // rsbuild.config.ts export default { output: { targets: ['web', 'node'], }, }; > Only affect JavaScript API. Users using the Rsbuild CLI do not need to change. [#](https://rsbuild.rs/blog/v0-2#entry) Entry --------------------------------------------- Remove the deprecated `source.entries` config. `source.entries` has been renamed to `source.entry` since Rsbuild 0.1.0, and we will remove the legacy `source.entries` config in Rsbuild v0.2.0. * before: // rsbuild.config.ts export default { source: { entries: {}, }, }; * after: // rsbuild.config.ts export default { source: { entry: {}, }, }; [#](https://rsbuild.rs/blog/v0-2#write-to-disk) Write to disk ------------------------------------------------------------- `dev.writeToDisk` defaults to `false`. Motivation: * Reduce fs overhead and improve dev server performance. * Avoid trigger watcher of UnoCSS and other tools. See [#654](https://github.com/web-infra-dev/rsbuild/issues/654) . * Align the default behavior with webpack-dev-middleware and other community dev servers. User can enable writeToDisk manually: export default { dev: { writeToDisk: true, }, }; [#](https://rsbuild.rs/blog/v0-2#babel-plugin) Babel plugin ----------------------------------------------------------- `@rsbuild/plugin-babel` will move all babel-loader options to `babelLoaderOptions`: * before: pluginBabel({ plugins: [], presets: [], }); * after: pluginBabel([\ babelLoaderOptions: {\ plugins: [],\ presets: [],\ }\ ]); This change allows us to add more options for `pluginBabel`, such as `include` and `exclude`. [#](https://rsbuild.rs/blog/v0-2#source-map) Source map ------------------------------------------------------- `output.disableSourceMap` has been renamed to `output.sourceMap`. * before: export default { output: { disableSourceMap: { js: true, css: true, }, }, }; * after: export default { output: { sourceMap: { js: false, css: false, }, }, }; The default value of source map has also been updated to improve build performance. * before: generate JS / CSS source map in development, generate JS source map in production. * after: generate JS source map in development, no source map are generated in production. [#](https://rsbuild.rs/blog/v0-2#inject-styles) Inject styles ------------------------------------------------------------- Rename `output.disableCssExtract` to `output.injectStyles` to be clearer: * before: export default { output: { disableCssExtract: true, }, }; * after: export default { output: { injectStyles: true, }, }; --- # Announcing Rsbuild 0.3 - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/v0-3.md. ON THIS PAGE [Back to blog](https://rsbuild.rs/blog/) [#](https://rsbuild.rs/blog/v0-3#announcing-rsbuild-03) Announcing Rsbuild 0.3 ============================================================================== Copy Markdown _January 10, 2024_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-3.png) Rsbuild 0.3 version has upgraded Rspack to 0.5 and now supports Module Federation. In addition, it includes some incompatible API changes. Please refer to the current documentation for upgrading. [#](https://rsbuild.rs/blog/v0-3#rspack-05) Rspack 0.5 ------------------------------------------------------ Bump Rspack to v0.5.0, see: [Rspack 0.5 Release Announcement](https://rspack.rs/blog/announcing-0-5) Notable changes: * [Module Federation added to Rspack](https://rspack.rs/blog/module-federation-added-to-rspack) * [Remove deprecated builtins options](https://rspack.rs/blog/announcing-0-5#make-swchelpers-and-react-refresh-as-peerdependencies) [#](https://rsbuild.rs/blog/v0-3#toml--yaml-plugin) TOML / YAML plugin ---------------------------------------------------------------------- The need to import TOML and YAML in JS is not common, so Rsbuild core will no longer support import TOML and YAML by default in v0.3.0. The TOML and YAML plugin will become an independent plugin: * TOML: // rsbuild.config.ts import { pluginToml } from '@rsbuild/plugin-toml'; export default { plugins: [pluginToml()], }; * YAML: // rsbuild.config.ts import { pluginYaml } from '@rsbuild/plugin-yaml'; export default { plugins: [pluginYaml()], }; [#](https://rsbuild.rs/blog/v0-3#javascript-api) JavaScript API --------------------------------------------------------------- Some JavaScript APIs have changed: * The `printURLs` option of `rsbuild.startDevServer` is deprecated, use [server.printUrls](https://rsbuild.rs/config/server/print-urls) instead. * The `logger` option of `rsbuild.startDevServer` is deprecated, use [logger.override()](https://rsbuild.rs/api/javascript-api/core#logger) instead. [#](https://rsbuild.rs/blog/v0-3#node-target) Node target --------------------------------------------------------- * Adjust default browserslist for node target, from `node >= 14` to `node >= 16`. * The default value of `output.distPath.server` is changed from `'bundles'` to `'server'` --- # Announcing Rsbuild 0.4 - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/v0-4.md. ON THIS PAGE [Back to blog](https://rsbuild.rs/blog/) [#](https://rsbuild.rs/blog/v0-4#announcing-rsbuild-04) Announcing Rsbuild 0.4 ============================================================================== Copy Markdown _February 6, 2024_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-4.png) Rsbuild 0.4 provides built-in support for module federation. It also contains some incompatible API updates. Please refer to the current document for upgrading. ### [#](https://rsbuild.rs/blog/v0-4#module-federation-config) Module Federation config Rsbuild now provides a built-in [moduleFederation](https://rsbuild.rs/config/module-federation/options) option, which will make configuring Module Federation in Rsbuild much easier. * **Example:** rsbuild.config.ts export default defineConfig({ moduleFederation: { options: { // ModuleFederationPluginOptions }, }, }); When you use this option, Rsbuild will automatically set the default `publicPath` and `splitChunks` config, making module federation ready to use out of the box. > See [RFC - Provide first-class support for Module Federation](https://github.com/web-infra-dev/rsbuild/discussions/1461) > for details. ### [#](https://rsbuild.rs/blog/v0-4#plugin-hook-order) Plugin hook order In Rsbuild plugin, you can now declare the order of hooks using the `order` field: const myPlugin = () => ({ setup(api) { api.modifyRsbuildConfig({ handler: () => console.log('hello'), order: 'pre', }); }, }); > For more details, see [Plugin hooks](https://rsbuild.rs/plugins/dev/hooks) > . ### [#](https://rsbuild.rs/blog/v0-4#rename-disablefilenamehash) Rename disableFilenameHash The `output.disableFilenameHash` config has been renamed to [output.filenameHash](https://rsbuild.rs/config/output/filename-hash) . * Before: export default { output: { disableFilenameHash: true, }, }; * After: export default { output: { filenameHash: false, }, }; [#](https://rsbuild.rs/blog/v0-4#remove-postcss-flexbugs-fixes) Remove postcss-flexbugs-fixes --------------------------------------------------------------------------------------------- Rsbuild 0.4 removed the built-in [postcss-flexbugs-fixes](https://github.com/luisrudge/postcss-flexbugs-fixes) plugin. This plugin is used to fix some flex bugs for IE 10 / 11. Considering that modern browsers no longer have these flex issues, we removed this plugin to improve build performance. If your project needs to be compatible with IE 10 / 11 and encounters these flex issues, you can manually add this plugin in Rsbuild: * Install plugin: npm add postcss-flexbugs-fixes -D * Register plugin in `postcss.config.cjs`: module.exports = { 'postcss-flexbugs-fixes': {}, }; [#](https://rsbuild.rs/blog/v0-4#pure-react-plugin) Pure React plugin --------------------------------------------------------------------- The React plugin has removed default [source.transformImport](https://rsbuild.rs/config/source/transform-import) config for [antd](https://npmjs.com/package/antd) v4 and [@arco-design/web-react](https://npmjs.com/package/@arco-design/web-react) . Configurations related to the UI library should be provided in the UI library-specific plugins, such as `rsbuild-plugin-antd` or `rsbuild-plugin-arco`, and the React plugin will concentrate on providing fundamental abilities for React. * If your project is using `antd` v3 or v4, you can manually add the following config: rsbuild.config.ts export default { source: { transformImport: [\ {\ libraryName: 'antd',\ libraryDirectory: 'es',\ style: 'css',\ },\ ], }, }; * If your project is using `@arco-design/web-react`, you can manually add the following config: rsbuild.config.ts export default { source: { transformImport: [\ {\ libraryName: '@arco-design/web-react',\ libraryDirectory: 'es',\ camelToDashComponentName: false,\ style: 'css',\ },\ {\ libraryName: '@arco-design/web-react/icon',\ libraryDirectory: 'react-icon',\ camelToDashComponentName: false,\ },\ ], }, }; [#](https://rsbuild.rs/blog/v0-4#javascript-api) JavaScript API --------------------------------------------------------------- The `loadConfig` method now returns both the contents of the config and the path to the config file: import { loadConfig } from '@rsbuild/core'; // 0.3 const config = await loadConfig(); // 0.4 const { content, filePath } = await loadConfig(); --- # Announcing Rsbuild 0.5 - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/v0-5.md. ON THIS PAGE [Back to blog](https://rsbuild.rs/blog/) [#](https://rsbuild.rs/blog/v0-5#announcing-rsbuild-05) Announcing Rsbuild 0.5 ============================================================================== Copy Markdown _March 19, 2024_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-5.png) Rsbuild 0.5 is an important milestone. As of this release, most of the Rsbuild API has reached a stable state and we expect to release Rsbuild 1.0 in Q3 2024. Main changes: * ⚡️ Support for [Lightning CSS](https://lightningcss.dev/) to speed up CSS compilation. * 🌟 Support for custom server based on the new JavaScript API. * 🍭 Refactor the SVGR plugin to support more usages. * 📍 Support for custom minify options. [#](https://rsbuild.rs/blog/v0-5#%EF%B8%8F-supports-lightning-css) ⚡️ Supports Lightning CSS -------------------------------------------------------------------------------------------- Lightning CSS is a high performance CSS parser, transformer and minifier written in Rust. It supports parsing and transforming many modern CSS features into syntax supported by target browsers, and also provides a better compression ratio. Rsbuild provides the Lightning CSS plugin to use Lightning CSS on an opt-in basis, replacing the built-in PostCSS, autoprefixer, and SWC CSS minimizer in Rsbuild. All you need to do is register the Lightning CSS plugin in the Rsbuild configuration to complete the switch: rsbuild.config.ts import { pluginLightningcss } from '@rsbuild/plugin-lightningcss'; export default { plugins: [pluginLightningcss()], }; In a real large-scale web application, we have integrated the Rsbuild Lightning CSS plugin and used [Rsdoctor](https://rsdoctor.rs/) to analyze the changes in build time: * CSS compilation time was reduced from 8.4s to 0.12s, a 70x improvement. * The overall build time was reduced from 33.1s to 25.4s, a 30% increase. [#](https://rsbuild.rs/blog/v0-5#-support-for-custom-server) 🌟 Support for custom server ----------------------------------------------------------------------------------------- Rsbuild now supports replacing the dev server with a custom server that reuses Rsbuild's page preview, routing, and module hot update features. This makes it easier to integrate Rsbuild with other Node.js frameworks. For example, you can implement a custom server based on express: import express from 'express'; import { createRsbuild } from '@rsbuild/core'; async function startCustomServer() { const app = express(); const rsbuild = await createRsbuild({ config: { server: { middlewareMode: true, }, }, }); const { port, middlewares } = await rsbuild.createDevServer(); app.use(middlewares); app.listen(port); } For more details, please refer to [Rsbuild - createDevServer](https://rsbuild.rs/api/javascript-api/instance#rsbuildcreatedevserver) . [#](https://rsbuild.rs/blog/v0-5#-refactoring-svgr-plugin) 🍭 Refactoring SVGR plugin ------------------------------------------------------------------------------------- In versions prior to 0.5.0, the default usage of the SVGR plugin was the same as create-react-app, allowing SVGs to be used via mixed import: import logoUrl, { ReactComponent as Logo } from './logo.svg'; console.log(logoUrl); // -> string console.log(Logo); // -> React component However, there are two problems with this approach: 1. **Increased bundle size**: Mixed import causes a single SVG module to be compiled into two types of code (even if some exports are not used), which will increase the bundle size. 2. **Slow down compiling**: Mixed import will cause extra compilation overhead. Even if the ReactComponent export is not used in the code, the SVG file will still be compiled by SVGR. And SVGR is based on Babel, which has a high performance overhead. So we have refactored the `@rsbuild/plugin-svgr` plugin to support converting SVGs to React components via the `?react` query. This approach can solve the problems mentioned above, and is more in line with community best practices. import logoUrl from './logo.svg'; import Logo from './logo.svg?react'; console.log(logoUrl); // -> string console.log(Logo); // -> React component The SVGR plugin now supports switching between different SVGR usages. If a project needs to use the previous mixed import usage, you can manually enable the [mixedImport](https://rsbuild.rs/plugins/list/plugin-svgr#mixedimport) option: pluginSvgr({ mixedImport: true, }); [#](https://rsbuild.rs/blog/v0-5#-custom-minify-options) 📍 Custom minify options --------------------------------------------------------------------------------- The `output.disableMinimize` option has been renamed to [output.minify](https://rsbuild.rs/config/output/minify) , and it allows customizing JS and HTML minification options. rsbuild.config.ts export default { output: { minify: { jsOptions: { minimizerOptions: { mangle: false, }, }, }, }, }; Projects using `output.disableMinimize` can refer to the example below: export default { output: { disableMinimize: true, minify: false, }, }; > See ["allow customize minify options"](https://github.com/web-infra-dev/rsbuild/issues/1681) > . * * * For more information, please refer to: * [Rsbuild 0.5.0 Changelog](https://github.com/web-infra-dev/rsbuild/releases/tag/v0.5.0) * [Rsbuild 0.5.0 Breaking Changes](https://github.com/web-infra-dev/rsbuild/discussions/1732) --- # Announcing Rsbuild 0.6 - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/v0-6.md. ON THIS PAGE [Back to blog](https://rsbuild.rs/blog/) [#](https://rsbuild.rs/blog/v0-6#announcing-rsbuild-06) Announcing Rsbuild 0.6 ============================================================================== Copy Markdown _April 10, 2024_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-6.png) Rsbuild 0.6 has been released along with Rspack 0.6! Notable changes: * Upgrade to Rspack 0.6 * Error overlay enabled by default * Support for Vue JSX HMR * New transform plugin API * Default port changed to 3000 [#](https://rsbuild.rs/blog/v0-6#upgrade-to-rspack-06) Upgrade to Rspack 0.6 ---------------------------------------------------------------------------- Rsbuild has upgraded the dependent Rspack to version 0.6, and adapted the breaking changes of CSS Modules contained in Rspack 0.6. In the new version, Rspack has enabled the new tree shaking algorithm by default, resulting in a significant improvement in bundle size and artifact stability. Please refer to the [Rspack 0.6 release announcement](https://rspack.rs/blog/announcing-0-6) to learn more. [#](https://rsbuild.rs/blog/v0-6#error-overlay-enabled-by-default) Error overlay enabled by default --------------------------------------------------------------------------------------------------- Starting from Rsbuild 0.6, the default value of [dev.client.overlay](https://rsbuild.rs/config/dev/client) has been adjusted to `true`. This means that when a compilation error occurs, Rsbuild will pop up the error overlay by default to display the error information: ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-error-overlay.png) If you do not need this feature, you can set `dev.client.overlay` to `false` to disable it. rsbuild.config.ts export default defineConfig({ dev: { client: { overlay: false, }, }, }); [#](https://rsbuild.rs/blog/v0-6#support-for-vue-jsx-hmr) Support for Vue JSX HMR --------------------------------------------------------------------------------- `@rsbuild/plugin-vue-jsx` now supports JSX HMR. When you modify JSX code in a Vue 3 application, it will automatically trigger hot module replacement and preserve the current page state. This feature is implemented by community contributor [@liyincode](https://github.com/liyincode) ❤️, and released as a standalone package [babel-plugin-vue-jsx-hmr](https://github.com/liyincode/babel-plugin-vue-jsx-hmr) , for use in projects outside of Rsbuild. [#](https://rsbuild.rs/blog/v0-6#new-transform-api) New transform API --------------------------------------------------------------------- Rsbuild plugin now supports the [transform API](https://rsbuild.rs/plugins/dev/core#apitransform) , which 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. 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;`; }); }, }); For some complex code transformation scenarios, `api.transform` may not be sufficient. In such situations, you can implement it using the Rspack loader. [#](https://rsbuild.rs/blog/v0-6#default-port-changed-to-3000) Default port changed to 3000 ------------------------------------------------------------------------------------------- Rsbuild has changed the default value of [server.port](https://rsbuild.rs/config/server/port) from `8080` to `3000`. Port 3000 is commonly used for web development, and is also the default port used by tools such as create-react-app. Changing the default port to 3000 can prevent possible port conflicts when using 8080. To use port 8080, set it manually as follows: rsbuild.config.ts export default defineConfig({ server: { port: 8080, }, }); --- # Announcing Rsbuild 1.0 - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/v1-0.md. ON THIS PAGE [Back to blog](https://rsbuild.rs/blog/) [#](https://rsbuild.rs/blog/v1-0#announcing-rsbuild-10) Announcing Rsbuild 1.0 ============================================================================== Copy Markdown _September 10, 2024_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-1-0-banner.png) We are pleased to announce the release of Rsbuild 1.0! [#](https://rsbuild.rs/blog/v1-0#why-rsbuild) Why Rsbuild --------------------------------------------------------- For a long time, developers using webpack have been bothered by two major issues: **slow build times and configuration complexity**. We have used Rust to rewrite webpack into [Rspack](https://github.com/web-infra-dev/rspack) , which addresses the slow build issue. However, to maintain compatibility with the webpack ecosystem, Rspack retains webpack's configuration and API, which means it still has some complexity and a learning curve. ### [#](https://rsbuild.rs/blog/v1-0#evolution-of-the-ecosystem) Evolution of the ecosystem In the early days, there were some excellent tools within the webpack ecosystem, such as Create React App (CRA) and Vue CLI. These tools provided best practices for building React or Vue applications, while hiding the complex webpack configuration. As a result, many React and Vue users used these tools to build applications without having to configure webpack from scratch. As the ecosystem evolved, full-stack web frameworks such as Next.js, Nuxt, and Remix became popular; Vite was introduced as a lightweight build tool and also gained popularity. However, CRA and Vue CLI gradually stopped being maintained. When we look at the npm download numbers for webpack, CRA, and Vue CLI, we find that a large number of projects are still using these tools. For example, webpack has about 25 million weekly downloads, and CRA has nearly 3 million weekly downloads. Many of these projects are CSR applications that do not require the SSR features of full-stack frameworks. Vite seems like a good choice, but after using Vite in our ByteDance projects, we found that migrating from webpack to Vite comes with high costs and introduces new problems, such as dev and build inconsistency, and slow page refreshes in large applications during development. For the webpack ecosystem, we discovered a sad fact: **the webpack ecosystem lacks a build tool that is easy to use and well maintained**. The tool should be as user-friendly as CRA and Vue CLI, fully meet the needs of CSR application development, and have features such as fast startup and plugin support similar to Vite. ### [#](https://rsbuild.rs/blog/v1-0#the-birth-of-rsbuild) The birth of Rsbuild During the development of Rspack, we became aware of the above problems and decided to create a modern build tool based on Rspack called **Rsbuild**. ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-1-0-build-tools.png) Rsbuild is built on top of Rspack. We designed Rsbuild with an easy-to-use, TypeScript-friendly API and a set of carefully designed configurations to fully leverage the Rspack's build performance while reducing configuration complexity and high up-front costs. When developing Rsbuild, we learned best practices from the best tools in the community and focused on two usage scenarios: * As a lightweight build tool: Helps developers quickly set up web applications with out-of-the-box support for CSR applications. * As a shared infrastructure: Provides [JavaScript API](https://rsbuild.rs/api/start/) and [Plugin API](https://rsbuild.rs/plugins/dev/) for higher-level tools and frameworks, allowing developers to easily build their tools or frameworks on top of Rsbuild. [#](https://rsbuild.rs/blog/v1-0#performance) Performance --------------------------------------------------------- **Rsbuild is currently the fastest build tool in the webpack and Rspack ecosystem**. Here is a comparison between Rsbuild, Create React App, Vite, and Rspack CLI: | Metric | Create React App | Vite (with SWC) | Rspack CLI | Rsbuild | Rsbuild vs CRA | | --- | --- | --- | --- | --- | --- | | dev startup time (1000 modules) | 5.47s | 1.29s | 0.66s | 0.39s | **14x faster** | | build time (1000 modules) | 5.69s | 1.39s | 0.51s | 0.27s | **20x faster** | | npm dependencies count | 1241 | 15 | 283 | 14 | **99% reduction** | | npm install size | 146.6MB | 56.3MB | 75.1MB | 59.1MB | **60% reduction** | Compared to the [Rspack CLI](https://npmjs.com/package/@rspack/cli) , Rsbuild provides a richer set of features while demonstrating superior performance. This is because Rspack CLI needs to maintain compatibility with the [webpack-cli](https://npmjs.com/package/webpack-cli) . It relies on the `webpack-dev-server` and provides the same default behavior as webpack, which has some performance limitations. Rsbuild, on the other hand, is designed for modern web development. We have reimplemented a lighter CLI, dev server, and build process for Rsbuild, resulting in faster startup speeds and fewer npm dependencies. > See the [Introduction](https://rsbuild.rs/guide/start/) > for more comparisons between Rsbuild, webpack, Vue CLI, and Vite. [#](https://rsbuild.rs/blog/v1-0#who-is-using) Who is using ----------------------------------------------------------- In the [Rspack 1.0 Announcement](https://rspack.rs/blog/announcing-1-0) , we introduced that Rspack is growing rapidly, with almost half of Rspack users using Rsbuild and giving us lots of positive feedback. At ByteDance, we use Rsbuild as the cornerstone of our internal web frameworks to support thousands of web projects. These projects cover diverse use cases, including desktop web applications, mobile web applications, cross-platform web applications, documentation sites, and more. For the community, we have open-sourced a high-performance toolchain based on Rsbuild, including the static site generator [Rspress](https://github.com/web-infra-dev/rspress) , the library development tool [Rslib](https://github.com/web-infra-dev/rslib) , the full-stack React framework [Modern.js](https://github.com/web-infra-dev/modern.js) , and the [Storybook Rsbuild](https://github.com/rstackjs/storybook-rsbuild) . The extensibility of Rsbuild allows these tools to flexibly integrate with Rsbuild and share its plugin ecosystem. After releasing Rsbuild 1.0, we also plan to collaborate with some excellent teams like [Remix](https://github.com/remix-run/remix) , to bring Rsbuild to more web frameworks. [#](https://rsbuild.rs/blog/v1-0#plugin-ecosystem) Plugin ecosystem ------------------------------------------------------------------- The Rsbuild plugin ecosystem is constantly evolving. There are currently over 50 [Rsbuild plugins](https://github.com/rstackjs/awesome-rstack#rsbuild-plugins) available in the community. We provide several advanced features through plugins to support the development of production-grade applications, such as [type checking](https://github.com/rstackjs/rsbuild-plugin-type-check) , [compatibility checking](https://github.com/rstackjs/rsbuild-plugin-check-syntax) , and [static assets retry](https://github.com/rstackjs/rsbuild-plugin-assets-retry) . Thanks to Rspack's compatibility with webpack, Rsbuild also supports most webpack plugins. Compared to webpack or Rspack, the Rsbuild plugin API is more straightforward and beginner-friendly, allowing developers to easily create plugins to meet their specific needs. For example, let us implement a plugin that outputs a file to the dist directory. The implementation comparison between Rspack and Rsbuild is as follows: ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-1-0-plugin-compare.png) As shown, the API style of the Rsbuild plugin is similar to esbuild, it can be defined by a function. The plugin hooks have been simplified to avoid verbose APIs, making plugin development more intuitive. [#](https://rsbuild.rs/blog/v1-0#how-to-use-10) How to use 1.0 -------------------------------------------------------------- * If you haven't used Rsbuild before, refer to the [Quick start](https://rsbuild.rs/guide/start/quick-start) to get started. * If you are using Rsbuild 0.7 or earlier, please note that 1.0 includes some breaking changes. You can refer to the [Upgrading from 0.x to v1](https://rsbuild.rs/guide/upgrade/v0-to-v1) document to upgrade. * Rsbuild also provides migration guides for projects that use webpack, CRA, Vue CLI, etc. See [Migrate from Existing Projects](https://rsbuild.rs/guide/start/quick-start#migrate-from-existing-projects) . > Give a star 🌟 to the [Rsbuild GitHub repository](https://github.com/web-infra-dev/rsbuild) > . [#](https://rsbuild.rs/blog/v1-0#whats-next) What's next -------------------------------------------------------- Rsbuild 1.0 provides several advanced features for the development of enterprise applications and higher-level tools, such as the [multi-environment build API](https://rsbuild.rs/guide/advanced/environments) , [SSR API](https://rsbuild.rs/guide/advanced/ssr) , [plugin API](https://rsbuild.rs/plugins/dev/) , [Module Federation support](https://rsbuild.rs/guide/advanced/module-federation) , and [library build (Rslib)](https://github.com/web-infra-dev/rslib) . We plan to continue to enhance these features to better support the development of the Rsbuild ecosystem. In the next 12 to 18 months, Rsbuild will evolve together with Rspack, adopting Rspack's new features as soon as they become available. These features include persistent caching, faster HMR, and TypeScript-based optimizations. For more details, see [Rspack - What's next](https://rspack.rs/blog/announcing-1-0#whats-next) . Finally, a big thank you to all the developers who have contributed to Rsbuild ❤️: ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-1-0-contributors.png) --- # Announcing Rsbuild 0.7 - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/v0-7.md. ON THIS PAGE [Back to blog](https://rsbuild.rs/blog/) [#](https://rsbuild.rs/blog/v0-7#announcing-rsbuild-07) Announcing Rsbuild 0.7 ============================================================================== Copy Markdown _May 28, 2024_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-7.png) Rsbuild 0.7 has been released with Rspack 0.7! This is the last minor release before the Rsbuild 1.0. After this, the Rspack team will focus on the development of 1.0 and aim to launch the Rspack / Rsbuild 1.0 alpha version soon. Notable changes in Rsbuild 0.7: * [Support for Storybook](https://rsbuild.rs/blog/v0-7#support-for-storybook) * [Faster Sass Compilation](https://rsbuild.rs/blog/v0-7#faster-sass-compilation) * [Better CSS supports](https://rsbuild.rs/blog/v0-7#better-css-supports) * [Typed CSS Modules](https://rsbuild.rs/blog/v0-7#typed-css-modules) * [ESM/CJS Exports](https://rsbuild.rs/blog/v0-7#esmcjs-exports) * [Breaking Changes](https://rsbuild.rs/blog/v0-7#breaking-changes) [#](https://rsbuild.rs/blog/v0-7#support-for-storybook) Support for Storybook ----------------------------------------------------------------------------- Rsbuild now supports Storybook! [storybook-builder-rsbuild](https://github.com/rstackjs/storybook-rsbuild) is a Storybook builder based on Storybook v8 and Rsbuild that allows you to quickly build your components and stories. ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-with-storybook.png) * For projects using Rsbuild, you can now quickly integrate Storybook and reuse your existing Rsbuild config. * For projects using the Storybook webpack builder, you can now upgrade to Rsbuild and **get ~5x faster build performance**. We provide `storybook-react-rsbuild` and `storybook-vue3-rsbuild` to support React and Vue 3. For example, to integrate React: .storybook/main.js import { StorybookConfig } from 'storybook-react-rsbuild'; const config: StorybookConfig = { framework: 'storybook-react-rsbuild', }; export default config; ![](https://assets.rspack.rs/rsbuild/assets/storybook-rsbuild-preview.png) > For more usage, please refer to [storybook-rsbuild repository](https://github.com/rstackjs/storybook-rsbuild) > . [#](https://rsbuild.rs/blog/v0-7#faster-sass-compilation) Faster Sass compilation --------------------------------------------------------------------------------- In Rsbuild 0.7, **Sass compilation is 3~10 times faster**. The performance improvements are particularly noticeable on large projects. Comparison of build times for Rsbuild 0.6 and 0.7 when compiling Bootstrap's Sass code: ![](https://assets.rspack.rs/rsbuild/assets/sass-embedded-compare.jpeg) This improvement is due to Rsbuild's default use of [sass-embedded](https://npmjs.com/package/sass-embedded) , a JavaScript wrapper around the native Dart Sass executable that provides a consistent API and superior performance. Rsbuild has also enabled the latest sass-loader's [modern-compiler](https://github.com/webpack/sass-loader/releases/tag/v14.2.0) API. This can enable Sass's shared resources feature, which allows the same compiler process to be reused when compiling multiple files, improving build performance. [#](https://rsbuild.rs/blog/v0-7#better-css-supports) Better CSS supports ------------------------------------------------------------------------- Rsbuild now uses [CssExtractRspackPlugin](https://rspack.rs/plugins/rspack/css-extract-rspack-plugin) to extract CSS into separate files, rather than using the [experimental.css](https://v0.rspack.rs/config/experiments#experimentscss) config to do so. This allows Rsbuild to support more CSS features, including: * Support for using ` * Support for complex CSS Modules `:global()` syntax style.module.css :local(.parent):global(.child) > ul { color: red; } * Support for more CSS Modules options, such as [cssModules.exportGlobals](https://rsbuild.rs/config/output/css-modules#cssmodulesexportglobals) * Now you can use [tools.cssExtract](https://rsbuild.rs/config/tools/css-extract) to configure CssExtractRspackPlugin. [#](https://rsbuild.rs/blog/v0-7#typed-css-modules) Typed CSS Modules --------------------------------------------------------------------- Rsbuild 0.7 added a new [Typed CSS Modules plugin](https://github.com/rstackjs/rsbuild-plugin-typed-css-modules) , which is used to generate type declaration files for CSS Modules in the project. When you use CSS Modules in a TypeScript project, the default type definition is as follows. It can only provide basic type support, and cannot accurately prompt which class names are exported by CSS Modules. src/env.d.ts declare module '*.module.css' { const classes: { readonly [key: string]: string }; export default classes; } After using the Typed CSS Modules plugin, Rsbuild will generate type declaration files for all CSS Modules in the project, providing accurate type hints. For example, create two files named `src/index.ts` and `src/index.module.css`: src/index.ts import styles from './index.module.css'; console.log(styles.pageHeader); index.module.css .page-header { color: black; } After building, Rsbuild will generate a `src/index.module.css.d.ts` type declaration file: src/index.module.css.d.ts interface CssExports { 'page-header': string; pageHeader: string; } declare const cssExports: CssExports; export default cssExports; Now when you open the `src/index.ts` file, you can see that the `styles` object already has an accurate type. [#](https://rsbuild.rs/blog/v0-7#esmcjs-exports) ESM/CJS Exports ---------------------------------------------------------------- Now, all packages of Rsbuild provide exports in both ES modules and CommonJS formats, and ["type"="module"](https://nodejs.org/api/packages.html#type) has been declared in the package.json. ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-dual-package-example.png) This allows you to use `import` or `require` to use the JavaScript API of Rsbuild: // ES module import { createRsbuild } from '@rsbuild/core'; // CommonJS const { createRsbuild } = require('@rsbuild/core'); ESM/CJS interop is a tricky issue, so we will provide both formats for a long time to make it easier for more users to use. [#](https://rsbuild.rs/blog/v0-7#breaking-changes) Breaking changes ------------------------------------------------------------------- ### [#](https://rsbuild.rs/blog/v0-7#upgrade-rspack-to-07) Upgrade Rspack to 0.7 Rsbuild has upgraded the dependent Rspack to version 0.7 and adapted to the breaking changes included in it. Typically, these breaking changes will not affect you. In the new version, Rspack supports lazy compilation, which can significantly improve the dev startup time for large projects. Please refer to [Announcing Rspack 0.7](https://rspack.rs/blog/announcing-0-7) to learn more. In Rsbuild, you can use [dev.lazyCompilation](https://rsbuild.rs/config/dev/lazy-compilation) to enable lazy compilation. ### [#](https://rsbuild.rs/blog/v0-7#sass-and-less-plugins) Sass and Less plugins Rsbuild's Sass and Less plugins are now two separate npm packages instead of being built into `@rsbuild/core` as before. This change allows users to enable Sass and Less compilation as needed. For example, projects using CSS solutions such as Tailwind CSS, CSS-in-JS, etc., no longer need to install the dependencies required for Sass and Less, **saving about 7MB of disk space**. * If your project requires compiling `.scss` or `.sass` files, please install and register the [@rsbuild/plugin-sass](https://rsbuild.rs/plugins/list/plugin-sass) plugin: rsbuild.config.ts import { pluginSass } from '@rsbuild/plugin-sass'; export default { plugins: [pluginSass()], }; * If your project requires compiling `.less` files, please install and register the [@rsbuild/plugin-less](https://rsbuild.rs/plugins/list/plugin-less) plugin: rsbuild.config.ts import { pluginLess } from '@rsbuild/plugin-less'; export default { plugins: [pluginLess()], }; ### [#](https://rsbuild.rs/blog/v0-7#dataurilimit-defaults) dataUriLimit defaults The default value for [output.dataUriLimit](https://rsbuild.rs/config/output/data-uri-limit) has been changed from `10000 (10 kB)` to `4096 (4 KiB)`. This is because more applications are currently using HTTP 2.0, so splitting assets into separate files would perform better. Meanwhile, inlining assets over 4KiB can make the JS bundle to be too large and not cache friendly. If you prefer the previous defaults, add the following config: rsbuild.config.ts export default { output: { dataUriLimit: 10000, }, }; --- # Announcing Rsbuild 2.1 - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/v2-1.md. ON THIS PAGE [Back to blog](https://rsbuild.rs/blog/) [#](https://rsbuild.rs/blog/v2-1#announcing-rsbuild-21) Announcing Rsbuild 2.1 ============================================================================== Copy Markdown _June 26, 2026_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan We are pleased to announce the official release of Rsbuild 2.1! The main improvements in 2.1 include: * Framework and ecosystem: * [Upgrade to Rspack 2.1](https://rsbuild.rs/blog/v2-1#upgrade-to-rspack-21) * [Rust-based React Compiler](https://rsbuild.rs/blog/v2-1#rust-react-compiler) * [TanStack Start support](https://rsbuild.rs/blog/v2-1#tanstack-start-support) * [Tailwind CSS plugin](https://rsbuild.rs/blog/v2-1#tailwind-css-plugin) * New features: * [Automatic externals](https://rsbuild.rs/blog/v2-1#auto-external) * [Parallel Babel and SVGR](https://rsbuild.rs/blog/v2-1#parallel-babel-and-svgr) * Resource imports: * [CSS URL imports](https://rsbuild.rs/blog/v2-1#css-url-imports) * [Worker query imports](https://rsbuild.rs/blog/v2-1#worker-query-imports) * [Wasm source import](https://rsbuild.rs/blog/v2-1#wasm-source-import) [#](https://rsbuild.rs/blog/v2-1#upgrade-to-rspack-21) Upgrade to Rspack 2.1 ---------------------------------------------------------------------------- Rsbuild 2.1 is powered by Rspack 2.1. This brings faster builds, the Rust implementation of React Compiler, new output optimization capabilities, and many improvements under the hood. For more details, see the [Rspack 2.1 announcement post](https://rspack.rs/blog/announcing-2-1) . [#](https://rsbuild.rs/blog/v2-1#rust-react-compiler) Rust-based React Compiler ------------------------------------------------------------------------------- [React Compiler](https://react.dev/learn/react-compiler) can automatically optimize React components and Hooks at build time. Previously, React Compiler was primarily integrated through a Babel plugin, which introduced additional Babel transform overhead and increased build time. Rspack 2.1 includes the [Rust implementation of React Compiler](https://github.com/react/react/pull/36173) , and Rsbuild 2.1 exposes this capability through `@rsbuild/plugin-react`. You can now enable the [`reactCompiler`](https://rsbuild.rs/plugins/list/plugin-react#reactcompiler) option in the React plugin to use React Compiler. When measuring only the additional compilation time introduced by React Compiler, our benchmarks show that the Rust implementation is **7-13x** faster than the Babel implementation. rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; export default defineConfig({ plugins: [\ pluginReact({\ reactCompiler: true,\ }),\ ], }); For projects using React 17 or React 18, you need to install `react-compiler-runtime` and explicitly set the target React version for React Compiler: rsbuild.config.ts pluginReact({ reactCompiler: { target: '18', }, }); For more options, see the [React plugin documentation](https://rsbuild.rs/plugins/list/plugin-react#reactcompiler) . [#](https://rsbuild.rs/blog/v2-1#tanstack-start-support) TanStack Start support ------------------------------------------------------------------------------- [TanStack Start](https://tanstack.com/start/latest) is a full-stack React framework powered by TanStack Router. It provides full-document SSR, streaming rendering, Server Functions, client and server builds, and more. In the Rsbuild 2.0 announcement, we mentioned that we were working with the TanStack team to explore an integration. TanStack Start now officially supports using Rsbuild as the build tool. You can keep using familiar Rsbuild configuration and plugins, and only need to add the TanStack Start plugin: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'; export default defineConfig({ plugins: [pluginReact(), tanstackStart()], }); See the [TanStack Start blog](https://tanstack.com/blog/start-adds-rsbuild-support) or the [guide](https://rsbuild.rs/guide/framework/react#tanstack-start) for more details. [#](https://rsbuild.rs/blog/v2-1#tailwind-css-plugin) Tailwind CSS plugin ------------------------------------------------------------------------- Rsbuild now provides the [Tailwind CSS plugin](https://rsbuild.rs/plugins/list/plugin-tailwindcss) for integrating Tailwind CSS v4 with Rsbuild. The plugin is built on top of Tailwind CSS's official [`@tailwindcss/webpack`](https://www.npmjs.com/package/@tailwindcss/webpack) loader. Compared with using `@tailwindcss/postcss`, this avoids running Tailwind CSS compilation through PostCSS. In our tests, it improved build performance by up to **30%**. rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginTailwindcss } from '@rsbuild/plugin-tailwindcss'; export default defineConfig({ plugins: [pluginTailwindcss()], }); [#](https://rsbuild.rs/blog/v2-1#auto-external) Automatic externals ------------------------------------------------------------------- When building Node.js applications or SSR output, some dependencies are not suitable for bundling. Examples include observability SDKs, native addons, packages that require runtime instrumentation, or peer dependencies that should be provided by the host application. In the past, these cases usually required manual `output.externals` configuration. Rsbuild now supports the [`output.autoExternal`](https://rsbuild.rs/config/output/auto-external) option. It reads dependency fields from `package.json` and automatically generates external rules. This capability was previously used mainly in Rslib, and can now be used directly in Rsbuild applications. rsbuild.config.ts export default { output: { target: 'node', autoExternal: true, }, }; [#](https://rsbuild.rs/blog/v2-1#parallel-babel-and-svgr) Parallel Babel and SVGR --------------------------------------------------------------------------------- Babel and SVGR both provide flexible transformation capabilities, but they can be relatively expensive to run. When a project has many modules that need Babel processing, or needs to convert many SVG files into React components, this overhead can become significant. [`@rsbuild/plugin-babel`](https://rsbuild.rs/plugins/list/plugin-babel#parallel) and [`@rsbuild/plugin-svgr`](https://rsbuild.rs/plugins/list/plugin-svgr#parallel) now provide the `parallel` option. This option uses Rspack's parallel loader to distribute transformation tasks to worker threads, reducing pressure on the main thread and improving overall build performance. rsbuild.config.ts import { pluginBabel } from '@rsbuild/plugin-babel'; import { pluginSvgr } from '@rsbuild/plugin-svgr'; export default { plugins: [\ pluginBabel({\ parallel: true,\ }),\ pluginSvgr({\ parallel: true,\ }),\ ], }; > Options passed to worker threads must be structured-cloneable. If you pass functions in Babel or SVGR options, keep using the default serial mode, or rewrite that logic as serializable configuration. [#](https://rsbuild.rs/blog/v2-1#css-url-imports) CSS URL imports ----------------------------------------------------------------- Rsbuild now supports [CSS `?url` imports](https://rsbuild.rs/guide/styling/css-usage#url) to access the URL of a compiled CSS file. When importing a stylesheet with `?url`, Rsbuild runs the full CSS compilation pipeline and emits the result as a separate asset. In JavaScript, you receive the final CSS file URL, and the stylesheet is not automatically injected into the page. This is useful when runtime code needs to decide when to load styles, such as in micro-frontends, theme customization, or Web Components. src/index.js import darkThemeUrl from './dark-theme.css?url'; const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = darkThemeUrl; document.head.appendChild(link); [#](https://rsbuild.rs/blog/v2-1#worker-query-imports) Worker query imports --------------------------------------------------------------------------- Rsbuild now supports importing a Worker constructor directly with the [`?worker` query](https://rsbuild.rs/guide/basic/web-workers) . This lets Worker scripts be imported like regular modules, making it easier to preserve the existing code structure when migrating from tools such as Vite. src/index.js import MyWorker from './worker.js?worker'; const worker = new MyWorker(); worker.onmessage = (event) => { console.log(event.data); }; worker.postMessage(10); By default, Worker scripts are emitted as separate chunks in production builds. If you want to inline the Worker code into the main bundle, add the `inline` query: src/index.js import InlineWorker from './worker.js?worker&inline'; const worker = new InlineWorker(); For scenarios that require the full [`WorkerOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#options) object, such as `type: 'module'` or `credentials: 'include'`, we still recommend using the [standard Worker constructor syntax](https://rsbuild.rs/guide/basic/web-workers#import-with-constructors) . [#](https://rsbuild.rs/blog/v2-1#wasm-source-import) Wasm source import ----------------------------------------------------------------------- Rsbuild 2.1 supports the [`import source`](https://rsbuild.rs/guide/basic/wasm-assets#source-import) syntax from the [Source Phase Imports](https://github.com/tc39/proposal-source-phase-imports) proposal, allowing you to obtain the compiled `WebAssembly.Module` directly. Unlike a regular import, which returns the Wasm module's exports directly, `import source` is better suited for scenarios where you need to instantiate the module manually, provide different imports, create multiple instances, or pass the module to a Worker. src/index.js import source wasmModule from './add.wasm'; const instance = await WebAssembly.instantiate(wasmModule); const { add } = instance.exports; console.log(add(1, 2)); // 3 [#](https://rsbuild.rs/blog/v2-1#upgrade) Upgrade ------------------------------------------------- If you are already using Rsbuild 2.0, you only need to upgrade the relevant `@rsbuild/*` packages to version 2.1. For more details, see [Upgrading Rsbuild](https://rsbuild.rs/guide/upgrade/upgrade-rsbuild) . --- # Announcing Rsbuild 2.0 - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/v2-0.md. ON THIS PAGE [Back to blog](https://rsbuild.rs/blog/) [#](https://rsbuild.rs/blog/v2-0#announcing-rsbuild-20) Announcing Rsbuild 2.0 ============================================================================== Copy Markdown _April 22, 2026_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v2.0.png) We are pleased to announce the official release of Rsbuild 2.0. Rsbuild is a modern build tool powered by Rspack and a key part of the Rstack ecosystem. Around it, we've built a set of higher-level tools, including [Rspress](https://github.com/web-infra-dev/rspress) , [Rslib](https://github.com/web-infra-dev/rslib) , [Rstest](https://github.com/web-infra-dev/rstest) , [Storybook Rsbuild](https://github.com/rstackjs/storybook-rsbuild) , and more. These tools share a unified build foundation and plugin system through Rsbuild, delivering a consistent development experience across application development, library builds, documentation sites, and testing. Since the 1.0 release, Rsbuild's weekly npm downloads have grown by more than **15x**, and it has become the preferred build tool for new Rspack projects. More teams are also migrating from tools such as webpack and Create React App to Rsbuild to improve both build performance and developer experience. ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-2-0-downloads.png) To help the ecosystem upgrade smoothly to 2.0, we spent three months validating and refining this release, publishing more than 20 preview versions along the way. Rslib, Rstest, Rspress, Storybook Rsbuild, and Modern.js have all completed the upgrade and are now running stably in production. The main improvements in 2.0 include: * New features: * [Upgrade to Rspack 2.0](https://rsbuild.rs/blog/v2-0#upgrade-to-rspack-20) * [React Server Components support](https://rsbuild.rs/blog/v2-0#react-server-components-support) * [Dev server and client communication](https://rsbuild.rs/blog/v2-0#dev-server-client-communication) * [Extending the built-in server](https://rsbuild.rs/blog/v2-0#extending-the-built-in-server) * [Custom logger support](https://rsbuild.rs/blog/v2-0#custom-logger-support) * [Easier chunk splitting configuration](https://rsbuild.rs/blog/v2-0#easier-chunk-splitting-configuration) * [create-rsbuild template updates](https://rsbuild.rs/blog/v2-0#create-rsbuild-template-updates) * Lighter weight: * [Reduced dependencies](https://rsbuild.rs/blog/v2-0#reduced-dependencies) * Safer by default: * [Default host change](https://rsbuild.rs/blog/v2-0#default-host-change) * [Proxy middleware upgrade](https://rsbuild.rs/blog/v2-0#proxy-middleware-upgrade) * More modern: * [Pure ESM package](https://rsbuild.rs/blog/v2-0#pure-esm-package) * [Node.js support](https://rsbuild.rs/blog/v2-0#nodejs-support) * [Updated default targets](https://rsbuild.rs/blog/v2-0#updated-default-targets) * [ESM Node.js output](https://rsbuild.rs/blog/v2-0#esm-nodejs-output) * [Updated decorator version](https://rsbuild.rs/blog/v2-0#updated-decorator-version) [#](https://rsbuild.rs/blog/v2-0#upgrade-to-rspack-20) Upgrade to Rspack 2.0 ---------------------------------------------------------------------------- Rsbuild 2.0 is powered by Rspack 2.0. This brings faster builds, new output optimization capabilities, and many improvements under the hood. For more details, see the [Rspack 2.0 announcement post](https://rspack.rs/blog/announcing-2-0) . [#](https://rsbuild.rs/blog/v2-0#react-server-components-support) React Server Components support ------------------------------------------------------------------------------------------------- [React Server Components](https://react.dev/reference/rsc/server-components) (RSC) are a type of pre-rendered React component that combines data fetching and component logic while reducing the amount of JavaScript sent to the client. To make RSC easier to use in Rsbuild-based web apps and frameworks, we introduced the [rsbuild-plugin-rsc](https://github.com/rstackjs/rsbuild-plugin-rsc) plugin. It is built on top of Rspack's built-in RSC support and uses Rsbuild's [Environments API](https://rsbuild.rs/guide/advanced/environments) to organize multiple environments, such as client and server, in a unified way. This reduces both integration and configuration costs. rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; import { pluginRSC } from 'rsbuild-plugin-rsc'; export default defineConfig({ plugins: [\ pluginReact(),\ pluginRSC({\ // Plugin options\ }),\ ], environments: { server: { // Server config... }, client: { // Client config... }, }, }); The plugin is still experimental. It can already run the [React Router RSC example](https://github.com/rstackjs/rsbuild-plugin-rsc/tree/main/examples/react-router) , and it has also been adopted by the [Modern.js framework](https://modernjs.dev/guides/basic-features/render/rsc) . We're also working with the [TanStack](https://tanstack.com/) team and plan to add support for [TanStack Start](https://tanstack.com/start) and [TanStack's RSC](https://tanstack.com/blog/react-server-components) in future releases. TanStack Start is a full-stack framework built on TanStack Router, and we're excited to explore more possibilities for RSC together. [#](https://rsbuild.rs/blog/v2-0#dev-server-client-communication) Dev server and client communication ----------------------------------------------------------------------------------------------------- While working on React Server Components support, we found that some scenarios require communication between the dev server and the browser. For example, after the server completes some work, it may need to actively notify the client to run related logic. To support this, Rsbuild 2.0 provides a set of communication APIs: * The server can send messages to the client for the current environment through [hot.send](https://rsbuild.rs/api/javascript-api/environment-api#hotsend) * The client can listen to these custom events through `import.meta.webpackHot.on` These APIs reuse the existing HMR channel, so no additional WebSocket connection is required. Messages are sent only to the matching environment, avoiding unnecessary broadcasts. For example, when server-side state changes, you can notify the client to update instead of triggering a full page refresh: * Send a message from the server: rsbuild.config.ts server.environments.web.hot.send('data-change', { count: 1, }); * Listen for the message on the client: src/dev-sync.ts if (import.meta.webpackHot) { import.meta.webpackHot.on('data-change', ({ count }) => { console.log('data updated:', count); }); } [#](https://rsbuild.rs/blog/v2-0#extending-the-built-in-server) Extending the built-in server --------------------------------------------------------------------------------------------- Rsbuild 2.0 adds the [server.setup](https://rsbuild.rs/config/server/setup) option, which allows you to run initialization logic when the dev server or preview server starts. Compared with the existing `server.setupMiddlewares`, this option is more powerful. You can use it to customize the built-in Rsbuild server by registering middleware, running tasks before startup, or injecting different logic for dev and preview modes. With `server.setup`, these tasks can be handled directly in the Rsbuild config. For example, you can add a simple endpoint for local development and preview: rsbuild.config.ts export default { server: { setup: ({ server }) => { server.middlewares.use((req, res, next) => { if (req.url === '/api/health') { res.end('ok'); return; } next(); }); }, }, }; [#](https://rsbuild.rs/blog/v2-0#custom-logger-support) Custom logger support ----------------------------------------------------------------------------- With the new [customLogger](https://rsbuild.rs/config/custom-logger) option, you can define a different logger for each Rsbuild instance. This makes it possible to use different log levels, output prefixes, or custom logging systems without modifying the [global logger instance](https://rsbuild.rs/api/javascript-api/core#logger) . rsbuild.config.ts import { createLogger, defineConfig } from '@rsbuild/core'; const customLogger = createLogger({ level: 'warn', prefix: '[web]', }); export default defineConfig({ customLogger, }); > See the [logging guide](https://rsbuild.rs/guide/advanced/logging) > for more details. [#](https://rsbuild.rs/blog/v2-0#easier-chunk-splitting-configuration) Easier chunk splitting configuration ----------------------------------------------------------------------------------------------------------- In 1.x, Rsbuild provided common chunk splitting strategies through [performance.chunkSplit](https://v1.rsbuild.rs/config/performance/chunk-split) . However, its design differed significantly from Rspack's `splitChunks`, so developers had to learn additional concepts such as `strategy` and `forceSplitting`. It also made it harder for coding agents to generate `splitChunks` configurations that matched community conventions directly, often requiring extra conversion. For this reason, Rsbuild 2.0 introduces the new [splitChunks](https://rsbuild.rs/config/split-chunks) option. Its behavior is fully aligned with Rspack's `splitChunks`, and an additional `preset` option provides built-in presets. For example, you can use the `per-package` preset to split each package into a separate chunk: rsbuild.config.ts export default { splitChunks: { preset: 'per-package', chunks: 'all', }, }; > `performance.chunkSplit` is deprecated in 2.0, but existing configurations will continue to work. We recommend migrating by following [Migrate from performance.chunkSplit](https://rsbuild.rs/guide/upgrade/v1-to-v2#migrate-performancechunksplit) > . [#](https://rsbuild.rs/blog/v2-0#create-rsbuild-template-updates) create-rsbuild template updates ------------------------------------------------------------------------------------------------- Alongside the core improvements, we also updated the templates in `create-rsbuild` to make project scaffolding better aligned with current development practices: * `AGENTS.md` is now generated by default, and you can install Agent Skills such as [rsbuild-best-practices](https://github.com/rstackjs/agent-skills?tab=readme-ov-file#rsbuild-skills) during initialization. * When creating a React project, you can choose [React Compiler](https://rsbuild.rs/guide/framework/react#react-compiler) as an optional tool. * Experimental support for [Rslint](https://github.com/web-infra-dev/rslint) has been added. Rslint is a high-performance linter built on `typescript-go`. * Outdated React 18 and Vue 2 templates have been removed. [#](https://rsbuild.rs/blog/v2-0#reduced-dependencies) Reduced dependencies --------------------------------------------------------------------------- Rsbuild 2.0 reduces its default dependencies by moving packages that are only needed in specific scenarios out of the default install set. This reduces the number of default dependencies from 13 to 4 and cuts installation size by about 2 MB. The main changes are: * [core-js](https://www.npmjs.com/package/core-js) is no longer installed by default. Install it manually when using [output.polyfill](https://rsbuild.rs/config/output/polyfill) . * [@module-federation/runtime-tools](https://www.npmjs.com/package/@module-federation/runtime-tools) is no longer installed by default. Install it manually when using [moduleFederation.options](https://rsbuild.rs/config/module-federation/options) . Module Federation 2.0 is not affected. * The [webpack-bundle-analyzer](https://www.npmjs.com/package/webpack-bundle-analyzer) dependency has been removed. We recommend using [Rsdoctor](https://rsbuild.rs/guide/debug/rsdoctor) for bundle analysis, or installing and registering `webpack-bundle-analyzer` yourself. [#](https://rsbuild.rs/blog/v2-0#default-host-change) Default host change ------------------------------------------------------------------------- The default value of [server.host](https://rsbuild.rs/config/server/host) has changed from `'0.0.0.0'` to `'localhost'`. By default, the dev server and preview server now listen only on the local machine and are no longer exposed to other devices on the local network. This change follows a secure-by-default principle. In most local development scenarios, the dev server does not need to be exposed externally. Listening only on the local address reduces accidental exposure and lowers the risk of scans or attacks on shared networks. If you need to access the page from devices on the local network, you can enable network access explicitly: rsbuild.config.ts export default { server: { host: '0.0.0.0', }, }; You can also enable it quickly with the `--host` CLI option: rsbuild --host [#](https://rsbuild.rs/blog/v2-0#proxy-middleware-upgrade) Proxy middleware upgrade ----------------------------------------------------------------------------------- The [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware) used by the dev server has been upgraded from v2 to the latest v4 release. At the same time, its underlying dependency has been switched from the unmaintained [http-proxy](https://www.npmjs.com/package/http-proxy) to [httpxy](https://npmx.dev/package/httpxy) , which is actively maintained by the [unjs community](https://github.com/unjs) . This brings several improvements: * HTTP/2 proxy support * Fixes for known security issues * No longer relying on Node.js's deprecated `url.parse()` API > Some fields in `server.proxy` have changed. When upgrading, please refer to [Migrate from v1 to v2](https://rsbuild.rs/guide/upgrade/v1-to-v2#proxy-middleware-upgraded) > . [#](https://rsbuild.rs/blog/v2-0#pure-esm-package) Pure ESM package ------------------------------------------------------------------- [@rsbuild/core](https://www.npmjs.com/package/@rsbuild/core) is now published as a pure ESM package, and its CommonJS build output has been removed. This change only affects how Rsbuild itself is distributed, reducing installation size by about 500 KB. In Node.js 20 and later, the runtime natively supports loading ESM modules through [require(esm)](https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require) . For most projects that still use Rsbuild through its JavaScript API, this change should have no practical impact and does not require any code changes. [#](https://rsbuild.rs/blog/v2-0#nodejs-support) Node.js support ---------------------------------------------------------------- Starting from 2.0, the minimum supported Node.js versions for Rsbuild are `20.19+` or `22.12+`. Since Node.js 18 reached end of life in late April 2025, 2.0 no longer supports it. > We usually remove support for a Node.js version about one year after it enters EOL, to give the community and users more time to upgrade. [#](https://rsbuild.rs/blog/v2-0#updated-default-targets) Updated default targets --------------------------------------------------------------------------------- Rsbuild 2.0 updates its default targets so build output targets more modern browsers and Node.js versions. For web output, the default browserslist now matches the [`baseline widely available on 2025-05-01`](https://browsersl.ist/#q=baseline+widely+available+on+2025-05-01) query. This query is based on the [Baseline Widely Available](https://web-platform-dx.github.io/baseline/) feature set as of [May 1, 2025](https://web-platform-dx.github.io/supported-browsers/?widelyAvailableOnDate=2025-05-01) . The default values change as follows: * Chrome 87 -> 107 * Edge 88 -> 107 * Firefox 78 -> 104 * Safari 14 -> 16 This means that if you do not explicitly configure browserslist, Rsbuild will generate more modern JavaScript and CSS by default while reducing syntax downleveling and polyfills. For Node.js output, the default target version is also raised from Node.js 16 to Node.js 20. If you have already configured the target environment explicitly through `.browserslistrc`, `package.json#browserslist`, or [output.overrideBrowserslist](https://rsbuild.rs/config/output/override-browserslist) , these changes will not affect your project. [#](https://rsbuild.rs/blog/v2-0#esm-nodejs-output) ESM Node.js output ---------------------------------------------------------------------- For Node.js output, Rsbuild 2.0 now generates unminified ES modules by default instead of the minified CommonJS output used in Rsbuild v1. This better matches common practice in modern Node.js applications. At the same time, leaving server-side code unminified by default helps preserve readable stack traces and makes debugging easier. Note that the runtime must be able to load ESM. For example, you can set `"type": "module"` in `package.json`, or use `.mjs` as the output file extension. If your project still depends on CommonJS, you can switch back explicitly: rsbuild.config.ts export default { output: { target: 'node', module: false, minify: true, }, }; [#](https://rsbuild.rs/blog/v2-0#updated-decorator-version) Updated decorator version ------------------------------------------------------------------------------------- With the underlying SWC now supporting the `2023-11` decorator version, Rsbuild updates the default value of [decorators.version](https://rsbuild.rs/config/source/decorators#decoratorsversion) from `2022-03` to `2023-11`. `2023-11` is the latest proposal version. It corresponds to the specification after the TC39 meeting in November 2023 and is also the default behavior in Babel 8. If you need to keep the old behavior, you can specify the version explicitly: rsbuild.config.ts export default { source: { decorators: { version: '2022-03', }, }, }; [#](https://rsbuild.rs/blog/v2-0#upgrading-to-rsbuild-20) Upgrading to Rsbuild 2.0 ---------------------------------------------------------------------------------- For most projects, upgrading to Rsbuild 2.0 should be relatively smooth. Although 2.0 introduces some default behavior and breaking changes, most come with a clear migration path, and in most cases you do not need to modify application code. If you are using a coding agent with skill support, you can install the [rsbuild-v2-upgrade](https://github.com/rstackjs/agent-skills#rsbuild-v2-upgrade) skill to let the agent automatically help with dependency upgrades, configuration updates, and migration checks, reducing manual work. npx skills add rstackjs/agent-skills --skill rsbuild-v2-upgrade For the full migration guide and the complete list of breaking changes, see [Upgrading from v1 to v2](https://rsbuild.rs/guide/upgrade/v1-to-v2) . [#](https://rsbuild.rs/blog/v2-0#acknowledgments) Acknowledgments ----------------------------------------------------------------- Rsbuild is primarily developed by the Rstack team, and it also relies on contributions from community members and support from users. Since the 1.0 release, many developers have helped move Rsbuild forward through their contributions. We would like to thank everyone who has been part of that journey: [@9aoy](https://github.com/9aoy) , [@adammark](https://github.com/adammark) , [@ahabhgk](https://github.com/ahabhgk) , [@alexUXUI](https://github.com/alexUXUI) , [@bodia-uz](https://github.com/bodia-uz) , [@Brennvo](https://github.com/Brennvo) , [@caohuilin](https://github.com/caohuilin) , [@Cheese-Yu](https://github.com/Cheese-Yu) , [@chenjiahan](https://github.com/chenjiahan) , [@Chevindu](https://github.com/Chevindu) , [@Colin3191](https://github.com/Colin3191) , [@colinaaa](https://github.com/colinaaa) , [@CPunisher](https://github.com/CPunisher) , [@davide97g](https://github.com/davide97g) , [@Deku-nattsu](https://github.com/Deku-nattsu) , [@DeveshSapkale](https://github.com/DeveshSapkale) , [@dovigod](https://github.com/dovigod) , [@Draculabo](https://github.com/Draculabo) , [@easy1090](https://github.com/yifancong) , [@escaton](https://github.com/escaton) , [@fansenze](https://github.com/fansenze) , [@fi3ework](https://github.com/fi3ework) , [@gaoachao](https://github.com/gaoachao) , [@GiveMe-A-Name](https://github.com/GiveMe-A-Name) , [@GRAMMAC1](https://github.com/GRAMMAC1) , [@hai-x](https://github.com/hai-x) , [@hangCode2001](https://github.com/nice-hang) , [@hardfist](https://github.com/hardfist) , [@hasnum-stack](https://github.com/hasnum-stack) , [@htoooth](https://github.com/htoooth) , [@Huxpro](https://github.com/Huxpro) , [@ianzone](https://github.com/ianzone) , [@iceprosurface](https://github.com/iceprosurface) , [@inottn](https://github.com/inottn) , [@jerrykingxyz](https://github.com/jerrykingxyz) , [@jkzing](https://github.com/jkzing) , [@JounQin](https://github.com/JounQin) , [@JSerFeng](https://github.com/JSerFeng) , [@JSH-data](https://github.com/JSH-data) , [@junhea](https://github.com/junhea) , [@junxiongchu](https://github.com/junxiongchu) , [@lguzzon](https://github.com/lguzzon) , [@LingyuCoder](https://github.com/LingyuCoder) , [@lluisemper](https://github.com/lluisemper) , [@lxKylin](https://github.com/lxKylin) , [@mhutter](https://github.com/mhutter) , [@miownag](https://github.com/miownag) , [@mycoin](https://github.com/mycoin) , [@nikhilsnayak](https://github.com/nikhilsnayak) , [@notzheng](https://github.com/notzheng) , [@Nsttt](https://github.com/Nsttt) , [@nyqykk](https://github.com/nyqykk) , [@puxiao](https://github.com/puxiao) , [@qmakani](https://github.com/qmakani) , [@quininer](https://github.com/quininer) , [@RobHannay](https://github.com/RobHannay) , [@roli-lpci](https://github.com/roli-lpci) , [@s-chance](https://github.com/s-chance) , [@s-r-x](https://github.com/s-r-x) , [@sagar-dwivedi](https://github.com/sagar-dwivedi) , [@Sang-Sang33](https://github.com/Sang-Sang33) , [@schu34](https://github.com/schu34) , [@ScriptedAlchemy](https://github.com/ScriptedAlchemy) , [@Shucei](https://github.com/Shucei) , [@shulaoda](https://github.com/shulaoda) , [@Simon-He95](https://github.com/Simon-He95) , [@slobo](https://github.com/slobo) , [@snatvb](https://github.com/snatvb) , [@SoonIter](https://github.com/SoonIter) , [@stormslowly](https://github.com/stormslowly) , [@SyMind](https://github.com/SyMind) , [@T9-Forever](https://github.com/T9-Forever) , [@thinkasany](https://github.com/thinkasany) , [@Timeless0911](https://github.com/Timeless0911) , [@TinsFox](https://github.com/TinsFox) , [@valorkin](https://github.com/valorkin) , [@vegerot](https://github.com/vegerot) , [@VenDream](https://github.com/VenDream) , [@wangi4myself](https://github.com/wangi4myself) , [@wChenonly](https://github.com/wChenonly) , [@wjw99830](https://github.com/wjw99830) , [@wralith](https://github.com/wralith) , [@wxiaoyun](https://github.com/wxiaoyun) , [@xbzhang2020](https://github.com/xbzhang2020) , [@xc2](https://github.com/xc2) , [@xettri](https://github.com/xettri) , [@xiaohp](https://github.com/xiaohp) , [@xuexb](https://github.com/xuexb) , [@xun082](https://github.com/xun082) , [@yifancong](https://github.com/yifancong) , [@ymq001](https://github.com/ymq001) , [@zackarychapple](https://github.com/zackarychapple) , [@zalishchuk](https://github.com/zalishchuk) , [@zoolsher](https://github.com/zoolsher) --- # customLogger - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /config/custom-logger.md. MenuON THIS PAGE [#](https://rsbuild.rs/config/custom-logger#customlogger) customLogger ====================================================================== Copy Markdown * **Type:** [Logger](https://rsbuild.rs/api/javascript-api/core#logger) * **Default:** `undefined` Uses a custom logger instance for the current Rsbuild instance. > See [Logging](https://rsbuild.rs/guide/advanced/logging) > for more details. [#](https://rsbuild.rs/config/custom-logger#example) Example ------------------------------------------------------------ Use [createLogger](https://rsbuild.rs/api/javascript-api/core#createlogger) to create a new logger instance. rsbuild.config.ts import { createLogger, defineConfig } from '@rsbuild/core'; const logger = createLogger({ level: 'warn', }); export default defineConfig({ customLogger: logger, }); [#](https://rsbuild.rs/config/custom-logger#version-history) Version history ---------------------------------------------------------------------------- | Version | Changes | | --- | --- | | v2.0.0 | Added the `customLogger` option | --- # Announcing Rsbuild 0.1 - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/v0-1.md. ON THIS PAGE [Back to blog](https://rsbuild.rs/blog/) [#](https://rsbuild.rs/blog/v0-1#announcing-rsbuild-01) Announcing Rsbuild 0.1 ============================================================================== Copy Markdown _November 22, 2023_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-1.png) We are pleased to announce **the release of** **[Rsbuild](https://github.com/web-infra-dev/rsbuild) ** **0.1!** Rsbuild is an Rspack-based build tool, designed to be **an enhanced Rspack** **CLI** that is both more user friendly and out-of-the-box. Rsbuild is the ideal solution for those looking to migrate from webpack to Rspack. It significantly reduces configuration by 90% while offering a 10x build speed. ### [#](https://rsbuild.rs/blog/v0-1#-performance) 🚀 Performance The build performance of Rsbuild is on par with native Rspack. Considering that Rsbuild includes more out-of-the-box features, its performance will be slightly lower than Rspack. Time to build a large web application: Rsbuild 1.36s dev 3.35s build 160ms hmr Vite 6.50s dev 1.98s build 130ms hmr webpack 21.40s dev 28.10s build 2.78s hmr > The data is based on the benchmark built by the Farm team, more info in [build-tools-performance](https://github.com/rstackjs/build-tools-performance) > . ### [#](https://rsbuild.rs/blog/v0-1#-features) 🔥 Features Rsbuild has the following features: * **Easy to Configure**: One of the goals of Rsbuild is to provide out-of-the-box build capabilities for Rspack users, allowing developers to start a web project with zero configuration. In addition, Rsbuild provides semantic build configuration to reduce the learning curve for Rspack configuration. * **Performance Oriented**: Rsbuild integrates high-performance Rust-based tools from the community, including [Rspack](https://github.com/web-infra-dev/rspack) , [SWC](https://swc.rs/) and [Lightning CSS](https://lightningcss.dev/) , to deliver top-notch build speed and development experience. Compared to webpack-based tools like Create React App and Vue CLI, Rsbuild provides 5 to 10 times faster build performance and lighter dependencies. * **Plugin Ecosystem**: Rsbuild has a lightweight plugin system and includes a range of high-quality official plugins. Furthermore, Rsbuild is compatible with most webpack plugins and all Rspack plugins, allowing users to leverage existing community or in-house plugins in Rsbuild without the need for rewriting code. * **Stable Artifacts**: Rsbuild is designed with a strong focus on the stability of build artifacts. It ensures high consistency between artifacts in the development and production builds, and automatically completes syntax downgrading and polyfill injection. Rsbuild also provides plugins for type checking and artifact syntax validation to prevent quality and compatibility issues in production code. * **Framework Agnostic**: Rsbuild is not coupled with any front-end UI framework. It supports frameworks like React, Vue, Svelte, Solid and Preact through plugins, and plans to support more UI frameworks from the community in the future. ### [#](https://rsbuild.rs/blog/v0-1#-next-step) 💡 Next step Currently, Rsbuild is still evolving rapidly and plans to introduce many more powerful new features. For example, we are developing **Rsdoctor**, a robust build analysis tool that can be used with all Rspack and webpack projects. It will provide a visual user interface to help developers analyze build times, duplicate dependencies, code transformation processes, and more, making it easier to locate and resolve build issues. ![Rsdoctor preview](https://assets.rspack.rs/rsbuild/assets/rsdoctor-preview.jpg) We will be releasing the first working version of Rsdoctor soon. Thereafter, Rsbuild will iterate in sync with Rspack, with plans to release version 1.0 in the first half of 2024. --- # Rsbuild 0.1 发布 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/v0-1.md. 目录 [返回博客](https://rsbuild.rs/zh/blog/) [#](https://rsbuild.rs/zh/blog/v0-1#rsbuild-01-%E5%8F%91%E5%B8%83) Rsbuild 0.1 发布 ================================================================================= 复制 Markdown _November 22, 2023_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-1.png) 我们很高兴地宣布 **[Rsbuild](https://github.com/web-infra-dev/rsbuild) ** **0.1** 的发布! Rsbuild 是基于 Rspack 的构建工具,旨在成为**增强版的 Rspack CLI**,更加容易上手和开箱即用。Rsbuild 是 webpack 应用迁移到 Rspack 的最佳方案,他能帮助你减少 90% 配置并获得 10 倍构建速度。 ### [#](https://rsbuild.rs/zh/blog/v0-1#-%E6%80%A7%E8%83%BD) 🚀 性能 Rsbuild 能够充分发挥 Rspack 的性能优势。由于 Rsbuild 内置了更多开箱即用的功能,因此性能数据会略微低于 Rspack。 构建一个大型 Web 应用的时间: Rsbuild 1.36s dev 3.35s build 160ms hmr Vite 6.50s dev 1.98s build 130ms hmr webpack 21.40s dev 28.10s build 2.78s hmr > 以上数据基于 Farm 团队搭建的 benchmark,更多信息请参考 [build-tools-performance](https://github.com/rstackjs/build-tools-performance) > 。 ### [#](https://rsbuild.rs/zh/blog/v0-1#-%E7%89%B9%E6%80%A7) 🔥 特性 Rsbuild 具备以下特性: * **易于配置**:Rsbuild 的目标之一,是为 Rspack 用户提供开箱即用的构建能力,使开发者能够在零配置的情况下开发 web 项目。同时,Rsbuild 提供一套语义化的构建配置,以降低 Rspack 配置的学习成本。 * **性能优先**:Rsbuild 集成了社区中基于 Rust 的高性能工具,包括 [Rspack](https://github.com/web-infra-dev/rspack) ,[SWC](https://swc.rs/) 和 [Lightning CSS](https://lightningcss.dev/) ,以提供一流的构建速度和开发体验。与基于 webpack 的 Create React App 和 Vue CLI 等工具相比,Rsbuild 提供了 5 ~ 10 倍的构建性能,以及更轻量的依赖体积。 * **插件生态**:Rsbuild 内置一个轻量级的插件系统,提供一系列高质量的官方插件。此外,Rsbuild 兼容大部分的 webpack 插件和所有的 Rspack 插件,这意味着你可以在 Rsbuild 中使用社区或公司内沉淀的现有插件,而无须重写相关代码。 * **产物稳定**:Rsbuild 设计时充分考虑了构建产物的稳定性,它的开发和生产构建产物具备较强的一致性,并自动完成语法降级和 polyfill 注入。Rsbuild 也提供插件来进行 TypeScript 类型检查和产物语法检查,以避免线上代码的质量问题和兼容性问题。 * **框架无关**:Rsbuild 不与前端 UI 框架耦合,并通过插件来支持 React、Vue、Svelte、Solid、Preact 等框架,未来也计划支持社区中更多的 UI 框架。 ### [#](https://rsbuild.rs/zh/blog/v0-1#-%E4%B8%8B%E4%B8%80%E6%AD%A5) 💡 下一步 目前 Rsbuild 仍在快速迭代中,并计划引入更多强大的新特性。 比如,我们正在开发 **Rsdoctor**,这是一个强大的构建分析工具,可以用于所有 Rspack 和 webpack 项目。它提供可视化 UI,来帮助开发者分析项目中的构建耗时、重复依赖、代码转换过程等,使构建问题更加容易被定位和解决。 ![Rsdoctor preview](https://assets.rspack.rs/rsbuild/assets/rsdoctor-preview.jpg) 我们将在近期发布 Rsdoctor 的第一个可用版本,后续 Rsbuild 会与 Rspack 同步迭代,并计划于 2024 年上半年发布 1.0 版本。 --- # Rsbuild 0.2 发布 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/v0-2.md. 目录 [返回博客](https://rsbuild.rs/zh/blog/) [#](https://rsbuild.rs/zh/blog/v0-2#rsbuild-02-%E5%8F%91%E5%B8%83) Rsbuild 0.2 发布 ================================================================================= 复制 Markdown _2023 年 12 月 11 日_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-2.png) Rsbuild 0.2 版本包含一些 API 的不兼容更新,请参考当前文档进行升级。 [#](https://rsbuild.rs/zh/blog/v0-2#targets) Targets ---------------------------------------------------- 我们将 `createRsbuild` 方法的 `target` 移动至 rsbuild 配置对象中,这个改动使用户可以在 Rsbuild 配置文件中配置 targets。 * before: const rsbuild = await createRsbuild({ target: ['web', 'node'], }); * after: // rsbuild.config.ts export default { output: { targets: ['web', 'node'], }, }; > 仅影响 JavaScript API。使用 Rsbuild CLI 的用户不需要做任何改变。 [#](https://rsbuild.rs/zh/blog/v0-2#entry) Entry ------------------------------------------------ 删除已弃用的 `source.entries` 配置。 自 Rsbuild 0.1.0 起,`source.entries` 已更名为 `source.entry`,我们在 Rsbuild v0.2.0`中删除了`source.entries\` 配置。 * before: // rsbuild.config.ts export default { source: { entries: {}, }, }; * after: // rsbuild.config.ts export default { source: { entry: {}, }, }; [#](https://rsbuild.rs/zh/blog/v0-2#write-to-disk) Write to disk ---------------------------------------------------------------- `dev.writeToDisk` 的默认值变更为 `false`. 原因: * 减少文件系统开销,提升开发服务器性能。 * 避免触发 UnoCSS 和其他工具的监听器。参考:[#654](https://github.com/web-infra-dev/rsbuild/issues/654) 。 * 使默认行为与 webpack-dev-middleware 及其他社区开发服务器保持一致。 用户可以手动开启写入磁盘: export default { dev: { writeToDisk: true, }, }; [#](https://rsbuild.rs/zh/blog/v0-2#babel-%E6%8F%92%E4%BB%B6) Babel 插件 ---------------------------------------------------------------------- `@rsbuild/plugin-babel` 将所有的 babel-loader 选项移动到 `babelLoaderOptions`: * before: pluginBabel({ plugins: [], presets: [], }); * after: pluginBabel([\ babelLoaderOptions: {\ plugins: [],\ presets: [],\ }\ ]); 这种改变使我们能为 `pluginBabel` 添加更多选项,如 `include` 和 `exclude`。 [#](https://rsbuild.rs/zh/blog/v0-2#source-map) Source map ---------------------------------------------------------- `output.disableSourceMap` 已经更名为 `output.sourceMap`. * before: export default { output: { disableSourceMap: { js: true, css: true, }, }, }; * after: export default { output: { sourceMap: { js: false, css: false, }, }, }; source map 的默认值已更新,以提升构建性能。 * 之前:在开发阶段生成 JS / CSS 的 source map,在生产阶段生成 JS 的 source map。 * 之后:在开发阶段生成 JS 的 source map,在生产阶段不生成 source map。 [#](https://rsbuild.rs/zh/blog/v0-2#inject-styles) Inject styles ---------------------------------------------------------------- 将 `output.disableCssExtract` 更名为 `output.injectStyles` 以更加直观: * before: export default { output: { disableCssExtract: true, }, }; * after: export default { output: { injectStyles: true, }, }; --- # Rsbuild 0.3 发布 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/v0-3.md. 目录 [返回博客](https://rsbuild.rs/zh/blog/) [#](https://rsbuild.rs/zh/blog/v0-3#rsbuild-03-%E5%8F%91%E5%B8%83) Rsbuild 0.3 发布 ================================================================================= 复制 Markdown _2024 年 1 月 10 日_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-3.png) Rsbuild 0.3 版本升级 Rspack 到 0.5 并支持了模块联邦。此外,还包含一些 API 的不兼容更新,请参考当前文档进行升级。 [#](https://rsbuild.rs/zh/blog/v0-3#rspack-05) Rspack 0.5 --------------------------------------------------------- 将 Rspack 升级到 v0.5.0,详情见:[Rspack 0.5 发布公告](https://rspack.rs/zh/blog/announcing-0-5) 主要变动: * [支持 Module Federation](https://rspack.rs/zh/blog/module-federation-added-to-rspack) * [移除已弃用的 builtins 选项](https://rspack.rs/zh/blog/announcing-0-5#%E7%A7%BB%E9%99%A4%E5%B7%B2%E5%BC%83%E7%94%A8%E7%9A%84-builtins-options) [#](https://rsbuild.rs/zh/blog/v0-3#toml--yaml-%E6%8F%92%E4%BB%B6) TOML / YAML 插件 --------------------------------------------------------------------------------- 在 JS 中导入 TOML 和 YAML 的需求并不常见,所以从 v0.3.0 开始,Rsbuild 核心将不再默认支持导入 TOML 和 YAML。 TOML 和 YAML 将变成独立的插件: * TOML: // rsbuild.config.ts import { pluginToml } from '@rsbuild/plugin-toml'; export default { plugins: [pluginToml()], }; * YAML: // rsbuild.config.ts import { pluginYaml } from '@rsbuild/plugin-yaml'; export default { plugins: [pluginYaml()], }; [#](https://rsbuild.rs/zh/blog/v0-3#javascript-api) JavaScript API ------------------------------------------------------------------ 包含一些 JavaScript API 的参数变更: * `rsbuild.startDevServer` 的 `printURLs` 选项已被弃用,改用 [server.printUrls](https://rsbuild.rs/zh/config/server/print-urls) 代替。 * `rsbuild.startDevServer` 的 `logger` 选项已被弃用,改用 [logger.override()](https://rsbuild.rs/zh/api/javascript-api/core#logger) 代替。 [#](https://rsbuild.rs/zh/blog/v0-3#node-%E4%BA%A7%E7%89%A9) Node 产物 -------------------------------------------------------------------- * 调整针对 Node.js 的默认 browserslist,从 `node >= 14` 变为 `node >= 16`。 * `output.distPath.server` 的默认值从 `'bundles'` 改为 `'server'`。 --- # Rsbuild 0.5 发布 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/v0-5.md. 目录 [返回博客](https://rsbuild.rs/zh/blog/) [#](https://rsbuild.rs/zh/blog/v0-5#rsbuild-05-%E5%8F%91%E5%B8%83) Rsbuild 0.5 发布 ================================================================================= 复制 Markdown _2024 年 3 月 19 日_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-5.png) Rsbuild 0.5 是一个重要的里程碑,从该版本开始,Rsbuild 的绝大部分 API 已经达到稳定状态,我们预计在 2024 年 Q3 发布 Rsbuild v1.0。 主要变更: * ⚡️ 支持启用 [Lightning CSS](https://lightningcss.dev/) 以加速 CSS 编译。 * 🌟 支持基于新的 JavaScript API 实现自定义 server。 * 🍭 重构 SVGR 插件以支持更丰富的用法。 * 📍 支持自定义压缩选项。 [#](https://rsbuild.rs/zh/blog/v0-5#%EF%B8%8F-%E6%94%AF%E6%8C%81-lightning-css) ⚡️ 支持 Lightning CSS --------------------------------------------------------------------------------------------------- Lightning CSS 是一个基于 Rust 编写的高性能 CSS 解析、转译和压缩工具。它支持将许多现代的 CSS 特性解析并转化为指定浏览器支持的语法,并提供更好的压缩比例。 Rsbuild 提供了 Lightning CSS 插件,用于按需开启 Lightning CSS 能力,并替代 Rsbuild 内置的 PostCSS、autoprefixer 和 SWC CSS minimizer。 只需要在 Rsbuild 配置中注册 Lightning CSS 插件,即可完成切换: rsbuild.config.ts import { pluginLightningcss } from '@rsbuild/plugin-lightningcss'; export default { plugins: [pluginLightningcss()], }; 在一个真实的大型 Web 应用中,我们接入了 Rsbuild Lightning CSS 插件,并使用 [Rsdoctor](https://rsdoctor.rs/) 分析构建耗时的变化: * CSS 编译耗时由 8.4s 降低到 0.12s,提升 70 倍。 * 整体构建耗时由 33.1s 降低到 25.4s,提升 30%。 [#](https://rsbuild.rs/zh/blog/v0-5#-%E6%94%AF%E6%8C%81%E8%87%AA%E5%AE%9A%E4%B9%89-server) 🌟 支持自定义 Server ---------------------------------------------------------------------------------------------------------- Rsbuild 现在支持将 dev server 替换为自定义的 server,并复用 Rsbuild 提供的页面预览、路由、模块热更新等功能。这将使得 Rsbuild 与其他 Node.js 框架结合使用变得更加容易。 比如基于 express 实现自定义 server: import express from 'express'; import { createRsbuild } from '@rsbuild/core'; async function startCustomServer() { const app = express(); const rsbuild = await createRsbuild({ config: { server: { middlewareMode: true, }, }, }); const { port, middlewares } = await rsbuild.createDevServer(); app.use(middlewares); app.listen(port); } 详情可参考 [Rsbuild - createDevServer](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildcreatedevserver) 。 [#](https://rsbuild.rs/zh/blog/v0-5#-%E9%87%8D%E6%9E%84-svgr-%E6%8F%92%E4%BB%B6) 🍭 重构 SVGR 插件 ---------------------------------------------------------------------------------------------- 在 0.5.0 之前的版本中,SVGR 插件的默认用法与 create-react-app 保持一致,允许以混合导入的形式使用 SVG: import logoUrl, { ReactComponent as Logo } from './logo.svg'; console.log(logoUrl); // -> string console.log(Logo); // -> React component 但这种做法存在两个问题: 1. **包体积增加**:混合导入会导致单个 SVG 模块被编译为两种代码(即使部分导出没有被使用),这会增加产物的包体积。 2. **编译速度下降**:混合导入会产生额外的编译开销。即使代码中未使用到 ReactComponent 导出,SVG 文件仍然会被 SVGR 编译。而 SVGR 是基于 Babel 实现的,性能开销较大。 因此,我们重构了 `@rsbuild/plugin-svgr` 插件,支持通过 `?react` query 来将 SVG 转换为 React 组件,这种用法能够解决以上问题,且更符合当前社区的最佳实践。 import logoUrl from './logo.svg'; import Logo from './logo.svg?react'; console.log(logoUrl); // -> string console.log(Logo); // -> React component SVGR 插件现在支持在多种 SVGR 用法之间切换,如果项目需要使用之前的混合导入用法,可以手动开启 [mixedImport](https://rsbuild.rs/zh/plugins/list/plugin-svgr#mixedimport) 选项: pluginSvgr({ mixedImport: true, }); [#](https://rsbuild.rs/zh/blog/v0-5#-%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8E%8B%E7%BC%A9%E9%80%89%E9%A1%B9) 📍 自定义压缩选项 ---------------------------------------------------------------------------------------------------------------- `output.disableMinimize` 选项已经被重命名为 [output.minify](https://rsbuild.rs/zh/config/output/minify) ,并允许自定义 JS 和 HTML 的压缩选项。 rsbuild.config.ts export default { output: { minify: { jsOptions: { minimizerOptions: { mangle: false, }, }, }, }, }; 使用 `output.disableMinimize` 的项目可以参考以下示例: export default { output: { disableMinimize: true, minify: false, }, }; > 详见 ["allow customize minify options"](https://github.com/web-infra-dev/rsbuild/issues/1681) > 。 * * * 更多内容请参考: * [Rsbuild 0.5.0 更新日志](https://github.com/web-infra-dev/rsbuild/releases/tag/v0.5.0) * [Rsbuild 0.5.0 不兼容更新](https://github.com/web-infra-dev/rsbuild/discussions/1732) --- # Rsbuild 0.6 发布 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/v0-6.md. 目录 [返回博客](https://rsbuild.rs/zh/blog/) [#](https://rsbuild.rs/zh/blog/v0-6#rsbuild-06-%E5%8F%91%E5%B8%83) Rsbuild 0.6 发布 ================================================================================= 复制 Markdown _2024 年 4 月 10 日_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-6.png) Rsbuild 0.6 已与 Rspack 0.6 同步发布! 主要变更: * 升级 Rspack 0.6 * 默认启用 error overlay * 支持 Vue JSX HMR * 全新的 transform 插件 API * 默认端口调整为 3000 [#](https://rsbuild.rs/zh/blog/v0-6#%E5%8D%87%E7%BA%A7-rspack-06) 升级 Rspack 0.6 ------------------------------------------------------------------------------- Rsbuild 已将依赖的 Rspack 升级至 0.6 版本,并适配了 Rspack 0.6 包含的 CSS Modules 不兼容更新。 在新版本中,Rspack 默认开启了新版 tree shaking 算法,使产物体积和产物稳定性得到显著提升。请参考 [Rspack 0.6 发布公告](https://rspack.rs/zh/blog/announcing-0-6) 了解更多。 [#](https://rsbuild.rs/zh/blog/v0-6#%E9%BB%98%E8%AE%A4%E5%90%AF%E7%94%A8-error-overlay) 默认启用 error overlay ---------------------------------------------------------------------------------------------------------- 从 Rsbuild 0.6 开始,[dev.client.overlay](https://rsbuild.rs/zh/config/dev/client) 的默认值调整为 `true`。这意味着当出现编译错误时,Rsbuild 将默认弹出 error overlay 来展示错误信息: ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-error-overlay.png) 如果你不需要此功能,可以将 `dev.client.overlay` 设置为 `false` 来禁用: rsbuild.config.ts export default defineConfig({ dev: { client: { overlay: false, }, }, }); [#](https://rsbuild.rs/zh/blog/v0-6#%E6%94%AF%E6%8C%81-vue-jsx-hmr) 支持 Vue JSX HMR ---------------------------------------------------------------------------------- `@rsbuild/plugin-vue-jsx` 现已支持 JSX HMR,当你在 Vue 3 应用中修改 JSX 代码时,会自动触发模块热替换,并保留当前页面的状态。 该功能由社区贡献者 [@liyincode](https://github.com/liyincode) 实现 ❤️,并且发布为独立的 [babel-plugin-vue-jsx-hmr](https://github.com/liyincode/babel-plugin-vue-jsx-hmr) 包,以便在 Rsbuild 以外的项目中使用。 [#](https://rsbuild.rs/zh/blog/v0-6#%E5%85%A8%E6%96%B0%E7%9A%84-transform-api) 全新的 transform API ------------------------------------------------------------------------------------------------ Rsbuild 插件现已支持 [transform API](https://rsbuild.rs/zh/plugins/dev/core#apitransform) ,这可以理解为 Rspack loader 的一个轻量化实现,它提供了简单易用的 API,并在底层自动调用 Rspack loader 进行代码转换。 在 Rsbuild 插件中,你可以通过 `api.transform` 快速实现代码转换功能,能够满足大部分常见场景,而无须学习 Rspack loader 的编写方法。 比如匹配以 .pug 为后缀的模块,并转换为 JavaScript 代码: 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;`; }); }, }); 对于一些复杂的代码转换场景,`api.transform` 可能无法满足,此时你可以使用 Rspack loader 进行实现。 [#](https://rsbuild.rs/zh/blog/v0-6#%E9%BB%98%E8%AE%A4%E7%AB%AF%E5%8F%A3%E8%B0%83%E6%95%B4%E4%B8%BA-3000) 默认端口调整为 3000 ---------------------------------------------------------------------------------------------------------------------- Rsbuild 已将 [server.port](https://rsbuild.rs/zh/config/server/port) 的默认值从 `8080` 调整到 `3000`。 端口 3000 通常用于 web 开发领域,也是 create-react-app 等工具默认使用的端口。通过更改默认端口为 3000,可以避免在使用 8080 时可能遇到的端口冲突问题。 如果你需要使用 8080 端口,可以手动设置: rsbuild.config.ts export default defineConfig({ server: { port: 8080, }, }); --- # Rsbuild types - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/api/javascript-api/types.md. 菜单目录 [#](https://rsbuild.rs/zh/api/javascript-api/types#rsbuild-types) Rsbuild types =============================================================================== 复制 Markdown 本章节介绍了 Rsbuild 提供的一些类型定义。 [#](https://rsbuild.rs/zh/api/javascript-api/types#rsbuildinstance) RsbuildInstance ----------------------------------------------------------------------------------- Rsbuild 实例的类型,对应 [createRsbuild](https://rsbuild.rs/zh/api/javascript-api/core#creatersbuild) 方法的返回值。 import type { RsbuildInstance } from '@rsbuild/core'; let rsbuild: RsbuildInstance; [#](https://rsbuild.rs/zh/api/javascript-api/types#rsbuildconfig) RsbuildConfig ------------------------------------------------------------------------------- Rsbuild 配置的类型。 import type { RsbuildConfig } from '@rsbuild/core'; const config: RsbuildConfig = { // ... }; 你也可以引用 Rsbuild 配置中各个字段的类型定义: import type { DevConfig, HtmlConfig, ToolsConfig, SourceConfig, ServerConfig, OutputConfig, SecurityConfig, PerformanceConfig, ModuleFederationConfig, } from '@rsbuild/core'; [#](https://rsbuild.rs/zh/api/javascript-api/types#normalizedconfig) NormalizedConfig ------------------------------------------------------------------------------------- Rsbuild 配置经过规范化后的类型,对应 [getNormalizedConfig](https://rsbuild.rs/zh/plugins/dev/core#apigetnormalizedconfig) 方法的返回值。 import type { NormalizedConfig } from '@rsbuild/core'; const config: NormalizedConfig = api.getNormalizedConfig(); 你也可以引用规范化后的 Rsbuild 配置中各个字段的类型定义: import type { NormalizedDevConfig, NormalizedHtmlConfig, NormalizedToolsConfig, NormalizedSourceConfig, NormalizedServerConfig, NormalizedOutputConfig, NormalizedSecurityConfig, NormalizedPerformanceConfig, NormalizedModuleFederationConfig, } from '@rsbuild/core'; [#](https://rsbuild.rs/zh/api/javascript-api/types#normalizedenvironmentconfig) NormalizedEnvironmentConfig ----------------------------------------------------------------------------------------------------------- 指定环境下经过规范化的 Rsbuild 配置类型,对应 [`getNormalizedConfig({ environment })`](https://rsbuild.rs/zh/plugins/dev/core#apigetnormalizedconfig) 方法的返回值。 import type { NormalizedEnvironmentConfig } from '@rsbuild/core'; const config: NormalizedEnvironmentConfig = api.getNormalizedConfig({ environment, }); [#](https://rsbuild.rs/zh/api/javascript-api/types#rsbuildcontext) RsbuildContext --------------------------------------------------------------------------------- Rsbuild 实例中 [context 属性](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildcontext) 的类型定义。 import type { RsbuildContext } from '@rsbuild/core'; const context: RsbuildContext = rsbuild.context; [#](https://rsbuild.rs/zh/api/javascript-api/types#rsbuildplugin) RsbuildPlugin ------------------------------------------------------------------------------- 定义 Rsbuild 插件的结构和行为。 Rsbuild 插件提供了一种标准化的方式,通过生命周期钩子和修改配置来扩展构建能力。 import type { RsbuildPlugin } from '@rsbuild/core'; const myPlugin: RsbuildPlugin = { name: 'my-plugin', setup() {}, }; [#](https://rsbuild.rs/zh/api/javascript-api/types#rsbuildpluginapi) RsbuildPluginAPI ------------------------------------------------------------------------------------- 通过 `setup` 函数提供给 Rsbuild 插件的 API 接口。 它允许插件与构建过程进行交互,修改配置、注册钩子、以及访问上下文信息。 import type { RsbuildPluginAPI } from '@rsbuild/core'; const myPlugin = { name: 'my-plugin', setup(api: RsbuildPluginAPI) {}, }; [#](https://rsbuild.rs/zh/api/javascript-api/types#rsbuildtarget) RsbuildTarget ------------------------------------------------------------------------------- Rsbuild 构建产物的类型。 import type { RsbuildTarget } from '@rsbuild/core'; [#](https://rsbuild.rs/zh/api/javascript-api/types#creatersbuildoptions) CreateRsbuildOptions --------------------------------------------------------------------------------------------- [createRsbuild](https://rsbuild.rs/zh/api/javascript-api/core#creatersbuild) 方法的入参类型。 import type { CreateRsbuildOptions } from '@rsbuild/core'; [#](https://rsbuild.rs/zh/api/javascript-api/types#inspectconfigoptions) InspectConfigOptions --------------------------------------------------------------------------------------------- [rsbuild.inspectConfig](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildinspectconfig) 方法的入参类型。 import type { InspectConfigOptions } from '@rsbuild/core'; [#](https://rsbuild.rs/zh/api/javascript-api/types#rspack) Rspack ----------------------------------------------------------------- 包含 `@rspack/core` 导出的所有类型,比如 `Rspack.Configuration`。 import type { Rspack } from '@rsbuild/core'; const rspackConfig: Rspack.Configuration = {}; [#](https://rsbuild.rs/zh/api/javascript-api/types#%E5%85%B6%E4%BB%96) 其他 ------------------------------------------------------------------------- 查看 [@rsbuild/core - src/index.ts](https://github.com/web-infra-dev/rsbuild/blob/main/packages/core/src/index.ts) 了解所有导出的类型。 --- # JavaScript API - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/api/start/index.md. 菜单目录 [#](https://rsbuild.rs/zh/api/start/#javascript-api) JavaScript API =================================================================== 复制 Markdown Rsbuild 提供了一整套 JavaScript API,以便于开发者基于 Rsbuild 开发上层的工具或框架。 Rsbuild 的 JavaScript API 可以在 Node.js、Deno 或 Bun 中使用。 [#](https://rsbuild.rs/zh/api/start/#%E6%8E%A5%E5%85%A5%E7%A4%BA%E4%BE%8B) 接入示例 ------------------------------------------------------------------------------- 下面是接入 Rsbuild JavaScript API 的基本示例。 ### [#](https://rsbuild.rs/zh/api/start/#1-%E5%AE%89%E8%A3%85-rsbuild) 1\. 安装 Rsbuild 你需要安装 `@rsbuild/core` 包: npm yarn pnpm bun deno npm add @rsbuild/core -D yarn add @rsbuild/core -D pnpm add @rsbuild/core -D bun add @rsbuild/core -D deno add npm:@rsbuild/core -D ### [#](https://rsbuild.rs/zh/api/start/#2-%E5%88%9B%E5%BB%BA-rsbuild-%E5%AE%9E%E4%BE%8B) 2\. 创建 Rsbuild 实例 你可以调用 [createRsbuild](https://rsbuild.rs/zh/api/javascript-api/core#creatersbuild) 方法来创建一个 Rsbuild 实例对象: import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild(); `createRsbuild` 方法提供了一些选项,你可以在 [API - createRsbuild](https://rsbuild.rs/zh/api/javascript-api/core#creatersbuild) 中进一步了解。 ### [#](https://rsbuild.rs/zh/api/start/#3-%E8%B0%83%E7%94%A8-rsbuild-%E5%AE%9E%E4%BE%8B%E6%96%B9%E6%B3%95) 3\. 调用 Rsbuild 实例方法 Rsbuild 实例提供了与构建相关的各个方法,你可以根据实际场景来进行使用。 在本地开发场景,建议使用 [rsbuild.startDevServer](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildstartdevserver) 方法,调用后会启动本地 dev server。 await rsbuild.startDevServer(); 成功启动 dev server 后,可以看到以下日志信息: ➜ Local: http://localhost:3000 ➜ Network: use --host to expose 在生产环境部署场景,建议使用 [rsbuild.build](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildbuild) 方法,调用后会构建出生产模式产物。 await rsbuild.build(); > 关于 Rsbuild 实例方法的更多介绍,请阅读 [Rsbuild instance](https://rsbuild.rs/zh/api/javascript-api/instance) > 章节。 通过以上三个步骤,你已经了解了 Rsbuild 基本的使用方法。接下来你可以通过 Rsbuild 插件和 Rsbuild 配置来对构建流程进行定制。 --- # Rsbuild 0.4 发布 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/v0-4.md. 目录 [返回博客](https://rsbuild.rs/zh/blog/) [#](https://rsbuild.rs/zh/blog/v0-4#rsbuild-04-%E5%8F%91%E5%B8%83) Rsbuild 0.4 发布 ================================================================================= 复制 Markdown _2024 年 2 月 6 日_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-4.png) Rsbuild 0.4 版本提供内置的模块联邦支持。此外,还包含一些 API 的不兼容更新,请参考当前文档进行升级。 ### [#](https://rsbuild.rs/zh/blog/v0-4#%E6%A8%A1%E5%9D%97%E8%81%94%E9%82%A6%E9%85%8D%E7%BD%AE) 模块联邦配置 Rsbuild 现在提供一个内置的 [moduleFederation](https://rsbuild.rs/zh/config/module-federation/options) 选项,这将使得在 Rsbuild 中配置模块联邦变得更加容易。 * **示例:** rsbuild.config.ts export default defineConfig({ moduleFederation: { options: { // ModuleFederationPluginOptions }, }, }); 当你使用该选项时,Rsbuild 会自动修改默认的 `publicPath` 和 `splitChunks` 配置,使模块联邦可以开箱即用。 > 详见 [RFC - Provide first-class support for Module Federation](https://github.com/web-infra-dev/rsbuild/discussions/1461) > 。 ### [#](https://rsbuild.rs/zh/blog/v0-4#%E6%8F%92%E4%BB%B6-hook-%E9%A1%BA%E5%BA%8F) 插件 Hook 顺序 在 Rsbuild 插件中使用 hook 时,现在可以通过 `order` 字段来声明 hook 的顺序: const myPlugin = () => ({ setup(api) { api.modifyRsbuildConfig({ handler: () => console.log('hello'), order: 'pre', }); }, }); > 详见 [插件 hooks](https://rsbuild.rs/zh/plugins/dev/hooks) > 。 ### [#](https://rsbuild.rs/zh/blog/v0-4#%E9%87%8D%E5%91%BD%E5%90%8D-disablefilenamehash) 重命名 disableFilenameHash `output.disableFilenameHash` 配置已被重命名为 [output.filenameHash](https://rsbuild.rs/zh/config/output/filename-hash) 。 * 更改前: export default { output: { disableFilenameHash: true, }, }; * 更改后: export default { output: { filenameHash: false, }, }; [#](https://rsbuild.rs/zh/blog/v0-4#%E7%A7%BB%E9%99%A4-postcss-flexbugs-fixes) 移除 postcss-flexbugs-fixes -------------------------------------------------------------------------------------------------------- Rsbuild 0.4 移除了内置的 [postcss-flexbugs-fixes](https://github.com/luisrudge/postcss-flexbugs-fixes) 插件。 该插件用于修复 IE 10 / 11 中的一些 flex bug。考虑到现代浏览器已经不再存在这些 flex 问题,我们移除了这个插件以提高构建性能。 如果你的项目需要兼容 IE 10 / 11 ,并且遇到了这些 flex 问题,你可以在 Rsbuild 中手动添加这个插件: * 安装插件: npm add postcss-flexbugs-fixes -D * 在 `postcss.config.cjs` 中注册插件: module.exports = { 'postcss-flexbugs-fixes': {}, }; [#](https://rsbuild.rs/zh/blog/v0-4#pure-react-%E6%8F%92%E4%BB%B6) Pure React 插件 -------------------------------------------------------------------------------- React 插件已移除对 [antd](https://npmjs.com/package/antd) v4 和 [@arco-design/web-react](https://npmjs.com/package/@arco-design/web-react) 的默认 [source.transformImport](https://rsbuild.rs/zh/config/source/transform-import) 配置。 与组件库相关的配置应该在组件库相关的插件中提供,如 `rsbuild-plugin-antd` 或 `rsbuild-plugin-arco`,而 React 插件会专注于提供 React 基础的能力。 * 如果你的项目正在使用 `antd` v3 或 v4,你可以手动添加以下配置: rsbuild.config.ts export default { source: { transformImport: [\ {\ libraryName: 'antd',\ libraryDirectory: 'es',\ style: 'css',\ },\ ], }, }; * 如果你的项目正在使用 `@arco-design/web-react` v3 或 v4,你可以手动添加以下配置: rsbuild.config.ts export default { source: { transformImport: [\ {\ libraryName: '@arco-design/web-react',\ libraryDirectory: 'es',\ camelToDashComponentName: false,\ style: 'css',\ },\ {\ libraryName: '@arco-design/web-react/icon',\ libraryDirectory: 'react-icon',\ camelToDashComponentName: false,\ },\ ], }, }; [#](https://rsbuild.rs/zh/blog/v0-4#javascript-api) JavaScript API ------------------------------------------------------------------ `loadConfig` 方法现在会返回配置内容和配置文件的路径: import { loadConfig } from '@rsbuild/core'; // 0.3 const config = await loadConfig(); // 0.4 const { content, filePath } = await loadConfig(); --- # Rsbuild 2.1 发布 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/v2-1.md. 目录 [返回博客](https://rsbuild.rs/zh/blog/) [#](https://rsbuild.rs/zh/blog/v2-1#rsbuild-21-%E5%8F%91%E5%B8%83) Rsbuild 2.1 发布 ================================================================================= 复制 Markdown _2026 年 6 月 26 日_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan 我们很高兴地宣布 Rsbuild 2.1 已经正式发布! 2.1 版本的主要改进包括: * 框架与生态: * [升级到 Rspack 2.1](https://rsbuild.rs/zh/blog/v2-1#upgrade-to-rspack-21) * [React Compiler Rust 版本](https://rsbuild.rs/zh/blog/v2-1#rust-react-compiler) * [TanStack Start 支持](https://rsbuild.rs/zh/blog/v2-1#tanstack-start-support) * [Tailwind CSS 插件](https://rsbuild.rs/zh/blog/v2-1#tailwind-css-plugin) * 新特性: * [自动 external](https://rsbuild.rs/zh/blog/v2-1#auto-external) * [并行编译](https://rsbuild.rs/zh/blog/v2-1#parallel-babel-and-svgr) * 资源导入: * [CSS URL 导入](https://rsbuild.rs/zh/blog/v2-1#css-url-imports) * [Worker 导入](https://rsbuild.rs/zh/blog/v2-1#worker-query-imports) * [Wasm 导入](https://rsbuild.rs/zh/blog/v2-1#wasm-source-import) [#](https://rsbuild.rs/zh/blog/v2-1#upgrade-to-rspack-21) 升级到 Rspack 2.1 ------------------------------------------------------------------------ Rsbuild 2.1 基于 Rspack 2.1 构建,带来了更快的构建性能、React Compiler Rust 版本、新的产物优化能力,以及多项底层改进。 更多详情请参考 [Rspack 2.1 发布公告](https://rspack.rs/zh/blog/announcing-2-1) 。 [#](https://rsbuild.rs/zh/blog/v2-1#rust-react-compiler) React Compiler Rust 版本 ------------------------------------------------------------------------------- [React Compiler](https://react.dev/learn/react-compiler) 可以在构建阶段自动优化 React 组件和 Hooks。过去,React Compiler 主要通过 Babel 插件接入,这会引入额外的 Babel 转换开销,并增加项目的构建时间。 Rspack 2.1 内置了 [Rust 版本的 React Compiler](https://github.com/react/react/pull/36173) ,Rsbuild 2.1 则通过 `@rsbuild/plugin-react` 对这一能力进行了封装。现在你只需要开启 [`reactCompiler`](https://rsbuild.rs/zh/plugins/list/plugin-react#reactcompiler) 选项,就可以在 React 插件中使用 React Compiler。 在我们的基准测试中,针对 React Compiler 带来的额外编译耗时,Rust 版本比 Babel 版本快 **7-13 倍**。 rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; export default defineConfig({ plugins: [\ pluginReact({\ reactCompiler: true,\ }),\ ], }); 对于 React 17 或 React 18 项目,你需要安装 `react-compiler-runtime`,并显式设置 React Compiler 的目标 React 版本: rsbuild.config.ts pluginReact({ reactCompiler: { target: '18', }, }); 更多选项可以参考 [React 插件文档](https://rsbuild.rs/zh/plugins/list/plugin-react#reactcompiler) 。 [#](https://rsbuild.rs/zh/blog/v2-1#tanstack-start-support) TanStack Start 支持 ----------------------------------------------------------------------------- [TanStack Start](https://tanstack.com/start/latest) 是一个由 TanStack Router 驱动的全栈 React 框架。它提供整页文档 SSR、流式渲染、Server Functions、客户端/服务端构建等能力。 在 Rsbuild 2.0 发布时,我们提到正在与 TanStack 团队合作探索集成。现在,TanStack Start 已经官方支持使用 Rsbuild 作为构建工具。你可以继续使用熟悉的 Rsbuild 配置与插件,只需额外注册 TanStack Start 插件: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'; export default defineConfig({ plugins: [pluginReact(), tanstackStart()], }); 参考 [TanStack Start 博客](https://tanstack.com/blog/start-adds-rsbuild-support) 或 [指南](https://rsbuild.rs/zh/guide/framework/react#tanstack-start) 了解更多。 [#](https://rsbuild.rs/zh/blog/v2-1#tailwind-css-plugin) Tailwind CSS 插件 ------------------------------------------------------------------------ Rsbuild 现在提供了 [Tailwind CSS 插件](https://rsbuild.rs/zh/plugins/list/plugin-tailwindcss) ,用于在 Rsbuild 中集成 Tailwind CSS v4。该插件基于 Tailwind CSS 官方的 [loader](https://www.npmjs.com/package/@tailwindcss/webpack) 实现。 相比通过 `@tailwindcss/postcss` 进行转换,这种方式不需要再经过 PostCSS 执行 Tailwind CSS 编译。在我们的测试中,它可以带来至多 **30%** 的构建性能提升。 rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginTailwindcss } from '@rsbuild/plugin-tailwindcss'; export default defineConfig({ plugins: [pluginTailwindcss()], }); [#](https://rsbuild.rs/zh/blog/v2-1#auto-external) 自动 external -------------------------------------------------------------- 在构建 Node.js 应用或 SSR 产物时,某些依赖并不适合打包进 bundle。例如观测 SDK、原生插件、需要运行时插桩的包,或应由宿主应用提供的 peer dependencies。过去这类场景通常需要手动配置 `output.externals`。 Rsbuild 现在支持 [`output.autoExternal`](https://rsbuild.rs/zh/config/output/auto-external) 选项。它会读取 `package.json` 中的依赖字段,并自动生成 external 规则。这个能力此前主要用于 Rslib,现在也可以直接用于 Rsbuild 应用。 rsbuild.config.ts export default { output: { target: 'node', autoExternal: true, }, }; [#](https://rsbuild.rs/zh/blog/v2-1#parallel-babel-and-svgr) 并行编译 ----------------------------------------------------------------- Babel 和 SVGR 都提供了灵活的转换能力,但执行性能较差。当项目中存在大量需要 Babel 处理的模块,或需要将大量 SVG 转换为 React 组件时,这部分开销会变得明显。 [`@rsbuild/plugin-babel`](https://rsbuild.rs/zh/plugins/list/plugin-babel#parallel) 和 [`@rsbuild/plugin-svgr`](https://rsbuild.rs/zh/plugins/list/plugin-svgr#parallel) 现在新增了 `parallel` 选项,可以借助 Rspack 的 parallel loader 将转换任务分配到 worker 线程中执行,从而降低主线程压力,提升整体构建性能。 rsbuild.config.ts import { pluginBabel } from '@rsbuild/plugin-babel'; import { pluginSvgr } from '@rsbuild/plugin-svgr'; export default { plugins: [\ pluginBabel({\ parallel: true,\ }),\ pluginSvgr({\ parallel: true,\ }),\ ], }; > 传递给 worker 线程的选项必须能够被结构化克隆。如果你在 Babel 或 SVGR 选项中传入函数,需要继续使用默认的串行模式,或将这部分逻辑改写为可序列化配置。 [#](https://rsbuild.rs/zh/blog/v2-1#css-url-imports) CSS URL 导入 --------------------------------------------------------------- Rsbuild 现在支持通过 [CSS `?url` 导入](https://rsbuild.rs/zh/guide/styling/css-usage#url) 来获取编译后样式文件的 URL。通过 `?url` 导入样式文件时,Rsbuild 会对 CSS 执行完整的编译处理,并将结果作为单独资源输出。在 JavaScript 中,你获取到的是最终 CSS 文件的 URL,样式不会自动注入页面。 这适用于需要由运行时代码决定何时加载样式的场景,例如微前端、主题定制或 Web Components 等。 src/index.js import darkThemeUrl from './dark-theme.css?url'; const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = darkThemeUrl; document.head.appendChild(link); [#](https://rsbuild.rs/zh/blog/v2-1#worker-query-imports) Worker 导入 ------------------------------------------------------------------- Rsbuild 现在支持通过 [`?worker` query](https://rsbuild.rs/zh/guide/basic/web-workers) 直接导入 Worker 构造器。这种写法让 Worker 脚本可以像普通模块一样被导入,在从 Vite 等工具迁移时也更容易保留原有代码结构。 src/index.js import MyWorker from './worker.js?worker'; const worker = new MyWorker(); worker.onmessage = (event) => { console.log(event.data); }; worker.postMessage(10); 默认情况下,Worker 脚本会在生产构建中输出为独立 chunk。如果你希望将 Worker 代码内联到主 bundle 中,可以添加 `inline` query: src/index.js import InlineWorker from './worker.js?worker&inline'; const worker = new InlineWorker(); 对于需要传入完整 [`WorkerOptions`](https://developer.mozilla.org/zh-CN/docs/Web/API/Worker/Worker#%E5%8F%82%E6%95%B0) 的场景,例如 `type: 'module'` 或 `credentials: 'include'`,仍然建议使用[标准 Worker 构造器写法](https://rsbuild.rs/zh/guide/basic/web-workers#%E4%BD%BF%E7%94%A8-worker-%E6%9E%84%E9%80%A0%E5%99%A8) 。 [#](https://rsbuild.rs/zh/blog/v2-1#wasm-source-import) Wasm 导入 --------------------------------------------------------------- Rsbuild 2.1 支持 [Source Phase Imports](https://github.com/tc39/proposal-source-phase-imports) 提案中的 [`import source`](https://rsbuild.rs/zh/guide/basic/wasm-assets#source-import) 语法,可以直接获取编译后的 `WebAssembly.Module`。 相比普通导入直接获取 Wasm 模块导出,`import source` 更适合需要手动实例化、传入不同 imports、创建多个实例,或将模块传递给 Worker 的场景。 src/index.js import source wasmModule from './add.wasm'; const instance = await WebAssembly.instantiate(wasmModule); const { add } = instance.exports; console.log(add(1, 2)); // 3 [#](https://rsbuild.rs/zh/blog/v2-1#%E5%8D%87%E7%BA%A7) 升级 ---------------------------------------------------------- 如果你已经在使用 Rsbuild 2.0,只需要将相关 `@rsbuild/*` 包升级到最新版本即可,升级方式可以参考 [升级 Rsbuild](https://rsbuild.rs/zh/guide/upgrade/upgrade-rsbuild) 。 --- # Rsbuild 0.7 发布 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/v0-7.md. 目录 [返回博客](https://rsbuild.rs/zh/blog/) [#](https://rsbuild.rs/zh/blog/v0-7#rsbuild-07-%E5%8F%91%E5%B8%83) Rsbuild 0.7 发布 ================================================================================= 复制 Markdown _2024 年 5 月 28 日_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v0-7.png) Rsbuild 0.7 已与 Rspack 0.7 同步发布! 这是 Rsbuild 1.0 版本发布前的最后一个 minor 版本,此后 Rspack 团队将投入到 1.0 版本的开发中,并致力于尽快推出 Rspack / Rsbuild 1.0 alpha 版本。 在 Rsbuild 0.7 中,值得关注的变更有: * [支持 Storybook](https://rsbuild.rs/zh/blog/v0-7#support-for-storybook) * [更快的 Sass 编译](https://rsbuild.rs/zh/blog/v0-7#faster-sass-compilation) * [更好的 CSS 支持](https://rsbuild.rs/zh/blog/v0-7#better-css-supports) * [CSS Modules 类型生成](https://rsbuild.rs/zh/blog/v0-7#typed-css-modules) * [ESM/CJS 导出](https://rsbuild.rs/zh/blog/v0-7#esmcjs-exports) * [不兼容更新](https://rsbuild.rs/zh/blog/v0-7#breaking-changes) [#](https://rsbuild.rs/zh/blog/v0-7#support-for-storybook) 支持 Storybook ----------------------------------------------------------------------- Rsbuild 现已支持 Storybook! [storybook-builder-rsbuild](https://github.com/rstackjs/storybook-rsbuild) 是基于 Storybook v8 和 Rsbuild 实现的 Storybook builder,能够快速构建你的 components 和 stories。 ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-with-storybook.png) * 对于使用 Rsbuild 的项目,现在你可以快速集成 Storybook,并复用已有的 Rsbuild 配置。 * 对于使用 Storybook webpack builder 的项目,现在即可升级到 Rsbuild,**并获得约 5 倍的构建性能提升**。 我们还提供了 `storybook-react-rsbuild` 和 `storybook-vue3-rsbuild`,用于支持 React 和 Vue 3。比如集成 React: .storybook/main.js import { StorybookConfig } from 'storybook-react-rsbuild'; const config: StorybookConfig = { framework: 'storybook-react-rsbuild', }; export default config; ![](https://assets.rspack.rs/rsbuild/assets/storybook-rsbuild-preview.png) > 更多用法请参考 [storybook-rsbuild 仓库](https://github.com/rstackjs/storybook-rsbuild) > 。 [#](https://rsbuild.rs/zh/blog/v0-7#faster-sass-compilation) 更快的 Sass 编译 ------------------------------------------------------------------------ 在 Rsbuild 0.7 中,**Sass 编译速度提高了 3~10 倍**,在大型项目项目中的性能提升尤为显著。 以编译 Bootstrap 的 Sass 代码为例,Rsbuild 0.6 和 0.7 的构建时间对比: ![](https://assets.rspack.rs/rsbuild/assets/sass-embedded-compare.jpeg) 这得益于 Rsbuild 默认启用了 [sass-embedded](https://npmjs.com/package/sass-embedded) ,sass-embedded 是一个围绕原生 Dart Sass 可执行文件的 JavaScript wrapper,具备一致的 API 和更优秀的性能。 此外,Rsbuild 还启用了 `sass-loader` 最新的 [modern-compiler](https://github.com/webpack/sass-loader/releases/tag/v14.2.0) API,这能够开启 Sass 的 shared resources 能力,在编译多个文件时重复利用相同的 compiler 进程,从而提升构建速度。 [#](https://rsbuild.rs/zh/blog/v0-7#better-css-supports) 更好的 CSS 支持 ------------------------------------------------------------------- Rsbuild 现在使用 [CssExtractRspackPlugin](https://rspack.rs/zh/plugins/rspack/css-extract-rspack-plugin) 来提取 CSS 到单独的文件中,而不是使用 [experiments.css](https://v0.rspack.rs/zh/config/experiments#experimentscss) 配置来实现。 这允许 Rsbuild 支持更多 CSS 特性,包括: * 支持在 Vue SFC 中使用 ` * 支持复杂的 CSS Modules `:global()` 语法 style.module.css :local(.parent):global(.child) > ul { color: red; } * 支持更多的 CSS Modules 选项,如 [cssModules.exportGlobals](https://rsbuild.rs/zh/config/output/css-modules#cssmodulesexportglobals) * 现在你可以使用 [tools.cssExtract](https://rsbuild.rs/zh/config/tools/css-extract) 来配置 CssExtractRspackPlugin。 [#](https://rsbuild.rs/zh/blog/v0-7#typed-css-modules) CSS Modules 类型生成 ----------------------------------------------------------------------- Rsbuild 0.7 新增了 [Typed CSS Modules 插件](https://github.com/rstackjs/rsbuild-plugin-typed-css-modules) ,用于为项目中的 CSS Modules 文件生成类型声明文件。 当你在 TypeScript 项目里使用 CSS Modules 时,默认的类型定义如下。它只能提供基本的类型支持,无法准确地提示出 CSS Modules 导出了哪些类名。 src/env.d.ts declare module '*.module.css' { const classes: { readonly [key: string]: string }; export default classes; } 在使用 Typed CSS Modules 插件后,Rsbuild 会为项目中所有的 CSS Modules 生成类型声明文件,提供准确的类型提示。 例如,创建 `src/index.ts` 和 `src/index.module.css` 两个文件: src/index.ts import styles from './index.module.css'; console.log(styles.pageHeader); index.module.css .page-header { color: black; } 构建后,Rsbuild 会自动生成 `src/index.module.css.d.ts` 类型声明文件: src/index.module.css.d.ts interface CssExports { 'page-header': string; pageHeader: string; } declare const cssExports: CssExports; export default cssExports; 此时再打开 `src/index.ts` 文件,可以看到 `styles` 对象已经具备了准确的类型。 [#](https://rsbuild.rs/zh/blog/v0-7#esmcjs-exports) ESM/CJS 导出 -------------------------------------------------------------- 现在,Rsbuild 的所有包均提供了 ES modules 和 CommonJS 两种格式的导出,并在 package.json 中声明了 ["type"="module"\`](https://nodejs.org/api/packages.html#type) 。 ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-dual-package-example.png) 这使你能够使用 `import` 或 `require` 来调用 Rsbuild 的 JavaScript API: // ES Modules import { createRsbuild } from '@rsbuild/core'; // CommonJS const { createRsbuild } = require('@rsbuild/core'); ESM/CJS 互操作是一个棘手的问题,因此我们计划长期提供这两种格式,以便于更多用户使用。 [#](https://rsbuild.rs/zh/blog/v0-7#breaking-changes) 不兼容更新 ----------------------------------------------------------- ### [#](https://rsbuild.rs/zh/blog/v0-7#%E5%8D%87%E7%BA%A7-rspack-07) 升级 Rspack 0.7 Rsbuild 已将依赖的 Rspack 升级至 0.7 版本,并适配了其中包含的不兼容更新,通常你不会受到这些不兼容更新的影响。 在新版本中,Rspack 支持了 lazy compilation,可以显著提升大型项目的 dev 启动速度。请参考 [Rspack 0.7 发布公告](https://rspack.rs/zh/blog/announcing-0-7) 了解更多。 在 Rsbuild 中,你可以使用 [dev.lazyCompilation](https://rsbuild.rs/zh/config/dev/lazy-compilation) 来启用 lazy compilation。 ### [#](https://rsbuild.rs/zh/blog/v0-7#sass-%E5%92%8C-less-%E6%8F%92%E4%BB%B6) Sass 和 Less 插件 Rsbuild 的 Sass 和 Less 插件现在是两个独立的 npm 包,而不是像之前一样内置在 `@rsbuild/core` 中,这允许用户可以按需启用 Sass 和 Less 编译能力。 比如,对于使用 Tailwind CSS、CSS-in-JS 等 CSS 方案的项目,现在不再需要安装 Sass 和 Less 所需的依赖,**这可以节省约 7MB 的磁盘空间**。 * 如果你的项目需要编译 `.scss` 或 `.sass` 文件,请安装并注册 [@rsbuild/plugin-sass](https://rsbuild.rs/zh/plugins/list/plugin-sass) 插件: rsbuild.config.ts import { pluginSass } from '@rsbuild/plugin-sass'; export default { plugins: [pluginSass()], }; * 如果你的项目需要编译 `.less` 文件,请安装并注册 [@rsbuild/plugin-less](https://rsbuild.rs/zh/plugins/list/plugin-less) 插件: rsbuild.config.ts import { pluginLess } from '@rsbuild/plugin-less'; export default { plugins: [pluginLess()], }; ### [#](https://rsbuild.rs/zh/blog/v0-7#dataurilimit-%E9%BB%98%E8%AE%A4%E5%80%BC) dataUriLimit 默认值 [output.dataUriLimit](https://rsbuild.rs/zh/config/output/data-uri-limit) 的默认值从 `10000 (10kB)` 调整为 `4096 (4KiB)`. 这是因为目前更多的应用正在使用 HTTP 2.0,所以将资源分割成单独的文件会表现得更好。而且将超过 4KiB 的资源内联可能会使 JS 包体积过大,不利于缓存。 如果你倾向于之前的默认设置,可以添加以下配置: rsbuild.config.ts export default { output: { dataUriLimit: 10000, }, }; --- # Rsbuild 1.0 发布 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/v1-0.md. 目录 [返回博客](https://rsbuild.rs/zh/blog/) [#](https://rsbuild.rs/zh/blog/v1-0#rsbuild-10-%E5%8F%91%E5%B8%83) Rsbuild 1.0 发布 ================================================================================= 复制 Markdown _2024 年 9 月 10 日_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![9aoy](https://github.com/9aoy.png) 9aoy [](https://github.com/9aoy) @9aoy ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-1-0-banner.png) 我们很高兴地宣布 Rsbuild 1.0 已经正式发布! [#](https://rsbuild.rs/zh/blog/v1-0#%E4%B8%BA%E4%BB%80%E4%B9%88%E6%98%AF-rsbuild) 为什么是 Rsbuild ---------------------------------------------------------------------------------------------- 长期以来,使用 webpack 的开发者饱受两个问题的困扰:**构建慢和配置复杂**。 我们使用 Rust 将 webpack 重写为 [Rspack](https://github.com/web-infra-dev/rspack) ,解决了构建慢的问题。但为了兼容 webpack 生态,Rspack 保留了 webpack 的配置和 API,这意味着它依然存在一定的复杂度和学习成本。 ### [#](https://rsbuild.rs/zh/blog/v1-0#%E7%94%9F%E6%80%81%E7%9A%84%E5%8F%91%E5%B1%95) 生态的发展 在早期,webpack 生态中出现了一些优秀的工具,比如 Create React App(简称 CRA)和 Vue CLI,它们为 React 或 Vue 应用提供最佳实践,隐藏了复杂的 webpack 配置。因此,许多 React 和 Vue 用户使用这些工具来创建应用,不需要从零开始配置 webpack。 随着生态的发展,Next.js、Nuxt 和 Remix 等全栈 web 框架变得流行;Vite 推出后,作为一个轻量化的构建工具,也受到了众多开发者的青睐。而 CRA、Vue CLI 则是逐渐停止了维护。 当我们查看 webpack、CRA 和 Vue CLI 的 npm 下载量时,会发现仍然有大量项目在使用这些工具。例如,webpack 有约 2500 万的周下载量,CRA 有近 300 万的周下载量。这些项目有很多是 CSR 应用,不需要使用全栈框架的 SSR 等特性;Vite 看起来是一个不错的选择,但我们在字节跳动的项目中实践后发现,从 webpack 迁移到 Vite 存在很高的成本,并且迁移带来了一些新问题,例如开发环境与生产环境的构建产物不一致、大型应用在开发过程中页面刷新缓慢等问题。 对于 webpack 生态,我们发现了一个让人遗憾的事实:**webpack 生态缺少一个易于使用且维护良好的构建工具**,它既要像 CRA 和 Vue CLI 一样对用户友好,能够很好地满足 CSR 应用开发的需求,又需要像 Vite 一样具备快速启动、插件化等特性。 ### [#](https://rsbuild.rs/zh/blog/v1-0#rsbuild-%E7%9A%84%E8%AF%9E%E7%94%9F) Rsbuild 的诞生 在开发 Rspack 的过程中,我们意识到了上述问题,并决定在 Rspack 的基础上开发一个现代的构建工具 —— **Rsbuild**。 ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-1-0-build-tools.png) Rsbuild 是以 Rspack 为核心实现的,我们为 Rsbuild 设计了易于使用、TypeScript 友好的 API,并内置一套精心设计的构建配置,使它既能充分发挥出 Rspack 的性能优势,也能解决配置复杂、上手成本高的问题。 在实现 Rsbuild 的过程中,我们向社区中优秀的工具学习最佳实践,并聚焦于两个使用场景来设计 Rsbuild: * 作为一个轻量的构建工具:帮助开发者快速搭建 Web 应用,为 CSR 应用提供开箱即用的支持。 * 作为一个共享的基础设施:为上层工具和框架提供 [JavaScript API](https://rsbuild.rs/zh/api/start/) 和 [插件 API](https://rsbuild.rs/zh/plugins/dev/) ,允许开发者基于 Rsbuild 来开发属于自己的工具或框架,轻松实现 SSR、SSG 等特性。 [#](https://rsbuild.rs/zh/blog/v1-0#%E6%80%A7%E8%83%BD) 性能 ---------------------------------------------------------- **Rsbuild 是目前 webpack 和 Rspack 生态中最快的构建工具**,下面是 Rsbuild 与 Create React App、Vite、Rspack CLI 的对比: | 指标 | Create React App | Vite (with SWC) | Rspack CLI | Rsbuild | Rsbuild vs CRA | | --- | --- | --- | --- | --- | --- | | dev 启动时间(1000 个模块) | 5.47s | 1.29s | 0.66s | 0.39s | **快 14 倍** | | build 构建时间(1000 个模块) | 5.69s | 1.39s | 0.51s | 0.27s | **快 20 倍** | | npm 依赖数量 | 1241 | 15 | 283 | 14 | **减少 99%** | | npm 安装体积 | 146.6MB | 56.3MB | 75.1MB | 59.1MB | **减少 60%** | 与 [Rspack CLI](https://npmjs.com/package/@rspack/cli) 相比,Rsbuild 内置了更丰富的功能,同时具备更好的性能表现。 这是因为 Rspack CLI 需要保持对 [webpack-cli](https://npmjs.com/package/webpack-cli) 的兼容性,它依赖了 `webpack-dev-server`,并提供与 webpack 一致的默认行为,因此性能受到了一定限制。而 Rsbuild 是面向现代 web 开发设计的,我们为 Rsbuild 重新实现了更轻量的 CLI、开发服务器和构建流程,使其具备更快的启动速度和更少的 npm 依赖。 > 参考 [Rsbuild 介绍](https://rsbuild.rs/zh/guide/start/) > 了解 Rsbuild 与 webpack、Vue CLI、Vite 的对比。 [#](https://rsbuild.rs/zh/blog/v1-0#%E8%B0%81%E5%9C%A8%E4%BD%BF%E7%94%A8) 谁在使用 ------------------------------------------------------------------------------ 在 [Rspack 1.0 发布公告](https://rspack.rs/zh/blog/announcing-1-0) 中,我们介绍了 Rspack 正在取得快速增长,这其中约有一半的 Rspack 用户已经在使用 Rsbuild,并给予我们很多正向的反馈。 在字节跳动,我们将 Rsbuild 作为内部研发框架的基石,支持了数千个 web 项目,这些项目涵盖了不同的使用场景,包括 desktop Web 应用、mobile Web 应用、跨平台 Web 应用、文档站等。 在社区中,我们开源了基于 Rsbuild 的高性能工具链,包括静态站点生成器 [Rspress](https://github.com/web-infra-dev/rspress) ,library 开发工具 [Rslib](https://github.com/web-infra-dev/rslib) ,React 全栈框架 [Modern.js](https://github.com/web-infra-dev/modern.js) ,[Storybook Rsbuild](https://github.com/rstackjs/storybook-rsbuild) 。得益于 Rsbuild 的可扩展性,这些工具能够灵活地集成 Rsbuild,并与它共享插件生态。 在 Rsbuild 1.0 发布后,我们也计划与 [Remix](https://github.com/remix-run/remix) 等优秀的团队一起探索,使 Rsbuild 能够与更多 web 框架集成。 [#](https://rsbuild.rs/zh/blog/v1-0#%E6%8F%92%E4%BB%B6%E7%94%9F%E6%80%81) 插件生态 ------------------------------------------------------------------------------ Rsbuild 的插件生态正在不断发展,目前社区中已经有超过 50 个 [Rsbuild 插件](https://github.com/rstackjs/awesome-rstack#rsbuild-plugins) 。我们通过插件提供了一些高级特性,以支持生产级应用的开发,例如 [类型检查](https://github.com/rstackjs/rsbuild-plugin-type-check) 、[产物语法检查](https://github.com/rstackjs/rsbuild-plugin-check-syntax) 、[静态资源重试](https://github.com/rstackjs/rsbuild-plugin-assets-retry) 。此外,受益于 Rspack 对 webpack 的兼容性,Rsbuild 也支持使用大部分 webpack 插件。 与 webpack 或 Rspack 相比,Rsbuild 的插件 API 更加简洁和容易上手,使开发者能够轻松地开发插件来满足自己的需求。 例如,我们来实现一个插件,它的功能是输出一个文件到产物目录,在 Rspack 和 Rsbuild 中的实现对比如下: ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-1-0-plugin-compare.png) 可以看到,Rsbuild 插件的 API 风格与 esbuild 类似,可以通过一个函数来定义。插件的 hooks 经过简化,避免了冗长的 API,使插件的编写更符合直觉。 [#](https://rsbuild.rs/zh/blog/v1-0#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8-10) 如何使用 1.0 ------------------------------------------------------------------------------------- * 如果你还未使用过 Rsbuild,可以参考 [快速上手](https://rsbuild.rs/zh/guide/start/quick-start) 来接入 Rsbuild。 * 如果你正在使用 Rsbuild 0.7 或更早的版本,请留意 1.0 版本包含一些不兼容更新,可参考 [从 Rsbuild 0.x 迁移](https://rsbuild.rs/zh/guide/upgrade/v0-to-v1) 文档进行升级。 * Rsbuild 也提供了 webpack、CRA、Vue CLI 等项目的迁移指南,详见 [从现有项目迁移](https://rsbuild.rs/zh/guide/start/quick-start#migrate-from-existing-projects) 。 > 欢迎为 [Rsbuild GitHub 仓库](https://github.com/web-infra-dev/rsbuild) > 点亮一颗 Star 🌟。 [#](https://rsbuild.rs/zh/blog/v1-0#%E4%B8%8B%E4%B8%80%E6%AD%A5) 下一步 -------------------------------------------------------------------- Rsbuild 1.0 为企业级应用和上层工具开发提供了一些高级特性,例如 [多环境构建 API](https://rsbuild.rs/zh/guide/advanced/environments) 、[服务端渲染 API](https://rsbuild.rs/zh/guide/advanced/ssr) 、[插件 API](https://rsbuild.rs/zh/plugins/dev/) 、[模块联邦支持](https://rsbuild.rs/zh/guide/advanced/module-federation) 和 [Library 构建(Rslib)](https://github.com/web-infra-dev/rslib) ,我们计划继续完善这些特性,更好地支持 Rsbuild 生态发展。 在接下来的 12~18 个月里,Rsbuild 将与 Rspack 共同演进,在第一时间应用 Rspack 的新特性,例如持久化缓存、更快的 HMR、基于 TypeScript 的优化等。请参考 [Rspack - 下一步](https://rspack.rs/zh/blog/announcing-1-0#%E4%B8%8B%E4%B8%80%E6%AD%A5) 了解更多。 最后,感谢所有为 Rsbuild 贡献过的开发者 ❤️: ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-1-0-contributors.png) --- # Rsbuild 博客 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/index.md. 目录 Rsbuild 博客[#](https://rsbuild.rs/zh/blog/#rsbuild-%E5%8D%9A%E5%AE%A2) ====================================================================== 复制 Markdown 这里汇总了与 Rsbuild 相关的博客文章。另外,Rsbuild 的 minor 版本更新通常也会直接发布在 [Rspack 博客](https://rspack.rs/zh/blog/) 中。 [2026年6月26日\ \ Rsbuild 2.1 发布\ \ Rsbuild 2.1 带来 Rust 版本 React Compiler、TanStack Start 支持、Tailwind CSS v4 插件,以及 CSS url、Worker 等资源导入 query 支持。\ \ ![](https://github.com/chenjiahan.png)\ \ Jiahan Chen](https://rsbuild.rs/zh/blog/v2-1) [2026年4月22日\ \ Rsbuild 2.0 发布\ \ Rsbuild 2.0 正式发布,升级 Rspack 2.0,引入 RSC 支持和更现代的默认行为。\ \ ![](https://github.com/chenjiahan.png)\ \ Jiahan Chen](https://rsbuild.rs/zh/blog/v2-0) [2024年9月10日\ \ Rsbuild 1.0 发布\ \ Rsbuild 1.0 正式发布,围绕更快构建、更易配置和插件生态展开,并介绍性能表现、社区采用与后续规划。\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/zh/blog/v1-0) [2024年5月28日\ \ Rsbuild 0.7 发布\ \ Rsbuild 0.7 发布,支持 Storybook、更快的 Sass 编译和 CSS Modules 类型生成。\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/zh/blog/v0-7) [2024年4月10日\ \ Rsbuild 0.6 发布\ \ Rsbuild 0.6 发布,默认启用 error overlay,支持 Vue JSX HMR,并引入全新的 transform API。\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/zh/blog/v0-6) [2024年3月19日\ \ Rsbuild 0.5 发布\ \ Rsbuild 0.5 发布,支持 Lightning CSS、自定义 Server 和更灵活的压缩配置。\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/zh/blog/v0-5) [2024年2月6日\ \ Rsbuild 0.4 发布\ \ Rsbuild 0.4 发布,提供内置模块联邦配置,并更新插件 Hook 顺序与多项默认行为。\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/zh/blog/v0-4) [2024年1月10日\ \ Rsbuild 0.3 发布\ \ Rsbuild 0.3 发布,支持模块联邦,并调整 TOML/YAML 插件、JavaScript API 与 Node 产物配置。\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/zh/blog/v0-3) [2023年12月11日\ \ Rsbuild 0.2 发布\ \ Rsbuild 0.2 发布,调整 targets、entry 等核心配置,并重构 Babel 插件选项。\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/zh/blog/v0-2) [2023年11月22日\ \ Rsbuild 0.1 发布\ \ Rsbuild 0.1 首次发布,带来基于 Rspack 的高性能构建、开箱即用配置和多框架支持。\ \ ![](https://github.com/chenjiahan.png)![](https://github.com/9aoy.png)\ \ Jiahan Chen, 9aoy](https://rsbuild.rs/zh/blog/v0-1) --- # Server API - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/api/javascript-api/server-api.md. 菜单目录 [#](https://rsbuild.rs/zh/api/javascript-api/server-api#server-api) Server API ============================================================================== 复制 Markdown Rsbuild 提供了面向 dev server 和 preview server 的 server API,可通过配置、插件 hooks 和 JavaScript API 访问。 [#](https://rsbuild.rs/zh/api/javascript-api/server-api#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8) 如何使用 -------------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#%E9%85%8D%E7%BD%AE) 配置 Rsbuild 提供了 [server.setup](https://rsbuild.rs/zh/config/server/setup) 选项,可以访问 dev server 和 preview server 实例。 rsbuild.config.ts export default { server: { setup: ({ server }) => { console.log('the server is ', server); }, }, }; ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#%E6%8F%92%E4%BB%B6-hooks) 插件 hooks 插件作者可通过 [onBeforeStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartdevserver) 和 [onBeforeStartPreviewServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartpreviewserver) 钩子访问 dev server 和 preview server 实例。 const myPlugin = () => ({ setup(api) { api.onBeforeStartDevServer(({ server }) => { console.log('the server is ', server); }); api.onBeforeStartPreviewServer(({ server }) => { console.log('the server is ', server); }); }, }); ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#javascript-api) JavaScript API * 通过 [rsbuild.createDevServer](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildcreatedevserver) 创建 dev server 实例: const server = await rsbuild.createDevServer(); console.log('the dev server is ', server); * 通过 [rsbuild.startDevServer](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildstartdevserver) 获取 dev server 实例: const { server } = await rsbuild.startDevServer(); console.log('the dev server is ', server); 通过 [rsbuild.preview](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildpreview) 获取 preview server 实例: const { server } = await rsbuild.preview(); console.log('the preview server is ', server); [#](https://rsbuild.rs/zh/api/javascript-api/server-api#%E7%A4%BA%E4%BE%8B) 示例 ------------------------------------------------------------------------------ ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#integrate-with-custom-server) 与自定义 server 集成 下面是一个在 [express](https://expressjs.com/) 中集成 Rsbuild dev server 的例子: import { createRsbuild } from '@rsbuild/core'; import express from 'express'; async function startDevServer() { // 初始化 Rsbuild const rsbuild = await createRsbuild({ config: { server: { middlewareMode: true, }, }, }); const app = express(); // 创建 Rsbuild dev server 实例 const rsbuildServer = await rsbuild.createDevServer(); // 使用 Rsbuild 的内置中间件 app.use(rsbuildServer.middlewares); const server = app.listen(rsbuildServer.port, async () => { // 通知 Rsbuild 自定义 Server 已启动 await rsbuildServer.afterListen(); }); // 激活 WebSocket 连接 rsbuildServer.connectWebSocket({ server }); } 更多用法可参考: * [示例代码](https://github.com/rstackjs/rstack-examples/blob/main/rsbuild/express/server.mjs) 。 * [rsbuild.createDevServer](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildcreatedevserver) * [server.middlewareMode](https://rsbuild.rs/zh/config/server/middleware-mode) [#](https://rsbuild.rs/zh/api/javascript-api/server-api#%E5%85%B1%E4%BA%AB-api) 共享 API -------------------------------------------------------------------------------------- 在 dev server 和 preview server 中都可用的公共方法和属性。 ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#close) close * **类型:** `() => Promise` 调用 `close()` 方法来执行必要的清理操作。 在 dev server 中,这还会触发 [onCloseDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onclosedevserver) 钩子。 import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild(); const rsbuildServer = await rsbuild.createDevServer(); await rsbuildServer.close(); ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#httpserver) httpServer * **类型:** `import('node:http').Server | import('node:http2').Http2SecureServer | null` Node.js HTTP 服务实例。 * 如果启用了 [server.https](https://rsbuild.rs/zh/config/server/https) ,则为 `Http2SecureServer`。 * 如果启用了 [server.middlewareMode](https://rsbuild.rs/zh/config/server/middleware-mode) ,则为 `null`。 ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#middlewares) middlewares * **类型:** `Connect.Server` `connect` 实例,可用于向服务器附加自定义中间件。 const rsbuildServer = await rsbuild.createDevServer(); rsbuildServer.middlewares.use((req, res, next) => { if (req.url === '/foo') { res.end('ok'); return; } next(); }); > 查看 [中间件](https://rsbuild.rs/zh/guide/basic/server#middleware) > 了解更多。 ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#open) open * **类型:** `() => Promise` 启动服务器后,在浏览器中打开 URL。 const { server } = await rsbuild.startDevServer(); await server.open(); ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#port) port * **类型:** `number` 解析后的端口号。 默认从 [server.port](https://rsbuild.rs/zh/config/server/port) 开始,如果端口被占用会自动递增并使用可用端口。 const { server } = await rsbuild.startDevServer(); console.log(server.port); ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#printurls) printUrls * **类型:** `() => void` 打印 server URLs。 const { server } = await rsbuild.startDevServer(); server.printUrls(); [#](https://rsbuild.rs/zh/api/javascript-api/server-api#dev-server-api) Dev server API -------------------------------------------------------------------------------------- 仅在 dev server 中可用的方法和属性。 ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#afterlisten) afterListen * **类型:** `() => Promise` 通知 Rsbuild 自定义的开发服务器已成功启动,Rsbuild 将在这个阶段触发 [onAfterStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartdevserver) 钩子。 例如: import express from 'express'; import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild(); const rsbuildServer = await rsbuild.createDevServer(); const app = express(); const server = app.listen(rsbuildServer.port, async () => { await rsbuildServer.afterListen(); }); ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#connectwebsocket) connectWebSocket * **类型:** type ConnectWebSocket = (options: { server: import('node:http').Server | import('node:http2').Http2SecureServer; }) => void; 激活 WebSocket 连接,这确保了 HMR 正常工作。 Rsbuild 内置了 WebSocket 处理器以支持 HMR 功能: 1. 当用户通过浏览器访问页面时,会自动向服务器发起 WebSocket 连接请求。 2. Rsbuild 开发服务器检测到连接请求后,会指示内置的 WebSocket 处理器进行处理。 3. 浏览器与 Rsbuild WebSocket 处理器成功建立连接后,便可进行实时通信。 4. 每次重新编译完成后,Rsbuild WebSocket 处理器会通知浏览器。随后,浏览器向开发服务器发送 `hot-update.(js|json)` 请求,以加载编译后的新模块。 当你使用自定义 server 时,可能会遇到 HMR 连接失败的问题。这是因为自定义 server 未能将 WebSocket 连接请求正确转发至 Rsbuild 的 WebSocket 处理器。此时,你需要调用 `connectWebSocket` 方法来让 Rsbuild 能够接收并处理来自浏览器的 WebSocket 连接请求。 import express from 'express'; import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild(); const rsbuildServer = await rsbuild.createDevServer(); const app = express(); const httpServer = app.listen(rsbuildServer.port); rsbuildServer.connectWebSocket({ server: httpServer }); ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#environments) environments * **类型:** [EnvironmentAPI](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-api) 提供 Rsbuild 的 [environment API](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-api) ,这允许你在服务端获取特定环境下的构建产物信息。 rsbuild.config.ts const rsbuildServer = await rsbuild.createDevServer(); const webStats = await rsbuildServer.environments.web.getStats(); console.log(webStats.toJson({ all: false })); ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#listen) listen * **类型:** `() => Promise<{ port: number; urls: string[]; server: RsbuildDevServer }>` 启动 Rsbuild dev server 并返回监听结果。 使用 [server.middlewareMode](https://rsbuild.rs/zh/config/server/middleware-mode) 时不需要调用该方法。 const rsbuildServer = await rsbuild.createDevServer(); const { port, urls } = await rsbuildServer.listen(); console.log(port, urls); ### [#](https://rsbuild.rs/zh/api/javascript-api/server-api#sockwrite) sockWrite * **类型:** type HotSend = { (type: 'full-reload', data?: { path?: string }): void; (type: 'static-changed'): void; (type: 'custom', data: { event: string; data?: any }): void; }; 向 HMR 客户端传递一些消息,HMR 客户端将根据接收到的消息类型进行不同的处理。 const rsbuildServer = await rsbuild.createDevServer(); if (someCondition) { rsbuildServer.sockWrite('full-reload'); } Tip 不推荐使用 `sockWrite` 作为消息发送 API,建议优先使用 [hot.send](https://rsbuild.rs/zh/api/javascript-api/environment-api#hotsend) 。 --- # Rsbuild - 基于 Rspack 的构建工具 For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/index.md. ![background](https://assets.rspack.rs/rspack/assets/landingpage-background-compressed.png) ![logo](https://assets.rspack.rs/rsbuild/rsbuild-logo.svg) Rsbuild ======= 由 Rspack 驱动的构建工具 在瞬息之间构建你的 Web 应用 快速上手[GitHubGitHub](https://github.com/web-infra-dev/rsbuild) 🚀 基于 Rspack --------- 享受 Rspack 带来的极致开发体验。 🦄 开箱即用 ---- 集成生态中最实用的构建功能。 🎯 框架无关 ---- 支持 React、Vue、Solid、Svelte 等。 🛠️ 深度优化 ---- 自动优化静态资源,最大化生产性能。 🎨 灵活插拔 ---- 提供轻量级插件系统和一系列高质量插件。 🍭 易于配置 ---- 以零配置启动,然后一切皆可配置。 构建极快 ==== 基于 Rust 和 TypeScript 的高度并行、增量编译架构,构建性能极佳,带来极致的开发体验。 Rsbuild 1.36s dev 3.35s build 160ms hmr Vite 6.50s dev 1.98s build 130ms hmr webpack 21.40s dev 28.10s build 2.78s hmr Rstack ====== 高性能、一体化的 JavaScript 工具链,为开发者与 Agent 打造 [![Rspack](https://assets.rspack.rs/rspack/rspack-logo.svg)\ \ Rspack\ \ 基于 Rust 编写的高性能 Web 打包工具,提供现代化的 webpack API\ \ rspack.rs](https://rspack.rs/) [![Rsbuild](https://assets.rspack.rs/rsbuild/rsbuild-logo.svg)\ \ Rsbuild\ \ 基于 Rspack 的现代 Web 构建工具,快速且易于扩展\ \ rsbuild.rs](https://rsbuild.rs/) [![Rslib](https://assets.rspack.rs/rslib/rslib-logo.svg)\ \ Rslib\ \ 基于 Rsbuild 的库开发工具,以简单的方式创建 JavaScript 库和 UI 组件库\ \ rslib.rs](https://rslib.rs/) [![Rspress](https://assets.rspack.rs/rspress/rspress-logo-480x480.png)\ \ Rspress\ \ 基于 Rsbuild 的静态站点生成器,用于创建优雅的文档站点\ \ rspress.rs](https://rspress.rs/) [![Rsdoctor](https://assets.rspack.rs/rsdoctor/rsdoctor-logo-480x480.png)\ \ Rsdoctor\ \ AI 友好的构建分析工具,使构建流程变得透明、可预测和可优化\ \ rsdoctor.rs](https://rsdoctor.rs/) [![Rstest](https://assets.rspack.rs/rstest/rstest-logo.svg)\ \ Rstest\ \ 基于 Rspack 的 JavaScript 测试框架,兼容 Jest API\ \ rstest.rs](https://rstest.rs/) [![Rslint](https://assets.rspack.rs/rslint/rslint-logo.svg)\ \ Rslint\ \ 高性能 JavaScript 和 TypeScript 代码检查工具,兼容 ESLint 生态\ \ rslint.rs](https://rslint.rs/) 指南 -- * [介绍](https://rsbuild.rs/zh/guide/start/) * [快速上手](https://rsbuild.rs/zh/guide/start/quick-start) * [特性](https://rsbuild.rs/zh/guide/start/features) * [迁移](https://rsbuild.rs/zh/guide/migration/webpack) API --- * [命令行工具](https://rsbuild.rs/zh/guide/basic/cli) * [配置](https://rsbuild.rs/zh/guide/configuration/rsbuild) * [插件 API](https://rsbuild.rs/zh/plugins/dev/) * [JavaScript API](https://rsbuild.rs/zh/api/start/) 生态 -- * [Rspack](https://rspack.rs/) * [Rspress](https://rspress.rs/) * [Rsdoctor](https://rsdoctor.rs/) * [Rslib](https://rslib.rs/) * [Rstest](https://rstest.rs/) 社区 -- * [GitHub](https://github.com/web-infra-dev/rsbuild) * [Discord](https://discord.gg/sYK4QjyZ4V) * [Twitter (X)](https://twitter.com/rspack_dev) * [Bluesky](https://bsky.app/profile/rspack.rs) * [Awesome Rstack](https://github.com/rstackjs/awesome-rstack) --- # Plugin list - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/index.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/#plugin-list) Plugin list ============================================================= Copy Markdown [#](https://rsbuild.rs/plugins/list/#plugin-system) Plugin system ----------------------------------------------------------------- You can read about the functionality of Rsbuild plugins and how to develop an Rsbuild plugin in the [Plugin development](https://rsbuild.rs/plugins/dev/) documentation. [#](https://rsbuild.rs/plugins/list/#using-plugins) Using plugins ----------------------------------------------------------------- Register plugins with the [plugins](https://rsbuild.rs/config/plugins) option in Rsbuild config. With Rsbuild's JavaScript API, register plugins with [addPlugins](https://rsbuild.rs/api/javascript-api/instance#rsbuildaddplugins) . [#](https://rsbuild.rs/plugins/list/#official-plugins) Official plugins ----------------------------------------------------------------------- The following are official plugins that can be used in Rsbuild. ### [#](https://rsbuild.rs/plugins/list/#react) React Plugins available for the React: * [@rsbuild/plugin-react](https://rsbuild.rs/plugins/list/plugin-react) : Support for React. * [@rsbuild/plugin-svgr](https://rsbuild.rs/plugins/list/plugin-svgr) : Support convert SVG to React components. * [@rsbuild/plugin-styled-components](https://github.com/rsbuild-contrib/rsbuild-plugin-styled-components) : Provide compile-time support for styled-components. ### [#](https://rsbuild.rs/plugins/list/#vue) Vue Plugins available for the Vue: * [@rsbuild/plugin-vue](https://rsbuild.rs/plugins/list/plugin-vue) : Support for Vue 3 SFC (Single File Components). * [@rsbuild/plugin-vue-jsx](https://github.com/rstackjs/rsbuild-plugin-vue-jsx) : Support for Vue 3 JSX / TSX syntax. * [@rsbuild/plugin-vue2](https://github.com/rstackjs/rsbuild-plugin-vue2) : Support for Vue 2 SFC (Single File Components). * [@rsbuild/plugin-vue2-jsx](https://github.com/rstackjs/rsbuild-plugin-vue2-jsx) : Support for Vue 2 JSX / TSX syntax. ### [#](https://rsbuild.rs/plugins/list/#preact) Preact Plugins available for the Preact: * [@rsbuild/plugin-preact](https://rsbuild.rs/plugins/list/plugin-preact) : Support for Preact. ### [#](https://rsbuild.rs/plugins/list/#svelte) Svelte Plugins available for the Svelte: * [@rsbuild/plugin-svelte](https://rsbuild.rs/plugins/list/plugin-svelte) : Support for Svelte components (`.svelte` files). ### [#](https://rsbuild.rs/plugins/list/#solid) Solid Plugins available for the Solid: * [@rsbuild/plugin-solid](https://rsbuild.rs/plugins/list/plugin-solid) : Support for Solid. ### [#](https://rsbuild.rs/plugins/list/#common) Common The following are common framework-agnostic plugins: * [@rsbuild/plugin-assets-retry](https://github.com/rstackjs/rsbuild-plugin-assets-retry) : Used to automatically resend requests when static assets fail to load. * [@rsbuild/plugin-babel](https://rsbuild.rs/plugins/list/plugin-babel) : Support for Babel transpilation capabilities. * [@rsbuild/plugin-tailwindcss](https://rsbuild.rs/plugins/list/plugin-tailwindcss) : Use Tailwind CSS v4. * [@rsbuild/plugin-sass](https://rsbuild.rs/plugins/list/plugin-sass) : Use Sass as the CSS preprocessor. * [@rsbuild/plugin-less](https://rsbuild.rs/plugins/list/plugin-less) : Use Less as the CSS preprocessor. * [@rsbuild/plugin-basic-ssl](https://github.com/rstackjs/rsbuild-plugin-basic-ssl) : Generate an untrusted, self-signed certificate for the HTTPS server. * [@rsbuild/plugin-eslint](https://github.com/rstackjs/rsbuild-plugin-eslint) : Run ESLint checks during the compilation. * [@rsbuild/plugin-type-check](https://github.com/rstackjs/rsbuild-plugin-type-check) : Run TypeScript type checker on a separate process. * [@rsbuild/plugin-image-compress](https://github.com/rstackjs/rsbuild-plugin-image-compress) : Compress the image assets. * [@rsbuild/plugin-mdx](https://github.com/rstackjs/rsbuild-plugin-mdx) : Provide support for MDX. * [@rsbuild/plugin-node-polyfill](https://github.com/rstackjs/rsbuild-plugin-node-polyfill) : Used to inject polyfills of Node core modules in the browser side. * [@rsbuild/plugin-source-build](https://github.com/rstackjs/rsbuild-plugin-source-build) : This plugin is designed for the monorepo scenario. It supports referencing source code from other subdirectories and performs build and hot update. * [@rsbuild/plugin-check-syntax](https://github.com/rstackjs/rsbuild-plugin-check-syntax) : Check the syntax compatibility of output files and determine if there are any advanced syntaxes that could cause compatibility issues. * [@rsbuild/plugin-css-minimizer](https://github.com/rstackjs/rsbuild-plugin-css-minimizer) : Customize the CSS minimizer, switching to [cssnano](https://github.com/cssnano/cssnano) or other tools for CSS compression. * [@rsbuild/plugin-typed-css-modules](https://github.com/rstackjs/rsbuild-plugin-typed-css-modules) : Generate TypeScript declaration file for CSS Modules. * [@rsbuild/plugin-pug](https://github.com/rstackjs/rsbuild-plugin-pug) : Support for the Pug template engine. * [@rsbuild/plugin-rem](https://github.com/rstackjs/rsbuild-plugin-rem) : Implements the rem adaptive layout for mobile pages. * [@rsbuild/plugin-umd](https://github.com/rstackjs/rsbuild-plugin-umd) : Generate outputs in UMD format. * [@rsbuild/plugin-yaml](https://github.com/rstackjs/rsbuild-plugin-yaml) : Import YAML files and convert them into JavaScript objects. * [@rsbuild/plugin-toml](https://github.com/rstackjs/rsbuild-plugin-toml) : Import TOML files and convert them into JavaScript objects. Tip You can find the source code of all official plugins in [web-infra-dev/rsbuild](https://github.com/web-infra-dev/rsbuild) and [rstackjs](https://github.com/rstackjs) . [#](https://rsbuild.rs/plugins/list/#community-plugins) Community plugins ------------------------------------------------------------------------- You can check out the Rsbuild plugins provided by the community at [awesome-rstack - Rsbuild Plugins](https://github.com/rstackjs/awesome-rstack#rsbuild-plugins) . You can also discover more Rsbuild plugins on npm by searching for the keyword [rsbuild-plugin](https://npmjs.com/search?q=rsbuild-plugin&ranking=popularity) . ### [#](https://rsbuild.rs/plugins/list/#react-1) React * [rsbuild-plugin-react-router](https://github.com/rstackjs/rsbuild-plugin-react-router) : Provides seamless integration with React Router. ### [#](https://rsbuild.rs/plugins/list/#angular) Angular * [@ng-rsbuild/plugin-angular](https://github.com/nrwl/angular-rspack) : Allows you to build Angular applications easily. --- # Preact plugin - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/plugin-preact.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/plugin-preact#preact-plugin) Preact plugin ============================================================================== Copy Markdown [Source Code](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-preact) The Preact plugin provides support for Preact, integrating features such as JSX compilation and React aliasing. [#](https://rsbuild.rs/plugins/list/plugin-preact#quick-start) Quick start -------------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-preact#install-plugin) Install plugin Run the following command: npm yarn pnpm bun deno npm add @rsbuild/plugin-preact -D yarn add @rsbuild/plugin-preact -D pnpm add @rsbuild/plugin-preact -D bun add @rsbuild/plugin-preact -D deno add npm:@rsbuild/plugin-preact -D Tip `@rsbuild/plugin-preact` v2 no longer supports Rsbuild 1.x. If your project uses Rsbuild 1.x, install `@rsbuild/plugin-preact@1` instead. ### [#](https://rsbuild.rs/plugins/list/plugin-preact#register-plugin) Register plugin Register the plugin in Rsbuild config: rsbuild.config.ts import { pluginPreact } from '@rsbuild/plugin-preact'; export default { plugins: [pluginPreact()], }; After registration, you can develop Preact directly. [#](https://rsbuild.rs/plugins/list/plugin-preact#options) Options ------------------------------------------------------------------ ### [#](https://rsbuild.rs/plugins/list/plugin-preact#reactaliasesenabled) reactAliasesEnabled Whether to aliases `react`, `react-dom` to `preact/compat`. * **Type:** `boolean` * **Default:** `true` * **Example:** Disable aliases. pluginPreact({ reactAliasesEnabled: false, }); ### [#](https://rsbuild.rs/plugins/list/plugin-preact#prefreshenabled) prefreshEnabled Whether to inject [Prefresh](https://github.com/preactjs/prefresh) for HMR. * **Type:** `boolean` * **Default:** `true` * **Version:** `>= v1.1.0` * **Example:** Disable Prefresh. pluginPreact({ prefreshEnabled: false, }); ### [#](https://rsbuild.rs/plugins/list/plugin-preact#preactrefreshoptions) preactRefreshOptions Set the options for [@rspack/plugin-preact-refresh](https://github.com/rstackjs/rspack-plugin-preact-refresh) . The value is passed to the Rspack plugin, and `preactPath` is automatically configured by Rsbuild. * **Type:** type PreactRefreshOptions = { // @link https://rspack.rs/config/module-rules#condition test?: Rspack.RuleSetCondition; include?: Rspack.RuleSetCondition | null; exclude?: Rspack.RuleSetCondition | null; overlay?: { module: string; }; }; * **Default:** The default value is the same as `@rspack/plugin-preact-refresh`: const defaultOptions = { test: /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, exclude: /[\\/]node_modules[\\/]/, }; * **Example:** pluginPreact({ preactRefreshOptions: { test: /\.(?:jsx|tsx)$/, include: /src/, exclude: /node_modules/, }, }); --- # Svelte plugin - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/plugin-svelte.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/plugin-svelte#svelte-plugin) Svelte plugin ============================================================================== Copy Markdown [Source Code](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-svelte) The Svelte plugin provides support for Svelte components (`.svelte` files). The plugin internally integrates [svelte-loader](https://github.com/sveltejs/svelte-loader) . [#](https://rsbuild.rs/plugins/list/plugin-svelte#quick-start) Quick start -------------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-svelte#install-plugin) Install plugin Run the following command: npm yarn pnpm bun deno npm add @rsbuild/plugin-svelte -D yarn add @rsbuild/plugin-svelte -D pnpm add @rsbuild/plugin-svelte -D bun add @rsbuild/plugin-svelte -D deno add npm:@rsbuild/plugin-svelte -D Tip `@rsbuild/plugin-svelte` v2 no longer supports Rsbuild 1.x or Svelte 4.x. If your project uses these versions, install `@rsbuild/plugin-svelte@1` instead. ### [#](https://rsbuild.rs/plugins/list/plugin-svelte#register-plugin) Register plugin Register the plugin in Rsbuild config: rsbuild.config.ts import { pluginSvelte } from '@rsbuild/plugin-svelte'; export default { plugins: [pluginSvelte()], }; After registration, you can import `*.svelte` files in your code. [#](https://rsbuild.rs/plugins/list/plugin-svelte#options) Options ------------------------------------------------------------------ To customize the compilation behavior of Svelte, use the following options. ### [#](https://rsbuild.rs/plugins/list/plugin-svelte#svelteloaderoptions) svelteLoaderOptions These options are passed to `svelte-loader`. For details, see the [svelte-loader documentation](https://github.com/sveltejs/svelte-loader) . * **Type:** `SvelteLoaderOptions` * **Default:** const defaultOptions = { compilerOptions: { dev: isDev, }, preprocess: require('svelte-preprocess')(), emitCss: isProd && !rsbuildConfig.output.injectStyles, hotReload: isDev && rsbuildConfig.dev.hmr, }; * **Example:** pluginSvelte({ svelteLoaderOptions: { preprocess: null, }, }); ### [#](https://rsbuild.rs/plugins/list/plugin-svelte#preprocessoptions) preprocessOptions These options are passed to `svelte-preprocess`. For details, see the [svelte-preprocess documentation](https://github.com/sveltejs/svelte-preprocess/blob/c2107e529da9438ea5b8060aa471119940896e40/docs/preprocessing.md) . * **Type:** `AutoPreprocessOptions` * **Default:** `undefined` interface AutoPreprocessOptions { globalStyle: { ... }, replace: { ... }, typescript: { ... }, scss: { ... }, sass: { ... }, less: { ... }, stylus: { ... }, babel: { ... }, postcss: { ... }, coffeescript: { ... }, pug: { ... }, } * **Example:** pluginSvelte({ preprocessOptions: { aliases: [\ ['potato', 'potatoLanguage'],\ ['pot', 'potatoLanguage'],\ ], /** Add a custom language preprocessor */ potatoLanguage({ content, filename, attributes }) { const { code, map } = require('potato-language').render(content); return { code, map }; }, }, }); [#](https://rsbuild.rs/plugins/list/plugin-svelte#notes) Notes -------------------------------------------------------------- Currently, `svelte-loader` does not support HMR for Svelte v5, see [svelte-loader - Hot Reload](https://github.com/sveltejs/svelte-loader#hot-reload) . ### [#](https://rsbuild.rs/plugins/list/plugin-svelte#alias-handling-in-lesssass) Alias handling in Less/Sass When using aliases to import Less or Sass files within Svelte components, you need to manually configure the preprocessor to handle alias resolution. Otherwise, you may encounter `"file not found"` errors. * **Example:** rsbuild.config.ts import { pluginSvelte } from '@rsbuild/plugin-svelte'; export default { plugins: [\ pluginSvelte({\ preprocessOptions: {\ scss: {\ importer: [\ // Handle alias imports for SCSS files\ (url, prev) => {\ if (url.startsWith('@/')) {\ return { file: url.replace('@/', 'src/') };\ }\ return null;\ },\ ],\ },\ less: {\ // recommend simple alias handling for Less files\ replace: [['@/style', 'style']],\ // use less plugin to handle alias imports\ plugins: [],\ },\ },\ }),\ ], }; This ensures that alias imports like `@import '@/styles/variables.scss'` or `@import '@/styles/variables.less'` are properly resolved within Svelte components. --- # Less plugin - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/plugin-less.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/plugin-less#less-plugin) Less plugin ======================================================================== Copy Markdown [Source Code](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-less) Use [Less](https://lesscss.org/) as the CSS preprocessor, implemented based on [less-loader](https://github.com/webpack/less-loader) . [#](https://rsbuild.rs/plugins/list/plugin-less#quick-start) Quick start ------------------------------------------------------------------------ ### [#](https://rsbuild.rs/plugins/list/plugin-less#install-plugin) Install plugin Run the following command: npm yarn pnpm bun deno npm add @rsbuild/plugin-less -D yarn add @rsbuild/plugin-less -D pnpm add @rsbuild/plugin-less -D bun add @rsbuild/plugin-less -D deno add npm:@rsbuild/plugin-less -D ### [#](https://rsbuild.rs/plugins/list/plugin-less#register-plugin) Register plugin Register the plugin in Rsbuild config: rsbuild.config.ts import { pluginLess } from '@rsbuild/plugin-less'; export default { plugins: [pluginLess()], }; After registration, you can import `*.less` or `*.module.less` files without additional config. [#](https://rsbuild.rs/plugins/list/plugin-less#options) Options ---------------------------------------------------------------- To customize the compilation behavior of Less, use the following options. ### [#](https://rsbuild.rs/plugins/list/plugin-less#lessloaderoptions) lessLoaderOptions You can modify the config of [less-loader](https://github.com/webpack/less-loader) via `lessLoaderOptions`. * **Type:** `Object | Function` * **Default:** const defaultOptions = { lessOptions: { javascriptEnabled: true, paths: [path.join(rootPath, 'node_modules')], }, sourceMap: false, // Controlled by output.sourceMap }; * **Example:** If `lessLoaderOptions` is an object, 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. pluginLess({ lessLoaderOptions: { lessOptions: { javascriptEnabled: false, }, }, }); If `lessLoaderOptions` is a function, the default config is passed as the first parameter, which can be directly modified or returned as the final result. pluginLess({ lessLoaderOptions(config) { config.lessOptions = { javascriptEnabled: false, }; }, }); Tip The `lessLoaderOptions.lessOptions` config is passed to Less. See the [Less documentation](https://lesscss.org/usage/#less-options) for all available options. ### [#](https://rsbuild.rs/plugins/list/plugin-less#include) include * **Type:** [Rspack.RuleSetCondition](https://rspack.rs/config/module-rules#condition) * **Default:** `/\.less$/` * **Version:** `>= 1.1.0` Include some `.less` files, they will be transformed by `less-loader`. The value is the same as the [rules\[\].test](https://rspack.rs/config/module-rules#rulestest) option in Rspack. For example: pluginLess({ include: /\.custom\.less$/, }); ### [#](https://rsbuild.rs/plugins/list/plugin-less#exclude) exclude * **Type:** [Rspack.RuleSetCondition](https://rspack.rs/config/module-rules#condition) * **Default:** `undefined` Exclude some `.less` files, they will not be transformed by `less-loader`. For example: pluginLess({ exclude: /some-folder[\\/]foo\.less/, }); ### [#](https://rsbuild.rs/plugins/list/plugin-less#parallel) parallel * **Type:** `boolean` * **Default:** `false` * **Version:** Added in v1.4.0 Whether to compile Less modules in parallel using worker threads. When enabled, Less modules are processed across multiple worker threads, reducing pressure on the main thread and improving overall build performance when compiling large numbers of Less modules. pluginLess({ parallel: true, }); > This feature is based on Rspack's parallel loader. Options transferred to worker threads must comply with the [HTML structured clone algorithm](https://nodejs.org/api/worker_threads.html#portpostmessagevalue-transferlist) > . Otherwise, transmission will fail. For example, functions cannot be passed as options. See [Rspack - Rule.use.parallel](https://rspack.rs/config/module-rules#rulesuseparallel) > for more details. [#](https://rsbuild.rs/plugins/list/plugin-less#modifying-less-version) 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`. pluginLess({ lessLoaderOptions: { implementation: require('less'), }, }); [#](https://rsbuild.rs/plugins/list/plugin-less#practices) Practices -------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-less#configure-multiple-less-plugins) Configure multiple Less plugins By using the `include` and `exclude` options, you can register multiple Less plugins and specify different options for each plugin. For example: export default { plugins: [\ pluginLess({\ exclude: /\.another\.less$/,\ }),\ pluginLess({\ include: /\.another\.less$/,\ lessLoaderOptions: {\ // some custom options\ },\ }),\ ], }; [#](https://rsbuild.rs/plugins/list/plugin-less#faq) FAQ -------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-less#division-in-less-file-does-not-work) Division in Less file does not work? The built-in Less version for `@rsbuild/plugin-less` is v4. Compared to v3, there are some differences in the division syntax in Less v4: // Less v3 .math { width: 2px / 2; // 1px width: 2px ./ 2; // 1px width: (2px / 2); // 1px } // Less v4 .math { width: 2px / 2; // 2px / 2 width: 2px ./ 2; // 1px width: (2px / 2); // 1px } The division syntax in Less can be modified through configuration. For more details, see [Less - Math](https://lesscss.org/usage/#less-options-math) . --- # Environment API - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/api/javascript-api/environment-api.md. 菜单目录 [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-api) Environment API ============================================================================================= 复制 Markdown 在这里你可以找到所有与 environment 相关的 API。 > 参考 [多环境构建](https://rsbuild.rs/zh/guide/advanced/environments) > 了解更多。 [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-context) Environment context ----------------------------------------------------------------------------------------------------- Environment context 是一个只读对象,提供一些和当前 environment 有关的上下文信息。 * **类型:** type EnvironmentContext = { index: number; name: string; browserslist: string[]; config: NormalizedEnvironmentConfig; distPath: string; entry: RsbuildEntry; htmlPaths: Record; tsconfigPath?: string; manifest?: Record | ManifestData; webSocketToken: string; }; Environment context 可以通过以下方式获取: 1. 在 Rsbuild 的 [插件 hooks](https://rsbuild.rs/zh/plugins/dev/hooks#plugin-hooks) 中,你可以通过 `environment` 或 `environments` 入参获取 environment context 对象。 2. 在 [Environment API](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-api-1) 中,可以通过 `environments[name].context` 获取。 ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#index) index 当前 environment 从零开始的索引。 * **类型:** `number` ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#name) name 当前环境的唯一名称,用于区分和定位环境,对应于 [environments](https://rsbuild.rs/zh/config/environments) 配置中的 key。 * **类型:** `string` * **示例:** api.modifyRspackConfig((config, { environment }) => { if (environment.name === 'node') { // modify config for node environment } return config; }); ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#browserslist) browserslist 当前环境设置的目标浏览器范围。详见 [浏览器范围](https://rsbuild.rs/zh/guide/advanced/browserslist) 。 * **类型:** `string[]` * **示例:** api.modifyRspackConfig((config, { environment }) => { console.log(environment.browserslist); return config; }); ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#config) config 当前环境使用的 Rsbuild 配置(已经过规范化处理)。 * **类型:** type NormalizedEnvironmentConfig = TwoLevelReadonly<{ mode: RsbuildMode; root: string; dev: NormalizedDevConfig; server: NormalizedServerConfig; html: NormalizedHtmlConfig; tools: NormalizedToolsConfig; resolve: NormalizedResolveConfig; source: NormalizedSourceConfig; output: NormalizedOutputConfig; plugins?: RsbuildPlugins; security: NormalizedSecurityConfig; performance: NormalizedPerformanceConfig; splitChunks: NormalizedSplitChunksConfig | false; moduleFederation?: ModuleFederationConfig; }>; * **示例:** api.modifyRspackConfig((config, { environment }) => { // Rspack console.log(config); // Rsbuild config for current environment console.log(environment.config); return config; }); ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#distpath) distPath 构建产物输出目录的绝对路径,对应 Rsbuild 的 [output.distPath.root](https://rsbuild.rs/zh/config/output/dist-path) 配置项。 * **类型:** `string` * **示例:** api.modifyRspackConfig((config, { environment }) => { console.log(environment.distPath); return config; }); ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#entry) entry 构建入口对象,对应 [source.entry](https://rsbuild.rs/zh/config/source/entry) 选项。 * **类型:** type RsbuildEntry = Record; * **示例:** api.modifyRspackConfig((config, { environment }) => { console.log(environment.entry); return config; }); ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#htmlpaths) htmlPaths HTML 产物的路径信息。 这个值是一个对象,对象的 key 为 entry 名称,value 为 HTML 文件在产物目录下的相对路径。 * **类型:** type htmlPaths = Record; * **示例:** api.modifyRspackConfig((config, { environment }) => { console.log(environment.htmlPaths); return config; }); ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#tsconfigpath) tsconfigPath tsconfig.json 文件的绝对路径,若项目中不存在 tsconfig.json 文件,则为 `undefined`。 * **类型:** type TsconfigPath = string | undefined; * **示例:** api.modifyRspackConfig((config, { environment }) => { console.log(environment.tsconfigPath); return config; }); ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#manifest) manifest manifest 文件数据。仅在 [output.manifest](https://rsbuild.rs/zh/config/output/manifest) 配置被启用时才能访问。 * **类型:** `Record | ManifestData | undefined` * **示例:** api.onAfterBuild(({ environments }) => { // Get the manifest data of web environment console.log(environments.web.manifest); }); api.onAfterDevCompile(({ environments }) => { console.log(environments.web.manifest); }); api.onAfterEnvironmentCompile(({ environment }) => { console.log(environment.manifest); }); manifest 数据仅在构建完成后才能被访问,你可以在以下 hooks 中访问: * [onAfterBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onafterbuild) * [onAfterEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterenvironmentcompile) * [onCloseBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onclosebuild) * [onCloseDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onclosedevserver) * [onAfterDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterdevcompile) * [onExit](https://rsbuild.rs/zh/plugins/dev/hooks#onexit) ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#websockettoken) webSocketToken WebSocket 认证 token,用于认证 WebSocket 连接,防止未授权访问。 当 Rsbuild 执行 `dev` action 时,该字段包含一个 token;执行其他 action 时为空字符串。 * **类型:** `string` * **版本:** 添加于 v1.4.4 当你需要在浏览器中建立与 Rsbuild dev server 的 WebSocket 连接时,需要使用这个 token 作为 query 参数。 const { webSocketToken } = environments.web.context; const webSocketUrl = `ws://localhost:${port}${pathname}?token=${webSocketToken}`; [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-api-1) Environment API ----------------------------------------------------------------------------------------------- Environment API 提供一些与多环境构建相关的 API。 你可以通过 [rsbuild.createDevServer()](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildcreatedevserver) 或 [server.setup](https://rsbuild.rs/zh/config/server/setup) 使用 environment API,这允许你在服务端获取特定环境下的构建产物信息。 type EnvironmentAPI = { [name: string]: { context: EnvironmentContext; getStats: () => Promise; loadBundle: (entryName: string) => Promise; getTransformedHtml: (entryName: string) => Promise; hot: { send: HotSend; }; }; }; ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#context) context 你可以通过 Environment API 获取和当前环境有关的上下文信息。 * **类型:** [EnvironmentContext](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-context) * **示例:** const webManifest = environments.web.context.manifest; console.log(webManifest.entries); ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#getstats) getStats 获取当前环境的产物信息。 * **类型:** type GetStats = () => Promise; * **示例:** const webStats = await environments.web.getStats(); console.log(webStats.toJson({ all: false })); ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#loadbundle) loadBundle 用于在服务端加载并执行构建产物。调用该方法后,会返回指定入口模块导出的内容,通常用于在服务端环境中运行由 Rsbuild 构建生成的产物。 `loadBundle` 会在构建完成且 [onAfterDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterdevcompile) hook 执行结束后返回结果。因此,无法在 `onAfterDevCompile` hook 内调用 `loadBundle`。 * **类型:** /** * @param entryName - 入口名称,和 Rsbuild `source.entry` 的某一个 key 值对应 * @returns 入口模块的返回值 */ type LoadBundle = (entryName: string) => Promise; * **示例:** // 加载 `main` 入口的 bundle const result = await environments.node.loadBundle('main'); ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#gettransformedhtml) getTransformedHtml 获取经过编译和转换后的 HTML 模版内容。 * **类型:** type GetTransformedHtml = (entryName: string) => Promise; * **示例:** // 获取 main 入口的 HTML 内容 const html = await environments.web.getTransformedHtml('main'); 该方法会返回完整的 HTML 字符串,包含了所有通过 HTML 插件注入的资源和内容。 ### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#hotsend) hot.send 向当前 environment 对应的客户端发送 HMR 消息。 它和 [server.sockWrite](https://rsbuild.rs/zh/api/javascript-api/server-api#sockwrite) 的行为一致,区别是只会影响当前匹配的 environment。 * **类型:** type HotSend = { (type: 'full-reload', data?: { path?: string }): void; (type: 'static-changed'): void; (type: 'custom', data: { event: string; data?: any }): void; }; #### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#full-reload) full-reload 如果你发送一个 `'full-reload'` 的消息,页面将会重新加载。 if (someCondition) { environments.web.hot.send('full-reload'); } 当传入 `path` 且它以 `.html` 结尾时,Rsbuild 只会重新加载当前 environment 中 URL 与该 HTML 路径匹配的页面。 当 `path` 为 `'*'` 时,Rsbuild 会重新加载当前 environment 中的所有页面。 HTML 路径应当相对于 dev server 根路径,并且不应包含 `server.base`。 environments.web.hot.send('full-reload', { path: '/foo.html', }); > `'static-changed'` 是 `'full-reload'` 的一个别名。 #### [#](https://rsbuild.rs/zh/api/javascript-api/environment-api#custom) custom 你也可以通过 `custom` 类型向浏览器发送自定义消息,并携带可选的 data,然后通过 HMR 事件进行处理: environments.web.hot.send('custom', { event: 'count', data: { value: 1 }, }); Rsbuild 在 Rspack 的 [import.meta.webpackHot](https://rspack.rs/api/runtime-api/hmr) 对象上扩展了 `on()` 方法,它允许你在浏览器端监听自定义事件,并处理数据: client.js if (import.meta.webpackHot) { import.meta.webpackHot.on('count', (data) => { console.log('count update', data.value); }); import.meta.webpackHot.accept(); } --- # Vue plugin - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/plugin-vue.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/plugin-vue#vue-plugin) Vue plugin ===================================================================== Copy Markdown [Source Code](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-vue) The Vue plugin provides support for Vue 3 SFC (Single File Components). The plugin internally integrates [rspack-vue-loader](https://npmjs.com/package/rspack-vue-loader) . Tip For Vue 3 JSX / TSX syntax, please use the [Vue JSX plugin](https://github.com/rstackjs/rsbuild-plugin-vue-jsx) . [#](https://rsbuild.rs/plugins/list/plugin-vue#quick-start) Quick start ----------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-vue#install-plugin) Install plugin Run the following command: npm yarn pnpm bun deno npm add @rsbuild/plugin-vue -D yarn add @rsbuild/plugin-vue -D pnpm add @rsbuild/plugin-vue -D bun add @rsbuild/plugin-vue -D deno add npm:@rsbuild/plugin-vue -D ### [#](https://rsbuild.rs/plugins/list/plugin-vue#register-plugin) Register plugin Register the plugin in Rsbuild config: rsbuild.config.ts import { pluginVue } from '@rsbuild/plugin-vue'; export default { plugins: [pluginVue()], }; After registration, you can import `*.vue` SFC files in your code. [#](https://rsbuild.rs/plugins/list/plugin-vue#options) Options --------------------------------------------------------------- Customize Vue compilation behavior with these options: ### [#](https://rsbuild.rs/plugins/list/plugin-vue#vueloaderoptions) vueLoaderOptions Options passed to `rspack-vue-loader`. See the [Vue Loader documentation](https://vue-loader.vuejs.org/) for detailed usage. * **Type:** `VueLoaderOptions` * **Default:** const emitCss = config.output.emitCss ?? config.output.target === 'web'; const defaultOptions = { compilerOptions: { preserveWhitespace: false, }, experimentalInlineMatchResource: emitCss, }; * **Example:** pluginVue({ vueLoaderOptions: { hotReload: false, }, }); ### [#](https://rsbuild.rs/plugins/list/plugin-vue#splitchunks) splitChunks When using Rsbuild's [default split chunks preset](https://rsbuild.rs/config/split-chunks#default) , this plugin splits `vue` and `router` related packages into separate chunks: * `lib-vue.js`: includes `vue`, `rspack-vue-loader`, and their sub-dependencies (`@vue/shared`, `@vue/reactivity`, `@vue/runtime-dom`, `@vue/runtime-core`). * `lib-router.js`: includes `vue-router`. This option is used to control this behavior and determine whether the `vue` and `router` related packages need to be split into separate chunks. * **Type:** type SplitVueChunkOptions = { vue?: boolean; router?: boolean; }; * **Default:** const defaultOptions = { vue: true, router: true, }; * **Example:** pluginVue({ splitChunks: { vue: false, router: false, }, }); ### [#](https://rsbuild.rs/plugins/list/plugin-vue#test) test Customize the matching rule for Vue Single File Components (SFC). * **Type:** [Rspack.RuleSetCondition](https://rspack.rs/config/module-rules#condition) * **Default:** `/\.vue$/` * **Version:** `>= 1.2.1` This option allows you to extend the Vue plugin to handle additional file types. For example, you can first use a plugin or loader to transform `.md` files into Vue components, then configure the `test` option in the Vue plugin to match both `.vue` and `.md` files: pluginVue({ test: /\.(vue|md)$/, }); [#](https://rsbuild.rs/plugins/list/plugin-vue#faq) FAQ ------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-vue#deep-selector-causes-compilation-error) /deep/ selector causes compilation error `/deep/` is a deprecated usage as of Vue v2.7. Since it is not a valid CSS syntax, CSS compilation tools like Lightning CSS will fail to compile it. You can use `:deep()` instead. See [Vue - Deep Selectors](https://vuejs.org/api/sfc-css-features.html#deep-selectors) for more details. > You can also refer to [Vue - RFC 0023](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0023-scoped-styles-changes.md) > for more details. --- # Sass plugin - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/plugin-sass.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/plugin-sass#sass-plugin) Sass plugin ======================================================================== Copy Markdown [Source Code](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-sass) Use [Sass](https://sass-lang.com/) as the CSS preprocessor, implemented based on [sass-loader](https://github.com/webpack/sass-loader) . [#](https://rsbuild.rs/plugins/list/plugin-sass#quick-start) Quick start ------------------------------------------------------------------------ ### [#](https://rsbuild.rs/plugins/list/plugin-sass#install-plugin) Install plugin Run the following command: npm yarn pnpm bun deno npm add @rsbuild/plugin-sass -D yarn add @rsbuild/plugin-sass -D pnpm add @rsbuild/plugin-sass -D bun add @rsbuild/plugin-sass -D deno add npm:@rsbuild/plugin-sass -D Tip * The Sass plugin only supports @rsbuild/core versions >= 0.7.0. * If the @rsbuild/core version is lower than 0.7.0, it has built-in support for the Sass plugin; you don't need to install it. ### [#](https://rsbuild.rs/plugins/list/plugin-sass#register-plugin) Register plugin Register the plugin in Rsbuild config: rsbuild.config.ts import { pluginSass } from '@rsbuild/plugin-sass'; export default { plugins: [pluginSass()], }; After registration, you can import `*.scss`, `*.sass`, `*.module.scss`, or `*.module.sass` files without additional config. [#](https://rsbuild.rs/plugins/list/plugin-sass#options) Options ---------------------------------------------------------------- To customize the compilation behavior of Sass, use the following options. ### [#](https://rsbuild.rs/plugins/list/plugin-sass#sassloaderoptions) sassLoaderOptions Modify the config of [sass-loader](https://github.com/webpack/sass-loader) . * **Type:** `Object | Function` * **Default:** Uses `sass-embedded` with the modern compiler API and suppresses dependency and import deprecation warnings. * **Example:** If `sassLoaderOptions` is an object, it is merged with the default config through `Object.assign`. It should be noted that `sassOptions` is merged through deepMerge in a deep way. pluginSass({ sassLoaderOptions: { sourceMap: true, }, }); If `sassLoaderOptions` is a function, the default config is passed as the first parameter, which can be directly modified or returned as the final result. pluginSass({ sassLoaderOptions(config) { config.additionalData = async (content, loaderContext) => { // ... }; }, }); ### [#](https://rsbuild.rs/plugins/list/plugin-sass#include) include * **Type:** [Rspack.RuleSetCondition](https://rspack.rs/config/module-rules#condition) * **Default:** `/\.s(?:a|c)ss$/` * **Version:** `>= 1.1.0` Include some `.scss` or `.sass` files, they will be transformed by `sass-loader`. The value is the same as the [rules\[\].test](https://rspack.rs/config/module-rules#rulestest) option in Rspack. For example: pluginSass({ include: /\.custom\.scss$/, }); ### [#](https://rsbuild.rs/plugins/list/plugin-sass#exclude) exclude * **Type:** [Rspack.RuleSetCondition](https://rspack.rs/config/module-rules#condition) * **Default:** `undefined` Exclude some `.sass` or `.scss` files, they will not be transformed by `sass-loader`. For example: pluginSass({ exclude: /some-folder[\\/]foo\.scss/, }); ### [#](https://rsbuild.rs/plugins/list/plugin-sass#rewriteurls) rewriteUrls * **Type:** `boolean` * **Default:** `true` * **Version:** `>= 1.2.0` Whether to use [resolve-url-loader](https://github.com/bholloway/resolve-url-loader/tree/v5/packages/resolve-url-loader) to rewrite URLs. When enabled, `resolve-url-loader` allows you to write relative URLs in your Sass files that are correctly resolved from the current Sass file's location, rather than being relative to the Sass entry file (e.g. `main.scss`). If you set this option to `false`, the build performance will be improved, but Rsbuild will use the native URL resolution of Sass, which means all URLs must be relative to the Sass entry file. pluginSass({ rewriteUrls: false, }); [#](https://rsbuild.rs/plugins/list/plugin-sass#practices) Practices -------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-sass#modify-sass-implementation) Modify Sass implementation Sass provides several implementations, including [sass](https://npmjs.com/package/sass) , [sass-embedded](https://npmjs.com/package/sass-embedded) , and [node-sass](https://npmjs.com/package/node-sass) . Rsbuild uses the latest `sass-embedded` implementation by default. `sass-embedded` is a JavaScript wrapper around the native Dart Sass executable, providing a consistent API and optimal performance. To use a different Sass implementation instead of the built-in `sass-embedded` included in Rsbuild, install the preferred Sass implementation in your project and specify it using the `sass-loader`'s [implementation](https://github.com/webpack/sass-loader#implementation) option. pluginSass({ sassLoaderOptions: { implementation: require.resolve('sass'), }, }); Tip Switching from `sass-embedded` to another Sass implementation can significantly decrease build performance. ### [#](https://rsbuild.rs/plugins/list/plugin-sass#select-sass-api) Select Sass API Rsbuild uses the latest `modern-compiler` API by default. If you rely on the `legacy` API of Sass, you can set the `api` option of the sass-loader to `legacy` to maintain compatibility with some deprecated Sass syntax. pluginSass({ sassLoaderOptions: { api: 'legacy', }, }); Tip Sass's `legacy` API has been deprecated and will be removed in Sass 2.0. We recommend migrating to the `modern-compiler` API. For more details, see [Sass - Legacy JS API](https://sass-lang.com/documentation/breaking-changes/legacy-js-api/) . ### [#](https://rsbuild.rs/plugins/list/plugin-sass#ignore-sass-deprecation-warnings) Ignore Sass deprecation warnings Sass uses warning logs to highlight deprecated patterns that will be removed in future major releases. We recommend updating your code according to these warnings. If you do not want to see them, you can ignore the warnings by using the [silenceDeprecations](https://sass-lang.com/documentation/js-api/interfaces/stringoptions/#silenceDeprecations) option in Sass. For example, `@import` has been deprecated in Sass. If you use this syntax, Sass will output the following prompt: Sass @import rules are deprecated and will be removed in Dart Sass 3.0.0. More info and automated migrator: https://sass-lang.com/d/import 0 | @import './b.scss'; `@rsbuild/plugin-sass` adds the following configuration by default to silence the `@import` warning, if you need to silence other deprecated warnings, you can use the same method. pluginSass({ sassLoaderOptions: { sassOptions: { silenceDeprecations: ['import'], }, }, }); > For more information, see [Sass Deprecations](https://sass-lang.com/documentation/js-api/interfaces/deprecations/) > . ### [#](https://rsbuild.rs/plugins/list/plugin-sass#configure-multiple-sass-plugins) Configure multiple Sass plugins By using the `include` and `exclude` options, you can register multiple Sass plugins and specify different options for each plugin. For example: export default { plugins: [\ pluginSass({\ exclude: /\.another\.scss$/,\ }),\ pluginSass({\ include: /\.another\.scss$/,\ sassLoaderOptions: {\ // some custom options\ },\ }),\ ], }; --- # Solid plugin - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/plugin-solid.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/plugin-solid#solid-plugin) Solid plugin =========================================================================== Copy Markdown [Source Code](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-solid) The Solid plugin provides support for Solid features. The plugin internally integrates [babel-preset-solid](https://github.com/solidjs/solid/tree/main/packages/babel-preset-solid) . Tip The Solid plugin relies on Babel transpilation and requires an additional [Babel plugin](https://rsbuild.rs/plugins/list/plugin-babel) . At the same time, adding the Babel plugin will cause additional compilation overhead. [#](https://rsbuild.rs/plugins/list/plugin-solid#quick-start) Quick start ------------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-solid#install-plugin) Install plugin Run the following command: npm yarn pnpm bun deno npm add @rsbuild/plugin-babel @rsbuild/plugin-solid -D yarn add @rsbuild/plugin-babel @rsbuild/plugin-solid -D pnpm add @rsbuild/plugin-babel @rsbuild/plugin-solid -D bun add @rsbuild/plugin-babel @rsbuild/plugin-solid -D deno add npm:@rsbuild/plugin-babel npm:@rsbuild/plugin-solid -D ### [#](https://rsbuild.rs/plugins/list/plugin-solid#register-plugin) Register plugin Register the plugin in Rsbuild config: rsbuild.config.ts import { pluginBabel } from '@rsbuild/plugin-babel'; import { pluginSolid } from '@rsbuild/plugin-solid'; export default { plugins: [\ pluginBabel({\ include: /\.(?:jsx|tsx)$/,\ }),\ pluginSolid(),\ ], }; After registration, you can develop Solid directly. Tip Since the Solid JSX relies on Babel for compilation, you need to additionally add the [Babel plugin](https://rsbuild.rs/plugins/list/plugin-babel) . Babel compilation will introduce extra overhead, in the example above, we use `include` to match `.jsx` and `.tsx` files, thereby reducing the performance cost brought by Babel. [#](https://rsbuild.rs/plugins/list/plugin-solid#solid-v2) Solid v2 ------------------------------------------------------------------- Solid v2 support is currently in beta. It uses the native Solid compiler by default and does not require `@rsbuild/plugin-babel`. Install and register the beta version of `@rsbuild/plugin-solid`: npm yarn pnpm bun deno npm add @rsbuild/plugin-solid@beta -D yarn add @rsbuild/plugin-solid@beta -D pnpm add @rsbuild/plugin-solid@beta -D bun add @rsbuild/plugin-solid@beta -D deno add npm:@rsbuild/plugin-solid@beta -D rsbuild.config.ts import { pluginSolid } from '@rsbuild/plugin-solid'; export default { plugins: [pluginSolid()], }; [#](https://rsbuild.rs/plugins/list/plugin-solid#resolution-behavior) Resolution behavior ----------------------------------------------------------------------------------------- The Solid plugin adds `solid` to Rsbuild's [resolve.conditionNames](https://rsbuild.rs/config/resolve/condition-names) . This allows package exports to resolve Solid-specific entries when they are available. In development mode, the plugin also adds `development` to resolve Solid's development runtime and enables development-only compiler transforms. You can disable both behaviors with [`dev: false`](https://rsbuild.rs/plugins/list/plugin-solid#dev) . If you configure `resolve.conditionNames`, the plugin preserves your configured values and prepends these Solid conditions. [#](https://rsbuild.rs/plugins/list/plugin-solid#options) Options ----------------------------------------------------------------- To customize the compilation behavior of Solid, use the following options. ### [#](https://rsbuild.rs/plugins/list/plugin-solid#compiler) compiler The JSX compiler backend. The native compiler is used by default. Set this option to `'babel'` to compile JSX with `babel-preset-solid` instead. * **Type:** `'native' | 'babel'` * **Default:** `'native'` * **Version:** `>= 2.0.0` * **Example:** pluginSolid({ compiler: 'babel', }); ### [#](https://rsbuild.rs/plugins/list/plugin-solid#dev) dev Whether to enable Solid's development runtime and development-only compiler transforms. Set it to `false` to disable both behaviors in development mode, or set it to `true` to enable them in production mode. If `solid.dev` is explicitly configured, it overrides the `dev` setting for compiler transforms without affecting runtime resolution. * **Type:** `boolean` * **Default:** `true` in development mode, `false` in production mode * **Example:** pluginSolid({ dev: false, }); ### [#](https://rsbuild.rs/plugins/list/plugin-solid#refreshdisabled) refresh.disabled Whether to disable Solid Refresh for HMR in development mode. This only controls the refresh transform and does not disable Rsbuild HMR. * **Type:** `boolean` * **Default:** `false` * **Example:** pluginSolid({ refresh: { disabled: true, }, }); ### [#](https://rsbuild.rs/plugins/list/plugin-solid#refreshgranular) refresh.granular Whether to emit per-component metadata so edits only remount components whose code changed. * **Type:** `boolean` * **Default:** `true` * **Version:** `>= 2.0.0` * **Example:** pluginSolid({ refresh: { granular: false, }, }); ### [#](https://rsbuild.rs/plugins/list/plugin-solid#ssr) ssr Whether to generate output for Solid SSR. When enabled, the plugin uses `generate: 'ssr'` and `hydratable: true` for Node.js targets, and uses `generate: 'dom'` and `hydratable: true` for other targets. Values in [`solid`](https://rsbuild.rs/plugins/list/plugin-solid#solid) will override these defaults. * **Type:** `boolean` * **Default:** `false` * **Example:** pluginSolid({ ssr: true, }); ### [#](https://rsbuild.rs/plugins/list/plugin-solid#solid) solid Solid compiler options passed to the selected JSX compiler. * **Type:** `SolidPresetOptions` * **Default:** `{}` * **Example:** pluginSolid({ solid: { generate: 'ssr', hydratable: true, }, }); --- # Rsbuild core - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/api/javascript-api/core.md. 菜单目录 [#](https://rsbuild.rs/zh/api/javascript-api/core#rsbuild-core) Rsbuild core ============================================================================ 复制 Markdown 本章节介绍了 Rsbuild 提供的一些核心方法。 [#](https://rsbuild.rs/zh/api/javascript-api/core#creatersbuild) createRsbuild ------------------------------------------------------------------------------ 创建一个 [Rsbuild 实例对象](https://rsbuild.rs/zh/api/javascript-api/instance) 。 * **类型:** function createRsbuild( options?: CreateRsbuildOptions, ): Promise; * **示例:** import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild({ config: { // Rsbuild configuration }, }); ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E9%80%89%E9%A1%B9) 选项 `createRsbuild` 的第一个参数是一个 `options` 对象,你可以传入以下选项: type CreateRsbuildOptions = { cwd?: string; callerName?: string; environment?: string[]; loadEnv?: boolean | LoadEnvOptions; config?: | RsbuildConfig | LoadConfigResult | (() => Promise); restart?: RestartFn; }; * `cwd`:当前执行构建的根路径,默认值为 `process.cwd()` * `callerName`:当前调用者的名称,默认值为 `'rsbuild'`,详见 [指定调用者名称](https://rsbuild.rs/zh/api/javascript-api/core#specify-caller-name) 。 * `environment`:只构建指定的 [environments](https://rsbuild.rs/zh/guide/advanced/environments) ,如果未指定或传入空数组,则构建所有环境。 * `loadEnv`:是否调用 [loadEnv](https://rsbuild.rs/zh/api/javascript-api/core#loadenv) 方法来加载环境变量,并通过 [source.define](https://rsbuild.rs/zh/config/source/define) 定义为全局变量。 * `config`:Rsbuild 配置对象或 [`loadConfig`](https://rsbuild.rs/zh/api/javascript-api/core#loadconfig) 返回的结果。参考 [配置总览](https://rsbuild.rs/zh/config/) 查看所有可用的配置项。 * `restart`:处理当前 dev server 或监听构建重启请求的函数,详见 [restart](https://rsbuild.rs/zh/api/javascript-api/core#restart-handling) 。 ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E4%BC%A0%E5%85%A5%E9%85%8D%E7%BD%AE) 传入配置 你可以将 Rsbuild 配置对象传入 `config` 选项: import { createRsbuild, type RsbuildConfig } from '@rsbuild/core'; const config: RsbuildConfig = { // Rsbuild configuration }; const rsbuild = await createRsbuild({ config }); 也可以将 [`loadConfig`](https://rsbuild.rs/zh/api/javascript-api/core#loadconfig) 的完整返回结果传入 `config`: import { createRsbuild, loadConfig } from '@rsbuild/core'; const result = await loadConfig(); const rsbuild = await createRsbuild({ config: result, }); 传入完整的 `loadConfig` 返回结果后,配置文件及其导入依赖的绝对路径会分别记录在 [`rsbuild.context.configFile`](https://rsbuild.rs/zh/api/javascript-api/instance#contextconfigfile) 和 [`rsbuild.context.configFileDependencies`](https://rsbuild.rs/zh/api/javascript-api/instance#contextconfigfiledependencies) 中。启用持久化构建缓存时,这些文件也会作为构建依赖。关于 Rsbuild 如何监听这些文件,并在文件变化时请求重启,详见[配置文件监听](https://rsbuild.rs/zh/guide/configuration/rsbuild#configuration-file-watching) 。 Tip `config` 是 Rsbuild 1.6 新增的选项。在旧版本中,可使用 `rsbuildConfig` 作为替代。 ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E5%BC%82%E6%AD%A5%E5%8A%A0%E8%BD%BD%E9%85%8D%E7%BD%AE) 异步加载配置 `config` 也可以是一个异步函数,你可以通过该函数来动态加载 Rsbuild 配置,并进行一些自定义操作。 import { createRsbuild, loadConfig } from '@rsbuild/core'; const rsbuild = await createRsbuild({ config: async () => { const result = await loadConfig(); someFunctionToUpdateConfig(result.content); return result; }, }); ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E5%8A%A0%E8%BD%BD%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F) 加载环境变量 `createRsbuild` 的 `loadEnv` 选项可以帮助你调用 [loadEnv](https://rsbuild.rs/zh/api/javascript-api/core#loadenv) 方法来加载环境变量: const rsbuild = await createRsbuild({ loadEnv: true, }); 传入 `loadEnv: true` 会自动完成如下步骤: 1. 调用 `loadEnv` 方法来加载环境变量。 2. 添加 [source.define](https://rsbuild.rs/zh/config/source/define) 配置,将 `loadEnv` 返回的 `publicVars` 定义为全局变量。 3. 监听 `.env` 文件的变化,在文件变化时重新启动开发服务器,并使构建缓存失效。 4. 在关闭构建或开发服务器时,自动调用 `loadEnv` 返回的 `cleanup` 方法来清除环境变量。 你也可以传入 [loadEnv](https://rsbuild.rs/zh/api/javascript-api/core#loadenv) 方法的选项,比如: const rsbuild = await createRsbuild({ loadEnv: { prefixes: ['PUBLIC_', 'REACT_APP_'], }, }); ### [#](https://rsbuild.rs/zh/api/javascript-api/core#restart-handling) 重启处理 * **版本:** v2.1.7 新增 `restart` 选项允许你控制 Rsbuild 如何重启当前 dev server 或监听构建,适用于需要在 Rsbuild 外部管理重启流程的场景。 > 查看 [配置文件监听](https://rsbuild.rs/zh/guide/configuration/rsbuild#configuration-file-watching) > 了解重启的触发方式。 当请求重启时,Rsbuild 会调用 [onRestart hook](https://rsbuild.rs/zh/plugins/dev/hooks#onrestart) ,关闭当前任务的资源,然后调用 `restart`。`restart` 回调会接收到当前调用 `rsbuild.build()` 或 `rsbuild.startDevServer()` 时传入的选项。 新任务成功启动时,该函数应返回 `true`。如果返回 `false` 或抛出错误,restart watcher 会保持运行,以便后续文件变化时再次尝试重启。 import { createRsbuild, type RestartFn } from '@rsbuild/core'; async function createInstance() { return createRsbuild({ restart, }); } const restart: RestartFn = async (context) => { const rsbuild = await createInstance(); if (context.action === 'build') { await rsbuild.build(context.options); } else { await rsbuild.startDevServer(context.options); } return true; }; const rsbuild = await createInstance(); await rsbuild.startDevServer(); ### [#](https://rsbuild.rs/zh/api/javascript-api/core#specify-caller-name) 指定调用者名称 你可以通过 `callerName` 选项来指定当前调用 Rsbuild 的框架或工具的名称,该名称可以被 Rsbuild 插件通过 [context.callerName](https://rsbuild.rs/zh/api/javascript-api/instance#contextcallername) 访问到,并基于这个标识符来执行不同的逻辑。 import { myPlugin } from './myPlugin'; const rsbuild = await createRsbuild({ callerName: 'rslib', config: { plugins: [myPlugin], }, }); myPlugin.ts export const myPlugin = { name: 'my-plugin', setup(api) { const { callerName } = api.context; if (callerName === 'rslib') { // ... } else if (callerName === 'rsbuild') { // ... } }, }; [#](https://rsbuild.rs/zh/api/javascript-api/core#loadconfig) loadConfig ------------------------------------------------------------------------ 加载 Rsbuild 配置文件。 * **类型:** function loadConfig(params?: { // 默认为 process.cwd() cwd?: string; // 指定配置文件路径,可以为相对路径或绝对路径 path?: string; // 未指定 path 时要查找的配置文件名列表 configFileNames?: string[]; /** * 从配置文件中读取的导出名称 * 设置为 `false` 时,只执行配置文件,不读取导出 * @default 'default' */ exportName?: string | false; meta?: Record; envMode?: string; /** * 传给配置函数的 command 参数。 * @default process.argv[2] */ command?: string; /** * 指定配置文件加载器,可选值为 `auto`、`jiti` 或 `native`。 * - `auto`:优先使用 Node.js 原生加载器,若加载失败则回退到 jiti * - `jiti`:使用 jiti 作为加载器,开箱即用地支持 TypeScript 和 ESM * - `native`:使用 Node.js 原生加载器。TypeScript 配置文件要求运行时原生支持 * TypeScript,例如 Node.js 22.6+ * @default 'auto' */ loader?: 'auto' | 'jiti' | 'native'; }): Promise<{ content: Config; filePath: string | null; dependencies: string[]; }>; * **示例:** import { loadConfig } from '@rsbuild/core'; // 按默认查找顺序从 cwd 加载 `rsbuild.config.*` 配置文件 const result = await loadConfig(); console.log(result.content); // -> Rsbuild config object const rsbuild = await createRsbuild({ config: result, }); 如果 cwd 目录下不存在 Rsbuild 配置文件,loadConfig 方法的返回值为 `{ content: {}, filePath: null }`。 当未指定 `path` 时,`loadConfig` 会按以下顺序查找配置文件: * `rsbuild.config.ts` * `rsbuild.config.js` * `rsbuild.config.mts` * `rsbuild.config.mjs` * `rsbuild.config.cts` * `rsbuild.config.cjs` 如果同时存在多个配置文件,`loadConfig` 会使用这个列表中第一个匹配到的文件。 ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E8%87%AA%E5%AE%9A%E4%B9%89%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E5%90%8D) 自定义配置文件名 使用 `configFileNames` 选项可以替换默认的配置文件查找列表。文件名会相对于 `cwd` 解析,且指定 `path` 时会忽略该选项。 import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ configFileNames: ['framework.config.ts', 'framework.config.mjs'], }); ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E6%8C%87%E5%AE%9A%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6) 指定配置文件 使用 `path` 选项加载 `my-config.ts` 配置文件: import { join } from 'node:path'; import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ path: join(__dirname, 'my-config.ts'), }); ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E6%8C%87%E5%AE%9A%E5%AF%BC%E5%87%BA%E5%90%8D%E7%A7%B0) 指定导出名称 默认情况下,`loadConfig` 会读取配置文件的默认导出。使用 `exportName` 可以读取命名导出: rsbuild.config.ts export const rsbuildConfig = { // ... }; import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ exportName: 'rsbuildConfig', }); 当配置文件只需要被执行、不需要读取任何导出时,可以将 `exportName` 设置为 `false`,此时 `content` 为 `{}`。 import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ exportName: false, }); ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E4%BC%A0%E5%85%A5-meta-%E5%AF%B9%E8%B1%A1) 传入 meta 对象 加载配置文件,并传入自定义的 meta 对象: import { join } from 'node:path'; import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ meta: { foo: 'bar', }, }); 在 `defineConfig` 定义的配置函数中,你可以通过 `meta` 对象访问到 `foo` 变量: rsbuild.config.ts export default defineConfig(({ meta }) => { console.log(meta.foo); // bar return config; }); ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E4%BC%A0%E5%85%A5-command) 传入 command 默认情况下,`loadConfig` 会将 `process.argv[2]` 作为 `command` 传给配置函数。你可以通过 `command` 选项显式设置该值。 import { loadConfig } from '@rsbuild/core'; const { content } = await loadConfig({ command: 'build', }); [#](https://rsbuild.rs/zh/api/javascript-api/core#loadenv) loadEnv ------------------------------------------------------------------ 加载 [.env](https://rsbuild.rs/zh/guide/advanced/env-vars#env-file) 文件,并返回所有以 `prefixes` 开头的环境变量。 * **类型:** type LoadEnvOptions = { /** * 加载 env 文件的根路径 * @default process.cwd() */ cwd?: string; /** * 用于指定 .env.[mode] 文件的名称 * 等价于 Rsbuild CLI 的 `--env-mode` 选项 * @default process.env.NODE_ENV */ mode?: string; /** * public 变量的前缀 * @default ['PUBLIC_'] */ prefixes?: string[]; /** * 指定一个目标对象来存储环境变量。 * 如果未提供,变量将写入 `process.env`。 * @default process.env */ processEnv?: Record; }; type LoadEnvResult = { /** .env 文件包含的所有环境变量 */ parsed: Record; /** 所有 env 文件的绝对路径 */ filePaths: string[]; /** * 以 prefixes 开头的环境变量 * * @example * ```ts * { * PUBLIC_FOO: 'bar', * } * ``` **/ rawPublicVars: Record; /** * 以 prefix 开头的环境变量,并经过格式化。 * key 包含前缀 `process.env.*` 和 `import.meta.env.*`。 * value 经过 `JSON.stringify` 处理。 * * @example * ```ts * { * 'process.env.PUBLIC_FOO': '"bar"', * 'import.meta.env.PUBLIC_FOO': '"bar"', * } * ``` **/ publicVars: Record; /** 从 `process.env` 上清除挂载的环境变量 */ cleanup: () => void; }; function loadEnv(options?: LoadEnvOptions): LoadEnvResult; * **示例:** import { loadEnv, mergeRsbuildConfig } from '@rsbuild/core'; const { parsed, publicVars } = loadEnv(); const mergedConfig = mergeRsbuildConfig( { source: { define: publicVars, }, }, userConfig, ); 该方法也会加载 `.env.local` 和 `.env.[mode]` 等文件,详见 [环境变量](https://rsbuild.rs/zh/guide/advanced/env-vars) 。 Tip * Rsbuild CLI 会自动调用 `loadEnv()` 方法,如果你在使用 Rsbuild CLI,可以通过 [\--env-mode](https://rsbuild.rs/zh/guide/advanced/env-vars#env-mode) 选项来设置 `mode` 参数。 * [createRsbuild](https://rsbuild.rs/zh/api/javascript-api/core#creatersbuild) 的 `loadEnv` 选项会帮助你调用 `loadEnv()` 方法,并处理相关操作。 ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E6%8C%87%E5%AE%9A%E7%9B%AE%E6%A0%87%E5%AF%B9%E8%B1%A1) 指定目标对象 默认情况下,`loadEnv` 会使用 `process.env` 对象来存储环境变量。你可以通过 `processEnv` 选项来指定一个目标对象来存储环境变量: import { loadEnv } from '@rsbuild/core'; // 传入一个空对象,避免修改 `process.env` loadEnv({ processEnv: {} }); // 传入 `process.env` 对象的副本,避免修改原始对象 loadEnv({ processEnv: { ...process.env } }); [#](https://rsbuild.rs/zh/api/javascript-api/core#mergersbuildconfig) mergeRsbuildConfig ---------------------------------------------------------------------------------------- 用于合并多份 Rsbuild 配置对象。 `mergeRsbuildConfig` 函数接收多个配置对象作为参数。它会对每个配置对象进行深层合并,自动将多个函数项合并为顺序执行的函数数组,并返回一个新的合并配置对象,不会修改传入的配置对象。 * **类型:** function mergeRsbuildConfig( ...configs: (RsbuildConfig | undefined)[] ): RsbuildConfig; ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E5%9F%BA%E7%A1%80%E7%A4%BA%E4%BE%8B) 基础示例 import { mergeRsbuildConfig } from '@rsbuild/core'; const config1 = { server: { compress: false, }, }; const config2 = { server: { compress: true, }, }; const mergedConfig = mergeRsbuildConfig(config1, config2); console.log(mergedConfig); // { server: { compress: true } } > 该方法不会修改入参中的 config 对象。 ### [#](https://rsbuild.rs/zh/api/javascript-api/core#%E5%90%88%E5%B9%B6%E8%A7%84%E5%88%99) 合并规则 除了深层合并外,`mergeRsbuildConfig` 函数还会对部分选项进行特殊处理。 比如 [tools.rspack](https://rsbuild.rs/zh/config/tools/rspack) 可以被设置为一个函数,当多份配置对象都包含 `tools.rspack` 时,`mergeRsbuildConfig` 不会简单地保留最后一个函数。相反,它会将所有的 `tools.rspack` 函数或对象合并到一个数组中。 import { mergeRsbuildConfig } from '@rsbuild/core'; const config1 = { tools: { rspack: { someOption: true, }, }, }; const config2 = { tools: { rspack: (config) => { console.log('function 1'); return config; }, }, }; const config3 = { tools: { rspack: (config) => { console.log('function 2'); return config; }, }, }; const mergedConfig = mergeRsbuildConfig(config1, config2, config3); 在以上示例中,合并后的配置为以下形式,该数组首先包含了一个对象 `{ someOption: true }`,然后是按合并顺序排列的两个函数。 数组中的每一项会依次执行,并且上一个函数的输出将作为下一个函数的输入,最终生成一份 Rspack 配置。 const mergedConfig = { tools: { rspack: [\ {\ someOption: true,\ },\ (config) => {\ console.log('function 1');\ return config;\ },\ (config) => {\ console.log('function 2');\ return config;\ },\ ], }, }; 通过这种方法,我们可以确保合并多份配置对象时,相同的多个 `tools.rspack` 字段均能够生效。 在 Rsbuild 中,大部分支持函数值的选项都使用上述规则,比如 `tools.postcss`、`tools.less`、`tools.bundlerChain` 等。 [#](https://rsbuild.rs/zh/api/javascript-api/core#createlogger) createLogger ---------------------------------------------------------------------------- 创建一个独立的 logger 实例,创建出的 logger 也可以传给 [customLogger](https://rsbuild.rs/zh/config/custom-logger) 配置项使用。 > 详见 [日志](https://rsbuild.rs/zh/guide/advanced/logging) > 。 * **示例:** import { createLogger } from '@rsbuild/core'; const logger = createLogger({ level: 'warn' }); logger.warn('This is a warning message'); logger.error('This is an error message'); // Will not print logger.info('This is an info message'); [#](https://rsbuild.rs/zh/api/javascript-api/core#logger) logger ---------------------------------------------------------------- 全局 logger 实例,可以用于输出与 Rsbuild 一致的日志格式。 > 详见 [日志](https://rsbuild.rs/zh/guide/advanced/logging) > 。 * **示例:** import { logger } from '@rsbuild/core'; // Info logger.info('This is an info message'); [#](https://rsbuild.rs/zh/api/javascript-api/core#rspack) rspack ---------------------------------------------------------------- 如果你需要访问 [@rspack/core](https://npmjs.com/package/@rspack/core) 导出的 API 或插件,可以直接从 `@rsbuild/core` 中引用 `rspack` 对象,无须额外安装 `@rspack/core` 包。 * **类型:** `Rspack` * **示例:** // the same as `import { rspack } from '@rspack/core'` import { rspack } from '@rsbuild/core'; console.log(rspack.rspackVersion); // a.b.c console.log(rspack.util.createHash); console.log(rspack.BannerPlugin); Tip * 参考 [Rspack 插件](https://rspack.rs/zh/plugins/) 和 [Rspack JavaScript API](https://rspack.rs/zh/api/javascript-api/) 了解可用的 Rspack API。 * 不推荐手动安装 `@rspack/core` 包,因为这可能与 Rsbuild 依赖的版本不一致。 [#](https://rsbuild.rs/zh/api/javascript-api/core#version) version ------------------------------------------------------------------ 当前使用的 `@rsbuild/core` 的版本。 * **类型:** `string` * **示例:** import { version } from '@rsbuild/core'; console.log(version); // 1.0.0 [#](https://rsbuild.rs/zh/api/javascript-api/core#ensureassetprefix) ensureAssetPrefix -------------------------------------------------------------------------------------- `ensureAssetPrefix` 函数用于将给定的 `assetPrefix` 拼接到一个可能是 URL 的字符串前面。如果传入的字符串已经是一个完整的 URL,则直接返回该字符串。 * **类型:** function ensureAssetPrefix( // 需要处理的 URL 字符串。可以是相对路径或绝对 URL url: string, // 需要拼接的 URL 前缀 assetPrefix?: Rspack.PublicPath, ) => string; 如果未传入 `assetPrefix`,Rsbuild 会使用默认的资源前缀 `/`。如果 `assetPrefix` 为 `'auto'` 或函数,该函数会直接返回传入的 URL。 * **示例:** import { ensureAssetPrefix } from '@rsbuild/core'; ensureAssetPrefix('foo/bar.js', '/static/'); // -> '/static/foo/bar.js' ensureAssetPrefix('foo/bar.js', 'https://example.com/static/'); // -> 'https://example.com/static/foo/bar.js' ensureAssetPrefix( 'https://example.com/index.html', 'https://example.com/static/', ); // -> 'https://example.com/index.html' --- # Tailwind CSS plugin - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/plugin-tailwindcss.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/plugin-tailwindcss#tailwind-css-plugin) Tailwind CSS plugin =============================================================================================== Copy Markdown [Source Code](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-tailwindcss) This plugin is based on [@tailwindcss/webpack](https://www.npmjs.com/package/@tailwindcss/webpack) and is used to integrate [Tailwind CSS](https://tailwindcss.com/) v4 in Rsbuild. Compared with the [@tailwindcss/postcss](https://www.npmjs.com/package/@tailwindcss/postcss) \-based integration, this plugin does not run Tailwind CSS transforms through PostCSS, providing better build performance. [#](https://rsbuild.rs/plugins/list/plugin-tailwindcss#quick-start) Quick start ------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-tailwindcss#install-plugin) Install plugin Run the following command: npm yarn pnpm bun deno npm add @rsbuild/plugin-tailwindcss tailwindcss -D yarn add @rsbuild/plugin-tailwindcss tailwindcss -D pnpm add @rsbuild/plugin-tailwindcss tailwindcss -D bun add @rsbuild/plugin-tailwindcss tailwindcss -D deno add npm:@rsbuild/plugin-tailwindcss npm:tailwindcss -D Tip The Tailwind CSS plugin supports Rsbuild >= 2.0 and Tailwind CSS >= 4.0. ### [#](https://rsbuild.rs/plugins/list/plugin-tailwindcss#register-plugin) Register plugin Register the plugin in Rsbuild config: rsbuild.config.ts import { pluginTailwindcss } from '@rsbuild/plugin-tailwindcss'; export default { plugins: [pluginTailwindcss()], }; ### [#](https://rsbuild.rs/plugins/list/plugin-tailwindcss#import-css) Import CSS Add an `@import` to your CSS entry file that imports Tailwind CSS: src/index.css @import 'tailwindcss'; Then import this CSS file in your JavaScript or TypeScript entry: src/index.ts import './index.css'; Now you can use Tailwind's utility classes in your HTML or framework components:

Hello world!

Tip Tailwind CSS v4 is not designed to be used with CSS preprocessors like Sass, Less, or Stylus. You need to place the `@import 'tailwindcss';` statement at the beginning of a `.css` file. See [Tailwind CSS - Compatibility](https://tailwindcss.com/docs/compatibility#sass-less-and-stylus) for more details. [#](https://rsbuild.rs/plugins/list/plugin-tailwindcss#scan-scope) Scan scope ----------------------------------------------------------------------------- By default, this plugin uses the [Rsbuild root directory](https://rsbuild.rs/config/root) as Tailwind CSS's scan base, which defaults to `process.cwd()`. Tailwind CSS automatically detects class names from files under the scan base. You can narrow or customize the scan scope with Tailwind CSS's `source(...)` function and [`@source` directive](https://tailwindcss.com/docs/detecting-classes-in-source-files#explicitly-registering-sources) in your CSS entry file: src/index.css @import 'tailwindcss' source('./'); You can also disable automatic source detection and explicitly register source files: src/index.css @import 'tailwindcss' source(none); @source './pages/**/*.html'; @source './components/**/*.{js,ts,jsx,tsx}'; Relative paths in `source(...)` and `@source` are resolved from the CSS file that contains them. [#](https://rsbuild.rs/plugins/list/plugin-tailwindcss#options) Options ----------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-tailwindcss#optimize) optimize Enable Tailwind CSS's built-in Lightning CSS optimization. By default, this option is enabled in production mode and disabled in development mode. * **Type:** type Optimize = | boolean | { minify?: boolean; }; * **Default:** `true` in production mode, `false` in development mode In production mode, Tailwind CSS's built-in minification follows Rsbuild's CSS minification config. For example, setting [`output.minify`](https://rsbuild.rs/config/output/minify) to `false` disables Tailwind CSS's built-in minification in the default configuration. When `optimize` is `false`, Tailwind CSS still compiles Tailwind directives and generates utilities, but skips Tailwind CSS's built-in Lightning CSS optimization step: rsbuild.config.ts pluginTailwindcss({ optimize: false, }); If you want to always enable Tailwind CSS's built-in optimization and minification, set `optimize` to `true`: rsbuild.config.ts pluginTailwindcss({ optimize: true, }); If you want to enable Tailwind CSS's built-in optimization without enabling its minification, pass an object and omit `minify` or set it to `false`: rsbuild.config.ts pluginTailwindcss({ optimize: { minify: false, }, }); To explicitly enable Tailwind CSS's built-in minification: rsbuild.config.ts pluginTailwindcss({ optimize: { minify: true, }, }); --- # Rsbuild 2.0 发布 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/blog/v2-0.md. 目录 [返回博客](https://rsbuild.rs/zh/blog/) [#](https://rsbuild.rs/zh/blog/v2-0#rsbuild-20-%E5%8F%91%E5%B8%83) Rsbuild 2.0 发布 ================================================================================= 复制 Markdown _2026 年 4 月 22 日_ ![Jiahan Chen](https://github.com/chenjiahan.png) Jiahan Chen [](https://github.com/chenjiahan) @chenjiahan ![](https://assets.rspack.rs/rsbuild/rsbuild-banner-v2.0.png) 我们很高兴地宣布 Rsbuild 2.0 已经正式发布! Rsbuild 是一个由 Rspack 驱动的现代 Web 应用构建工具,也是 Rstack 生态的重要基础设施。围绕 Rsbuild,我们陆续打造了一系列上层工具,包括 [Rspress](https://github.com/web-infra-dev/rspress) 、[Rslib](https://github.com/web-infra-dev/rslib) 、[Rstest](https://github.com/web-infra-dev/rstest) 、[Storybook Rsbuild](https://github.com/rstackjs/storybook-rsbuild) 等。这些工具通过 Rsbuild 共享统一的构建能力与插件体系,在应用开发、库构建、文档站点以及测试等场景中提供一致的开发体验。 自 1.0 发布以来,Rsbuild 的 npm 周下载量已增长超过 **15 倍**,并成为 Rspack 新项目的首选构建工具。与此同时,越来越多团队从 webpack、Create React App 等工具迁移至 Rsbuild,并在构建效率和开发体验上获得了提升。 ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-2-0-downloads.png) 为了帮助生态平稳升级到 2.0,我们投入了三个月进行验证与打磨,期间发布了 20 多个预览版本。目前,Rslib、Rstest、Rspress、Storybook Rsbuild 和 Modern.js 均已完成升级,并在生产环境中稳定运行。 2.0 版本的主要改进包括: * 新特性: * [升级 Rspack 2.0](https://rsbuild.rs/zh/blog/v2-0#upgrade-to-rspack-20) * [React Server Components 支持](https://rsbuild.rs/zh/blog/v2-0#react-server-components-support) * [开发服务器与客户端通信](https://rsbuild.rs/zh/blog/v2-0#dev-server-client-communication) * [支持扩展内置 Server](https://rsbuild.rs/zh/blog/v2-0#extending-the-built-in-server) * [支持自定义 logger](https://rsbuild.rs/zh/blog/v2-0#custom-logger-support) * [更易用的拆包配置](https://rsbuild.rs/zh/blog/v2-0#easier-chunk-splitting-configuration) * [create-rsbuild 模板更新](https://rsbuild.rs/zh/blog/v2-0#create-rsbuild-template-updates) * 更轻量: * [默认依赖从 13 个减少到 4 个](https://rsbuild.rs/zh/blog/v2-0#reduced-dependencies) * 更安全: * [默认仅监听 'localhost'](https://rsbuild.rs/zh/blog/v2-0#default-host-change) * [Proxy 中间件升级,支持 HTTP/2 代理](https://rsbuild.rs/zh/blog/v2-0#proxy-middleware-upgrade) * 更现代: * [Pure ESM 包](https://rsbuild.rs/zh/blog/v2-0#pure-esm-package) * [不再支持 Node.js 18](https://rsbuild.rs/zh/blog/v2-0#nodejs-support) * [默认目标环境更新](https://rsbuild.rs/zh/blog/v2-0#updated-default-targets) * [默认输出 ESM Node.js 产物](https://rsbuild.rs/zh/blog/v2-0#esm-nodejs-output) * [默认使用 '2023-11' 装饰器版本](https://rsbuild.rs/zh/blog/v2-0#updated-decorator-version) [#](https://rsbuild.rs/zh/blog/v2-0#upgrade-to-rspack-20) 升级 Rspack 2.0 ----------------------------------------------------------------------- Rsbuild 2.0 基于 Rspack 2.0 实现,因此也继承了 Rspack 2.0 在构建性能、产物优化和底层能力上的一系列改进。 参考 [Rspack 2.0 博客](https://rspack.rs/zh/blog/announcing-2-0) 了解这部分变更。 [#](https://rsbuild.rs/zh/blog/v2-0#react-server-components-support) React Server Components 支持 ----------------------------------------------------------------------------------------------- [React Server Components](https://react.dev/reference/rsc/server-components) (RSC) 是一种预先渲染的 React 组件类型,它将数据获取与组件逻辑结合起来,并减少发送到客户端的 JavaScript。 为了帮助基于 Rsbuild 的 Web 应用或框架更便捷地使用 RSC,我们提供了 [rsbuild-plugin-rsc](https://github.com/rstackjs/rsbuild-plugin-rsc) 插件。该插件基于 Rspack 内置的 RSC 能力实现,并借助 Rsbuild 的 [Environments API](https://rsbuild.rs/zh/guide/advanced/environments) 对 client 与 server 等多环境进行统一组织,降低了接入与配置成本。 rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; import { pluginRSC } from 'rsbuild-plugin-rsc'; export default defineConfig({ plugins: [\ pluginReact(),\ pluginRSC({\ // Plugin options\ }),\ ], environments: { server: { // Server config... }, client: { // Client config... }, }, }); 目前该插件仍处于实验阶段。它已经能够运行 React Router 的 [RSC 示例](https://github.com/rstackjs/rsbuild-plugin-rsc/tree/main/examples/react-router) ,也已经在 [Modern.js 框架](https://modernjs.dev/guides/basic-features/render/rsc) 中落地使用。 另外,我们也在与 [TanStack](https://tanstack.com/) 团队展开合作,计划在后续版本中提供对 [TanStack Start](https://tanstack.com/start) 和 [TanStack 的 RSC](https://tanstack.com/blog/react-server-components) 的支持。TanStack Start 是一个基于 TanStack Router 构建的全栈框架,我们非常期待结合双方的能力,共同探索 RSC 在不同场景下的更多可能性。 [#](https://rsbuild.rs/zh/blog/v2-0#dev-server-client-communication) 开发服务器与客户端通信 -------------------------------------------------------------------------------- 在支持 React Server Components 的过程中,我们发现一些场景需要在开发服务器与浏览器之间进行通信。例如,服务端完成某些操作后,需要主动通知客户端执行对应逻辑。 为此,Rsbuild 2.0 提供了一组通信 API: * 服务端可通过 [hot.send](https://rsbuild.rs/zh/api/javascript-api/environment-api#hotsend) 向当前 environment 对应的客户端发送消息 * 客户端可通过 `import.meta.webpackHot.on` 监听这些自定义事件 这些 API 复用了现有的 HMR 通道,无需额外创建 WebSocket 连接。同时,消息仅会发送到匹配的 environment,避免不必要的广播。 例如,当服务端状态发生变化时,通知客户端更新,而不是触发整页刷新: * 在服务端触发消息: rsbuild.config.ts server.environments.web.hot.send('data-change', { count: 1, }); * 在客户端监听消息: src/dev-sync.ts if (import.meta.webpackHot) { import.meta.webpackHot.on('data-change', ({ count }) => { console.log('data updated:', count); }); } [#](https://rsbuild.rs/zh/blog/v2-0#extending-the-built-in-server) 扩展内置 Server ------------------------------------------------------------------------------ Rsbuild 2.0 新增了 [server.setup](https://rsbuild.rs/zh/config/server/setup) 选项,用于在开发服务器或预览服务器启动时执行初始化逻辑。 该选项相较于原有的 `server.setupMiddlewares` 更为强大,用于对 Rsbuild 内置服务器进行定制,例如注册中间件、执行启动前任务,或根据 dev / preview 模式注入不同逻辑。通过 `server.setup`,这些能力可以直接在 Rsbuild 配置中完成。 例如,为本地开发和预览环境添加一个简单的接口: rsbuild.config.ts export default { server: { setup: ({ server }) => { server.middlewares.use((req, res, next) => { if (req.url === '/api/health') { res.end('ok'); return; } next(); }); }, }, }; [#](https://rsbuild.rs/zh/blog/v2-0#custom-logger-support) 支持自定义 logger ----------------------------------------------------------------------- 通过新增的 [customLogger](https://rsbuild.rs/zh/config/custom-logger) 选项,你可以为多个 Rsbuild 实例自定义不同的 logger。 这允许你为不同 Rsbuild 实例设置不同的日志级别、输出前缀,或者接入自定义的日志系统,而无需修改 [全局 logger 实例](https://rsbuild.rs/zh/api/javascript-api/core#logger) 。 rsbuild.config.ts import { createLogger, defineConfig } from '@rsbuild/core'; const customLogger = createLogger({ level: 'warn', prefix: '[web]', }); export default defineConfig({ customLogger, }); > 查看 [日志指南](https://rsbuild.rs/zh/guide/advanced/logging) > 了解更多。 [#](https://rsbuild.rs/zh/blog/v2-0#easier-chunk-splitting-configuration) 更易用的拆包配置 ---------------------------------------------------------------------------------- 在 1.x 中,Rsbuild 通过 [performance.chunkSplit](https://v1.rsbuild.rs/config/performance/chunk-split) 封装了常见的拆包策略,但它的设计与 Rspack 的 `splitChunks` 差异较大,开发者需要额外理解 `strategy`、`forceSplitting` 等概念。对于 coding agent 来说,也难以直接生成符合社区习惯的 `splitChunks` 配置,通常还需要进行额外转换。 因此,Rsbuild 2.0 提供了新的 [splitChunks](https://rsbuild.rs/zh/config/split-chunks) 选项。它的行为与 Rspack 的 `splitChunks` 完全对齐,并通过额外的 `preset` 选项来提供预设配置。 例如,使用 `per-package` 预设将每个 package 拆分成一个独立的 chunk: rsbuild.config.ts export default { splitChunks: { preset: 'per-package', chunks: 'all', }, }; > `performance.chunkSplit` 已在 2.0 中废弃,但现有配置仍可继续使用。建议参考 [迁移 performance.chunkSplit](https://rsbuild.rs/zh/guide/upgrade/v1-to-v2#migrate-performancechunksplit) > 进行迁移。 [#](https://rsbuild.rs/zh/blog/v2-0#create-rsbuild-template-updates) create-rsbuild 模板更新 ---------------------------------------------------------------------------------------- 在核心能力升级的同时,我们也更新了 `create-rsbuild` 中的模板,使新项目的初始化流程更加贴近当前的开发实践: * 默认生成 `AGENTS.md` 文件,并支持在初始化时安装 [rsbuild-best-practices](https://github.com/rstackjs/agent-skills?tab=readme-ov-file#rsbuild-skills) 等 Agent Skills。 * 创建 React 项目时,可以选择 [React Compiler](https://rsbuild.rs/zh/guide/framework/react#react-compiler) 作为可选工具。 * 新增对 [Rslint](https://github.com/web-infra-dev/rslint) 的实验性支持,Rslint 是基于 `typescript-go` 的高性能代码检查工具。 * 移除过时的 React 18 和 Vue 2 模板。 [#](https://rsbuild.rs/zh/blog/v2-0#reduced-dependencies) 精简依赖 -------------------------------------------------------------- Rsbuild 2.0 对默认依赖进行了精简,将仅在特定场景下使用的包移出默认依赖,使默认依赖的数量从 13 个减少到 4 个,安装体积约减少 2 MB。 本次调整主要涉及: * 不再默认安装 [core-js](https://www.npmjs.com/package/core-js) ,在使用 [output.polyfill](https://rsbuild.rs/zh/config/output/polyfill) 时需要手动安装。 * 不再默认安装 [@module-federation/runtime-tools](https://www.npmjs.com/package/@module-federation/runtime-tools) ,在使用 [moduleFederation.options](https://rsbuild.rs/zh/config/module-federation/options) 时需要手动安装,Module Federation 2.0 不受影响。 * 移除 [webpack-bundle-analyzer](https://www.npmjs.com/package/webpack-bundle-analyzer) 依赖,推荐使用 [Rsdoctor](https://rsbuild.rs/zh/guide/debug/rsdoctor) 进行产物分析,或自行安装和注册 `webpack-bundle-analyzer`。 [#](https://rsbuild.rs/zh/blog/v2-0#default-host-change) 默认 host 变化 ------------------------------------------------------------------- [server.host](https://rsbuild.rs/zh/config/server/host) 的默认值从 `'0.0.0.0'` 调整为 `'localhost'`。开发和预览服务器默认仅监听本机,不再对局域网内的其他设备开放。 这一调整遵循「默认安全」的原则。在大多数本地开发场景中,开发服务器无需对外暴露。仅监听本机地址可以减少意外暴露,降低在共享网络环境中被扫描或攻击的风险。 如果你需要在局域网设备上访问页面,可以显式开启网络访问: rsbuild.config.ts export default { server: { host: '0.0.0.0', }, }; 也可以通过 CLI 的 `--host` 参数快速开启: rsbuild --host [#](https://rsbuild.rs/zh/blog/v2-0#proxy-middleware-upgrade) Proxy 中间件升级 ------------------------------------------------------------------------- 开发服务器使用的 [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware) 已经从 v2 升级至最新的 v4 版本,同时其底层依赖从已经停止维护的 [http-proxy](https://www.npmjs.com/package/http-proxy) 切换为由 [unjs 社区](https://github.com/unjs) 积极维护的 [httpxy](https://npmx.dev/package/httpxy) 。 这主要带来几点改进: * 支持 HTTP/2 代理 * 解决已知的安全问题 * 不再依赖 Node.js 已废弃的 `url.parse()` API > `server.proxy` 的部分字段已发生变更,升级时请参考 [从 v1 升级到 v2](https://rsbuild.rs/zh/guide/upgrade/v1-to-v2#proxy-middleware-upgraded) > 。 [#](https://rsbuild.rs/zh/blog/v2-0#pure-esm-package) Pure ESM 包 ---------------------------------------------------------------- [@rsbuild/core](https://www.npmjs.com/package/@rsbuild/core) 现在以 pure ESM 包的形式发布,并移除了自身的 CommonJS 构建产物。这一调整仅影响 Rsbuild 本身的发布形式,使安装体积减少了约 500KB。 在 Node.js 20 及以上版本中,运行时已原生支持通过 [require(esm)](https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require) 加载 ESM 模块。因此,对大多数仍通过 JavaScript API 使用 Rsbuild 的项目来说,这一变更通常不会带来实际影响,也无需额外修改现有代码。 [#](https://rsbuild.rs/zh/blog/v2-0#nodejs-support) Node.js 支持 -------------------------------------------------------------- 从 2.0 开始,Rsbuild 最低支持的 Node.js 版本为 `20.19+` 或 `22.12+`。由于 Node.js 18 已于 2025 年 4 月底结束维护,2.0 也不再继续支持该版本。 > 我们通常会在某个 Node.js 版本进入 EOL 约一年后再移除支持,以为社区和用户预留更充足的升级时间。 [#](https://rsbuild.rs/zh/blog/v2-0#updated-default-targets) 默认目标环境更新 --------------------------------------------------------------------- Rsbuild 2.0 调整了默认的目标环境,使产物面向更现代的浏览器和 Node.js 版本。 对于 Web 产物,默认的 browserslist 现在与 [`baseline widely available on 2025-05-01`](https://browsersl.ist/#q=baseline+widely+available+on+2025-05-01) 查询结果一致。该查询基于 [2025 年 5 月 1 日](https://web-platform-dx.github.io/supported-browsers/?widelyAvailableOnDate=2025-05-01) 的 [Baseline 广泛可用](https://web-platform-dx.github.io/baseline/) 特性集。 默认值变化如下: * Chrome 87 → 107 * Edge 88 → 107 * Firefox 78 → 104 * Safari 14 → 16 这意味着在未显式配置 browserslist 的情况下,Rsbuild 会默认输出更现代的 JavaScript 和 CSS,同时减少语法降级和 polyfill 的引入。 对于 Node.js 产物,默认目标版本也从 Node.js 16 提升至 Node.js 20。 如果你已经通过 `.browserslistrc`、`package.json#browserslist` 或 [output.overrideBrowserslist](https://rsbuild.rs/zh/config/output/override-browserslist) 显式配置了目标环境,则不会受到上述调整的影响。 [#](https://rsbuild.rs/zh/blog/v2-0#esm-nodejs-output) ESM Node.js 产物 --------------------------------------------------------------------- 在构建 Node.js 产物时,相比 Rsbuild v1 默认输出压缩后的 CommonJS 代码,Rsbuild 2.0 现在会默认输出未压缩的 ES modules 代码。 这一调整更符合现代 Node 应用的主流实践。同时,服务端代码默认不压缩,有助于保留清晰的调试堆栈,提升问题排查效率。 需要注意的是,运行时需要具备加载 ESM 的能力。例如在 `package.json` 中设置 `"type": "module"`,或者使用 `.mjs` 作为输出文件扩展名。如果你的项目仍依赖 CommonJS,可以显式切回原有行为: rsbuild.config.ts export default { output: { target: 'node', module: false, minify: true, }, }; [#](https://rsbuild.rs/zh/blog/v2-0#updated-decorator-version) 装饰器版本更新 ---------------------------------------------------------------------- 随着底层 SWC 支持 `2023-11` 装饰器版本,Rsbuild 将 [decorators.version](https://rsbuild.rs/zh/config/source/decorators#decoratorsversion) 默认值从 `2022-03` 调整为 `2023-11`。 `2023-11` 是当前最新的提案版本,对应 2023 年 11 月 TC39 会议后的规范,同时也是 Babel 8 的默认行为。如果你需要保留旧行为,可以显式指定版本: rsbuild.config.ts export default { source: { decorators: { version: '2022-03', }, }, }; [#](https://rsbuild.rs/zh/blog/v2-0#%E5%8D%87%E7%BA%A7%E8%87%B3-rsbuild-20) 升级至 Rsbuild 2.0 ------------------------------------------------------------------------------------------- 对于大多数项目来说,升级到 Rsbuild 2.0 是一个相对平滑的过程。尽管 2.0 引入了一些默认行为调整和不兼容变更,但大多数变更都提供了清晰的迁移路径,通常无需修改业务代码。 如果你正在使用支持 skills 的 coding agent,可以安装 [rsbuild-v2-upgrade](https://github.com/rstackjs/agent-skills#rsbuild-v2-upgrade) skill,由 agent 自动协助完成依赖升级、配置调整和迁移检查,减少手动操作成本。 npx skills add rstackjs/agent-skills --skill rsbuild-v2-upgrade 完整的升级指南及所有不兼容变更,请参考 [从 v1 升级到 v2](https://rsbuild.rs/zh/guide/upgrade/v1-to-v2) 。 [#](https://rsbuild.rs/zh/blog/v2-0#%E8%87%B4%E8%B0%A2) 致谢 ---------------------------------------------------------- Rsbuild 由 Rstack 团队主导开发,同时也离不开社区贡献者与所有用户的共同参与。自 1.0 发布以来,许多开发者通过贡献推动了 Rsbuild 的演进,在此感谢所有参与其中的朋友: [@9aoy](https://github.com/9aoy) 、[@adammark](https://github.com/adammark) 、[@ahabhgk](https://github.com/ahabhgk) 、[@alexUXUI](https://github.com/alexUXUI) 、[@bodia-uz](https://github.com/bodia-uz) 、[@Brennvo](https://github.com/Brennvo) 、[@caohuilin](https://github.com/caohuilin) 、[@Cheese-Yu](https://github.com/Cheese-Yu) 、[@chenjiahan](https://github.com/chenjiahan) 、[@Chevindu](https://github.com/Chevindu) 、[@Colin3191](https://github.com/Colin3191) 、[@colinaaa](https://github.com/colinaaa) 、 [@CPunisher](https://github.com/CPunisher) 、[@davide97g](https://github.com/davide97g) 、[@Deku-nattsu](https://github.com/Deku-nattsu) 、[@DeveshSapkale](https://github.com/DeveshSapkale) 、[@dovigod](https://github.com/dovigod) 、[@Draculabo](https://github.com/Draculabo) 、[@easy1090](https://github.com/yifancong) 、[@escaton](https://github.com/escaton) 、[@fansenze](https://github.com/fansenze) 、[@fi3ework](https://github.com/fi3ework) 、[@gaoachao](https://github.com/gaoachao) 、[@GiveMe-A-Name](https://github.com/GiveMe-A-Name) 、 [@GRAMMAC1](https://github.com/GRAMMAC1) 、[@hai-x](https://github.com/hai-x) 、[@hangCode2001](https://github.com/nice-hang) 、[@hardfist](https://github.com/hardfist) 、[@hasnum-stack](https://github.com/hasnum-stack) 、[@htoooth](https://github.com/htoooth) 、[@Huxpro](https://github.com/Huxpro) 、[@ianzone](https://github.com/ianzone) 、[@iceprosurface](https://github.com/iceprosurface) 、[@inottn](https://github.com/inottn) 、[@jerrykingxyz](https://github.com/jerrykingxyz) 、[@jkzing](https://github.com/jkzing) 、 [@JounQin](https://github.com/JounQin) 、[@JSerFeng](https://github.com/JSerFeng) 、[@JSH-data](https://github.com/JSH-data) 、[@junhea](https://github.com/junhea) 、[@junxiongchu](https://github.com/junxiongchu) 、[@lguzzon](https://github.com/lguzzon) 、[@LingyuCoder](https://github.com/LingyuCoder) 、[@lluisemper](https://github.com/lluisemper) 、[@lxKylin](https://github.com/lxKylin) 、[@mhutter](https://github.com/mhutter) 、[@miownag](https://github.com/miownag) 、[@mycoin](https://github.com/mycoin) 、 [@nikhilsnayak](https://github.com/nikhilsnayak) 、[@notzheng](https://github.com/notzheng) 、[@Nsttt](https://github.com/Nsttt) 、[@nyqykk](https://github.com/nyqykk) 、[@puxiao](https://github.com/puxiao) 、[@qmakani](https://github.com/qmakani) 、[@quininer](https://github.com/quininer) 、[@RobHannay](https://github.com/RobHannay) 、[@roli-lpci](https://github.com/roli-lpci) 、[@s-chance](https://github.com/s-chance) 、[@s-r-x](https://github.com/s-r-x) 、[@sagar-dwivedi](https://github.com/sagar-dwivedi) 、 [@Sang-Sang33](https://github.com/Sang-Sang33) 、[@schu34](https://github.com/schu34) 、[@ScriptedAlchemy](https://github.com/ScriptedAlchemy) 、[@Shucei](https://github.com/Shucei) 、[@shulaoda](https://github.com/shulaoda) 、[@Simon-He95](https://github.com/Simon-He95) 、[@slobo](https://github.com/slobo) 、[@snatvb](https://github.com/snatvb) 、[@SoonIter](https://github.com/SoonIter) 、[@stormslowly](https://github.com/stormslowly) 、[@SyMind](https://github.com/SyMind) 、[@T9-Forever](https://github.com/T9-Forever) 、 [@thinkasany](https://github.com/thinkasany) 、[@Timeless0911](https://github.com/Timeless0911) 、[@TinsFox](https://github.com/TinsFox) 、[@valorkin](https://github.com/valorkin) 、[@vegerot](https://github.com/vegerot) 、[@VenDream](https://github.com/VenDream) 、[@wangi4myself](https://github.com/wangi4myself) 、[@wChenonly](https://github.com/wChenonly) 、[@wjw99830](https://github.com/wjw99830) 、[@wralith](https://github.com/wralith) 、[@wxiaoyun](https://github.com/wxiaoyun) 、[@xbzhang2020](https://github.com/xbzhang2020) 、 [@xc2](https://github.com/xc2) 、[@xettri](https://github.com/xettri) 、[@xiaohp](https://github.com/xiaohp) 、[@xuexb](https://github.com/xuexb) 、[@xun082](https://github.com/xun082) 、[@yifancong](https://github.com/yifancong) 、[@ymq001](https://github.com/ymq001) 、[@zackarychapple](https://github.com/zackarychapple) 、[@zalishchuk](https://github.com/zalishchuk) 、[@zoolsher](https://github.com/zoolsher) --- # React plugin - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/plugin-react.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/plugin-react#react-plugin) React plugin =========================================================================== Copy Markdown [Source Code](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-react) The React plugin provides support for React, integrating features such as JSX compilation and React Refresh. [#](https://rsbuild.rs/plugins/list/plugin-react#quick-start) Quick start ------------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-react#install-plugin) Install plugin Run the following command: npm yarn pnpm bun deno npm add @rsbuild/plugin-react -D yarn add @rsbuild/plugin-react -D pnpm add @rsbuild/plugin-react -D bun add @rsbuild/plugin-react -D deno add npm:@rsbuild/plugin-react -D ### [#](https://rsbuild.rs/plugins/list/plugin-react#register-plugin) Register plugin Register the plugin in Rsbuild config: rsbuild.config.ts import { pluginReact } from '@rsbuild/plugin-react'; export default { plugins: [pluginReact()], }; After registration, you can develop React directly. [#](https://rsbuild.rs/plugins/list/plugin-react#options) Options ----------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-react#swcreactoptions) swcReactOptions Configure the behavior of SWC to transform React code, the same as SWC's [jsc.transform.react](https://swc.rs/docs/configuration/compilation#jsctransformreact) option. * **Type:** interface ReactConfig { pragma?: string; pragmaFrag?: string; throwIfNamespace?: boolean; development?: boolean; refresh?: | boolean | { refreshReg?: string; refreshSig?: string; emitFullSignatures?: boolean; }; runtime?: 'automatic' | 'classic' | 'preserve'; importSource?: string; } * **Default:** Uses the automatic JSX runtime. Development transforms and Fast Refresh are enabled when applicable. ### [#](https://rsbuild.rs/plugins/list/plugin-react#swcreactoptionsruntime) swcReactOptions.runtime Decides which runtime to use when transforming JSX. * **Type:** `'automatic' | 'classic' | 'preserve'` * **Default:** `'automatic'` #### [#](https://rsbuild.rs/plugins/list/plugin-react#automatic) automatic By default, Rsbuild uses `runtime: 'automatic'` to leverage the [new JSX runtime](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) introduced in React 17. This approach eliminates the need to manually import React in every file that uses JSX. Tip React 16.14.0 and later versions support the new JSX runtime. #### [#](https://rsbuild.rs/plugins/list/plugin-react#classic) classic For React versions prior to 16.14.0, set `runtime` to `'classic'`: pluginReact({ swcReactOptions: { runtime: 'classic', }, }); When using the classic JSX runtime, you must manually import React in your code: App.jsx import React from 'react'; function App() { return

Hello World

; } #### [#](https://rsbuild.rs/plugins/list/plugin-react#preserve) preserve Use `runtime: 'preserve'` to leave JSX syntax unchanged without transforming it, this is useful when you are building a library that expects JSX to be left as is. pluginReact({ swcReactOptions: { runtime: 'preserve', }, }); ### [#](https://rsbuild.rs/plugins/list/plugin-react#swcreactoptionsimportsource) swcReactOptions.importSource * **Type:** `string` * **Default:** `'react'` With `runtime` set to `'automatic'`, you can specify the JSX runtime import path through `importSource`. For example, when using [Emotion](https://emotion.sh/) , you can set `importSource` to `'@emotion/react'`: pluginReact({ swcReactOptions: { importSource: '@emotion/react', }, }); > See [Customize JSX](https://rsbuild.rs/guide/framework/react#customize-jsx) > for more details. ### [#](https://rsbuild.rs/plugins/list/plugin-react#swcreactoptionsrefresh) swcReactOptions.refresh * **Type:** `boolean` * **Default:** enabled for development web builds when [fastRefresh](https://rsbuild.rs/plugins/list/plugin-react#fastrefresh) and [dev.hmr](https://rsbuild.rs/config/dev/hmr) are enabled Whether to enable [React Fast Refresh](https://npmjs.com/package/react-refresh) . Most of the time, you should use the plugin's [fastRefresh](https://rsbuild.rs/plugins/list/plugin-react#fastrefresh) option to enable or disable Fast Refresh. ### [#](https://rsbuild.rs/plugins/list/plugin-react#reactcompiler) reactCompiler Enable or configure [React Compiler](https://react.dev/learn/react-compiler) , which Rsbuild passes to Rspack's [`builtin:swc-loader`](https://rspack.rs/guide/tech/react#using-builtinswc-loader) as the `jsc.transform.reactCompiler` option. Tip This option is only supported in `@rsbuild/core` v2.1.0 and later. * **Type:** type ReactCompiler = | boolean | { compilationMode?: 'infer' | 'syntax' | 'annotation' | 'all'; panicThreshold?: 'none' | 'critical_errors' | 'all_errors'; target?: '17' | '18' | '19'; noEmit?: boolean; outputMode?: 'client' | 'ssr' | 'lint'; ignoreUseNoForget?: boolean; flowSuppressions?: boolean; enableReanimated?: boolean; isDev?: boolean; eslintSuppressionRules?: string[]; customOptOutDirectives?: string[]; gating?: { source: string; importSpecifierName: string; }; dynamicGating?: { source: string; }; }; * **Default:** `undefined` Set `reactCompiler` to `true` to enable React Compiler with the default options: pluginReact({ reactCompiler: true, }); For React 17 and 18 projects, install [`react-compiler-runtime`](https://npmjs.com/package/react-compiler-runtime) and set the compiler target: pluginReact({ reactCompiler: { target: '18', }, }); The `reactCompiler` options are aligned with the React Compiler configuration. For example, you can use [`compilationMode`](https://react.dev/reference/react-compiler/compilationMode) to control which functions are compiled: pluginReact({ reactCompiler: { compilationMode: 'annotation', }, }); For more options, refer to the official [React Compiler configuration documentation](https://react.dev/reference/react-compiler/configuration) . ### [#](https://rsbuild.rs/plugins/list/plugin-react#splitchunks) splitChunks When using Rsbuild's [default split chunks preset](https://rsbuild.rs/config/split-chunks#default) , this plugin splits `react` and `react-router` related packages into separate chunks: * `lib-react.js`: includes `react`, `react-dom`, and their sub-dependencies (`scheduler`). In development, it also includes React Fast Refresh runtime packages (`react-refresh`, `@rspack/plugin-react-refresh`). * `lib-router.js`: includes `react-router`, `react-router-dom`, and their sub-dependencies (`history`, `@remix-run/router`). This option is used to control this behavior and determine whether the `react` and `router` related packages need to be split into separate chunks. * **Type:** type SplitChunks = | boolean | { react?: boolean; router?: boolean; }; * **Default:** `true` (equivalent to `{ react: true, router: true }`) For example, to disable all chunk splitting: pluginReact({ splitChunks: false }); Or to disable only the `router` chunk splitting: pluginReact({ splitChunks: { react: true, router: false, }, }); ### [#](https://rsbuild.rs/plugins/list/plugin-react#enableprofiler) enableProfiler * **Type:** `boolean` * **Default:** `false` When set to `true`, enables the React Profiler for performance analysis in production builds. Use the React DevTools to examine profiling results and identify potential performance optimizations. Profiling adds a slight overhead, so it is disabled by default in production mode. rsbuild.config.ts pluginReact({ // Only enable the profiler when REACT_PROFILER is true, // as the option will increase the build time and add some small additional overhead. enableProfiler: process.env.REACT_PROFILER === 'true', }); Set `REACT_PROFILER=true` when running build script: package.json { "scripts": { "build:profiler": "REACT_PROFILER=true rsbuild build" } } As Windows does not support the above usage, you can also use [cross-env](https://npmjs.com/package/cross-env) to set environment variables. This ensures compatibility across different systems: package.json { "scripts": { "build:profiler": "cross-env REACT_PROFILER=true rsbuild build" }, "devDependencies": { "cross-env": "^7.0.0" } } > See the [React docs](https://legacy.reactjs.org/docs/optimizing-performance.html#profiling-components-with-the-devtools-profiler) > for details about profiling using the React DevTools. ### [#](https://rsbuild.rs/plugins/list/plugin-react#reactrefreshoptions) reactRefreshOptions * **Type:** type ReactRefreshOptions = { // @link https://rspack.rs/config/module-rules#condition test?: Rspack.RuleSetCondition; include?: Rspack.RuleSetCondition | null; exclude?: Rspack.RuleSetCondition | null; resourceQuery?: Rspack.RuleSetCondition; library?: string; forceEnable?: boolean; injectLoader?: boolean; injectEntry?: boolean; reloadOnRuntimeErrors?: boolean; reactRefreshLoader?: string; }; * **Default:** React Fast Refresh applies to files handled by Rsbuild's built-in JavaScript rule, except files imported with `?raw`. Set the options for [@rspack/plugin-react-refresh](https://github.com/rstackjs/rspack-plugin-react-refresh) . The passed value will be shallowly merged with the default value. * **Example:** pluginReact({ reactRefreshOptions: { exclude: [/some-module-to-exclude/, /[\\/]node_modules[\\/]/], }, }); ### [#](https://rsbuild.rs/plugins/list/plugin-react#fastrefresh) fastRefresh * **Type:** `boolean` * **Default:** `true` Whether to enable [React Fast Refresh](https://npmjs.com/package/react-refresh) in development mode. If `fastRefresh` is set to `true`, `@rsbuild/plugin-react` will automatically register the [@rspack/plugin-react-refresh](https://github.com/rstackjs/rspack-plugin-react-refresh) plugin for development web builds with HMR enabled. To disable Fast Refresh, set it to `false`: pluginReact({ fastRefresh: false, }); --- # SVGR plugin - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/plugin-svgr.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/plugin-svgr#svgr-plugin) SVGR plugin ======================================================================== Copy Markdown [Source Code](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-svgr) By default, Rsbuild treats SVG files as static assets. For processing rules, see [Static assets](https://rsbuild.rs/guide/basic/static-assets) . With the SVGR plugin, Rsbuild supports transforming SVG to React components via [SVGR](https://react-svgr.com/) . [#](https://rsbuild.rs/plugins/list/plugin-svgr#quick-start) Quick start ------------------------------------------------------------------------ ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#install-plugin) Install plugin Run the following command: npm yarn pnpm bun deno npm add @rsbuild/plugin-svgr -D yarn add @rsbuild/plugin-svgr -D pnpm add @rsbuild/plugin-svgr -D bun add @rsbuild/plugin-svgr -D deno add npm:@rsbuild/plugin-svgr -D ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#register-plugin) Register plugin Register the plugin in Rsbuild config: rsbuild.config.ts import { pluginReact } from '@rsbuild/plugin-react'; import { pluginSvgr } from '@rsbuild/plugin-svgr'; export default { plugins: [pluginReact(), pluginSvgr()], }; [#](https://rsbuild.rs/plugins/list/plugin-svgr#example) Example ---------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#default-usage) Default usage After registration, when a JavaScript import references an SVG with the `?react` suffix, Rsbuild calls SVGR to transform the SVG into a React component. App.jsx import Logo from './logo.svg?react'; export const App = () => ; If the imported path doesn't include the `?react` suffix, the SVG will be treated as a normal static asset and you will get a URL string or base64 URL. See [Static assets](https://rsbuild.rs/guide/basic/static-assets) . import logoURL from './static/logo.svg'; console.log(logoURL); // => "/static/svg/logo.6c12aba3ab.svg" or a base64 URL ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#named-import) Named import `@rsbuild/plugin-svgr` supports named imports for `ReactComponent` when using SVGR. You need to set [svgrOptions.exportType](https://rsbuild.rs/plugins/list/plugin-svgr#svgroptionsexporttype) to `'named'`: pluginSvgr({ svgrOptions: { exportType: 'named', }, }); App.jsx import { ReactComponent as Logo } from './logo.svg'; export const App = () => ; `@rsbuild/plugin-svgr` also supports default imports and mixed imports: * Enable default imports by setting [svgrOptions.exportType](https://rsbuild.rs/plugins/list/plugin-svgr#svgroptionsexporttype) to `'default'`. * Enable mixed imports by setting the [mixedImport](https://rsbuild.rs/plugins/list/plugin-svgr#mixedimport) option to use both default and named imports at the same time. [#](https://rsbuild.rs/plugins/list/plugin-svgr#options) Options ---------------------------------------------------------------- To customize the compilation behavior of Svgr, use the following options. * **Type:** type PluginSvgrOptions = { /** * Configure SVGR options. */ svgrOptions?: import('@svgr/core').Config; /** * Whether to allow the use of default import and named import at the same time. * @default false */ mixedImport?: boolean; /** * Custom query suffix to match SVGR transformation. * @default /react/ */ query?: RegExp; /** * Whether to transform SVG modules into React components in parallel. * @default false */ parallel?: boolean; /** * Exclude specific SVG files from SVGR transformation. */ exclude?: Rspack.RuleSetCondition; /** * Exclude some modules, the SVGs imported by these modules will not be transformed by SVGR. */ excludeImporter?: Rspack.RuleSetCondition; }; ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#svgroptions) svgrOptions Modifies the options of SVGR, the passed object will be deep merged with the default value. See [SVGR - Options](https://react-svgr.com/docs/options/) for details. * **Type:** `import('@svgr/core').Config` * **Default:** const defaultSvgrOptions = { svgo: true, svgoConfig: { plugins: [\ {\ name: 'preset-default',\ params: {\ overrides: {\ removeViewBox: false,\ },\ },\ },\ 'prefixIds',\ ], }, }; * **Example:** pluginSvgr({ svgrOptions: { svgoConfig: { datauri: 'base64', }, }, }); When you set `svgoConfig.plugins`, the configuration for plugins with the same name is automatically merged. For example, the following configuration will be merged with the built-in `preset-default`: pluginSvgr({ svgrOptions: { svgoConfig: { plugins: [\ {\ name: 'preset-default',\ params: {\ overrides: {\ cleanupIds: false,\ },\ },\ },\ ], }, }, }); The merged `svgoConfig` will be: const mergedSvgoConfig = { plugins: [\ {\ name: 'preset-default',\ params: {\ overrides: {\ removeViewBox: false,\ cleanupIds: false,\ },\ },\ },\ 'prefixIds',\ ], }; ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#svgroptionsexporttype) svgrOptions.exportType Set the export type of SVG React components. * **Type:** `'default' | 'named'` * **Default:** `undefined` `exportType` can be set as: * `default`: use default export. * `named`: use `ReactComponent` named export. For example, set the default export of SVG file as a React component: pluginSvgr({ svgrOptions: { exportType: 'default', }, }); Then import the SVG, you'll get a React component instead of a URL: import Logo from './logo.svg'; console.log(Logo); // => React Component At this time, you can also specify the `?url` query to import the URL, for example: import logo from './logo.svg?url'; console.log(logo); // => asset url Tip When `svgrOptions.exportType` is set to `'default'`, the named imports (ReactComponent) cannot be used. ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#mixedimport) mixedImport * **Type:** `boolean` * **Default:** `false` Whether to enable mixed import, allowing to use default import and named import at the same time. Mixed import is usually used with `svgrOptions.exportType: 'named'`, for example: pluginSvgr({ mixedImport: true, svgrOptions: { exportType: 'named', }, }); At this time, the imported SVG file will export both URL and the React component: import logoUrl, { ReactComponent as Logo } from './logo.svg'; console.log(logoUrl); // -> string console.log(Logo); // -> React component Tip When `mixedImport` is enabled, `svgrOptions.exportType` defaults to `'named'` if not explicitly configured. #### [#](https://rsbuild.rs/plugins/list/plugin-svgr#limitations) Limitations We recommend using `?react` to convert an SVG into a React component rather than relying on mixed imports, which have the following limitations: 1. Increased bundle size: Mixed import causes a single SVG module to be compiled into two types of code (even if some exports are not used), which will increase the bundle size. 2. Slow down compiling: Mixed import will cause extra compilation overhead. Even if the ReactComponent export is not used in the code, the SVG file will still be compiled by SVGR. And SVGR is based on Babel, which has a high performance overhead. ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#query) query * **Type:** `RegExp` * **Default:** `/react/` Customize the query suffix used to match SVGR transformation. For example, if you need to match import paths with the `?svgr` suffix: pluginSvgr({ query: /svgr/, }); App.jsx import Logo from './logo.svg?svgr'; export const App = () => ; ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#parallel) parallel * **Type:** `boolean` * **Default:** `false` * **Version:** Added in v2.0.4 Whether to transform SVG modules into React components in parallel using worker threads. When enabled, SVG modules are processed across multiple worker threads, reducing pressure on the main thread and improving overall build performance when compiling large numbers of SVG modules. pluginSvgr({ parallel: true, }); > This feature is based on Rspack's parallel loader. Options transferred to worker threads must comply with the [HTML structured clone algorithm](https://nodejs.org/api/worker_threads.html#portpostmessagevalue-transferlist) > . Otherwise, transmission will fail. For example, functions cannot be passed as options. See [Rspack - Rule.use.parallel](https://rspack.rs/config/module-rules#rulesuseparallel) > for more details. ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#exclude) exclude * **Type:** [Rspack.RuleSetCondition](https://rspack.rs/config/module-rules#condition) * **Default:** `undefined` Exclude specific SVG files from SVGR transformation. For example, if a project includes `a.svg` and `b.svg`, you can add `b.svg` to exclude: pluginSvgr({ svgrOptions: { exportType: 'default', }, exclude: /b\.svg/, }); When imported, `a.svg` will be transformed into a React component, while `b.svg` will be treated as a regular static asset: src/index.ts import component from './a.svg'; import url from './b.svg'; console.log(component); // => React component console.log(url); // => resource url ### [#](https://rsbuild.rs/plugins/list/plugin-svgr#excludeimporter) excludeImporter * **Type:** [Rspack.RuleSetCondition](https://rspack.rs/config/module-rules#condition) * **Default:** `undefined` Exclude some modules, the SVGs imported by these modules will not be transformed by SVGR. For example, if your project contains `page-a/index.ts` and `page-b/index.ts`, you can add `page-b` to excludeImporter: pluginSvgr({ svgrOptions: { exportType: 'default', }, excludeImporter: /\/page-b\/index\.ts/, }); * SVGs referenced in page-a will be transformed to React components: page-a/index.ts import Logo from './logo.svg'; console.log(Logo); // => React component * SVGs referenced in page-b will be treated as static assets: page-b/index.ts import url from './logo.svg'; console.log(url); // => Resource url Tip The query in the module path has a higher priority than `exclude` and `excludeImporter`. For example, if a module is excluded, adding `?react` can still make it transformed by SVGR. [#](https://rsbuild.rs/plugins/list/plugin-svgr#type-declaration) Type declaration ---------------------------------------------------------------------------------- When you reference an SVG asset in TypeScript code, TypeScript may prompt that the module is missing a type definition: TS2307: Cannot find module './logo.svg' or its corresponding type declarations. To fix this, add type declarations for the SVG assets by creating a `src/env.d.ts` file and adding the declarations below. * By default, you can add the following type declarations: declare module '*.svg' { const content: string; export default content; } declare module '*.svg?react' { const ReactComponent: React.FunctionComponent>; export default ReactComponent; } * If the value of `svgrOptions.exportType` is `'default'`, set the type declaration to: declare module '*.svg' { const ReactComponent: React.FunctionComponent>; export default ReactComponent; } declare module '*.svg?react' { const ReactComponent: React.FunctionComponent>; export default ReactComponent; } * If the value of `svgrOptions.exportType` is `'named'`, set the type declaration to: declare module '*.svg' { export const ReactComponent: React.FunctionComponent< React.SVGProps >; } declare module '*.svg?react' { const ReactComponent: React.FunctionComponent>; export default ReactComponent; } * If the value of `svgrOptions.exportType` is `'named'`, and `mixedImport` is enabled, set the type declaration to: declare module '*.svg' { export const ReactComponent: React.FunctionComponent< React.SVGProps >; const content: string; export default content; } declare module '*.svg?react' { const ReactComponent: React.FunctionComponent>; export default ReactComponent; } After adding the type declarations, if the type error still exists, you can try to restart the IDE, or adjust the directory where `env.d.ts` is located, making sure that TypeScript can correctly identify the type definition. --- # Plugin development - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/dev/index.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/dev/#plugin-development) Plugin development ========================================================================== Copy Markdown Rsbuild's architecture is centered on a plugin system. Most of Rsbuild's functionality is implemented through plugins, which keeps the core lightweight while providing flexible extensibility. Rsbuild plugins are functions that can register hooks at different stages, listen to events, and execute custom logic. If you want to modify the default behavior, add new features, or integrate third-party tools, plugins provide a comprehensive API to fulfill these requirements. [#](https://rsbuild.rs/plugins/dev/#comparison) Comparison ---------------------------------------------------------- Before developing a Rsbuild plugin, you may have been familiar with the plugin systems of tools such as webpack, Vite, esbuild, etc. Rsbuild's plugin API is similar to esbuild's, and compared with webpack or Rspack plugins, Rsbuild's plugin API is simpler and easier to get started with. // esbuild plugin const esbuildPlugin = { name: 'example', setup(build) { build.onEnd(() => console.log('done')); }, }; // Rsbuild plugin const rsbuildPlugin = () => ({ name: 'example', setup(api) { api.onAfterBuild(() => console.log('done')); }, }); // Rspack plugin class RspackExamplePlugin { apply(compiler) { compiler.hooks.done.tap('RspackExamplePlugin', () => { console.log('done'); }); } } From a functional perspective, Rsbuild's plugin API mainly revolves around Rsbuild's operation process and build configuration, providing various hooks for extension. On the other hand, Rspack's plugin API is more complex and comprehensive, capable of modifying every aspect of the bundling process. Rspack plugins can be integrated into Rsbuild plugins. If the hooks provided by Rsbuild do not meet your requirements, you can also implement the functionality using Rspack plugin and register Rspack plugins in the Rsbuild plugin: const rsbuildPlugin = () => ({ name: 'example', setup(api) { api.modifyRspackConfig((config) => { config.plugins.push(new RspackExamplePlugin()); }); }, }); [#](https://rsbuild.rs/plugins/dev/#developing-plugins) Developing plugins -------------------------------------------------------------------------- Plugins provide a function similar to `(options?: PluginOptions) => RsbuildPlugin` as an entry point. ### [#](https://rsbuild.rs/plugins/dev/#plugin-example) Plugin example pluginFoo.ts import type { RsbuildPlugin } from '@rsbuild/core'; export type PluginFooOptions = { message?: string; }; export const pluginFoo = (options: PluginFooOptions = {}): RsbuildPlugin => ({ name: 'plugin-foo', setup(api) { api.onAfterStartDevServer(() => { const msg = options.message || 'hello!'; console.log(msg); }); }, }); Registering the plugin: rsbuild.config.ts import { pluginFoo } from './pluginFoo'; export default { plugins: [pluginFoo({ message: 'world!' })], }; ### [#](https://rsbuild.rs/plugins/dev/#plugin-structure) Plugin structure Function-based plugins can **accept an options object** and **return a plugin instance**, managing internal state through closures. The roles of each part are as follows: * The `name` property is used to label the plugin's name. * `setup` serves as the main entry point for the plugin logic. * The `api` object contains various hooks and utility functions. ### [#](https://rsbuild.rs/plugins/dev/#naming-convention) Naming convention The naming convention for plugins is as follows: * The function of the plugin is named `pluginAbc` and exported by name. * The `name` of the plugin follows the format `scope:foo-bar` or `plugin-foo-bar`, adding `scope:` can avoid naming conflicts with other plugins. Here is an example: pluginFooBar.ts import type { RsbuildPlugin } from '@rsbuild/core'; export const pluginFooBar = (): RsbuildPlugin => ({ name: 'scope:foo-bar', setup() {}, }); Tip The `name` of official Rsbuild plugins uniformly uses `rsbuild:` as a prefix, for example, `rsbuild:react` corresponds to `@rsbuild/plugin-react`. ### [#](https://rsbuild.rs/plugins/dev/#template-repository) Template repository [rsbuild-plugin-template](https://github.com/rstackjs/rsbuild-plugin-template) is a minimal Rsbuild plugin template repository that you can use as a basis for developing your Rsbuild plugin. ### [#](https://rsbuild.rs/plugins/dev/#environment-plugin) Environment plugin Rsbuild supports building outputs for multiple environments at the same time, and supports [add plugins for specified environment](https://rsbuild.rs/guide/advanced/environments#plugins-specified-environment) . If you want the plugin you develop to support use as an Environment plugin, you need to pay attention to the following points: 1. Each environment has its own Rsbuild config: * Use [environment context](https://rsbuild.rs/guide/advanced/environments#environment-context) instead of `getRsbuildConfig` to get environment information. * When modifying the Rsbuild config for a specific environment, prioritize using [modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) instead of [modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) to avoid affecting other environments. 2. Be aware of side effects, your plugin code may be executed multiple times: * When the same plugin is registered multiple times in different environments, it will be regarded as multiple Rsbuild plugins (even if they point to the same plugin instance), because they have different Rsbuild environment contexts. Here is an example: pluginFoo.ts import type { RsbuildPlugin } from '@rsbuild/core'; export type PluginFooOptions = { title?: string; }; export const pluginFoo = (options: PluginFooOptions = {}): RsbuildPlugin => ({ name: 'plugin-foo', setup(api) { api.modifyEnvironmentConfig((config) => { config.html.title = options.title || 'My Default Title'; }); api.modifyBundlerChain((chain, { environment }) => { chain.name(environment.config.html.title); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/#reference-other-plugins) Reference other plugins Rsbuild's [plugins](https://rsbuild.rs/config/plugins) config supports passing a nested array, which means you can reference and register other Rsbuild plugins within your plugin. For example, register `pluginBar` within `pluginFoo`: import { pluginBar } from 'rsbuild-plugin-bar'; export const pluginFoo = (): RsbuildPlugin => { const foo = { name: 'plugin-foo', setup(api) { // ... }, }; return [foo, pluginBar()]; }; [#](https://rsbuild.rs/plugins/dev/#lifetime-hooks) Lifetime hooks ------------------------------------------------------------------ Rsbuild internally uses lifecycle hooks to schedule tasks, and plugins can also register hooks to take part in any stage of the workflow and implement their own features. The full list of Rsbuild's lifetime hooks can be found in the [API References](https://rsbuild.rs/plugins/dev/hooks) . Rsbuild does not take over the hooks of the underlying Rspack, whose documents can be found here: [Rspack Plugin API](https://rspack.rs/api/plugin-api) . [#](https://rsbuild.rs/plugins/dev/#migrate-vite-plugin) Migrate Vite plugin ---------------------------------------------------------------------------- See [Migrate Vite plugin](https://rsbuild.rs/guide/migration/vite-plugin) to learn how to migrate a Vite plugin to Rsbuild plugin. [#](https://rsbuild.rs/plugins/dev/#read-and-modify-rsbuild-config) Read and modify Rsbuild config -------------------------------------------------------------------------------------------------- When a plugin needs to read or modify the project's Rsbuild config, use Rsbuild's config APIs. ### [#](https://rsbuild.rs/plugins/dev/#modify-the-base-config) Modify the base config Register [api.modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) during `setup` to modify the base config before it is merged with each environment's config: api.modifyRsbuildConfig((config) => { config.output.minify = false; }); `modifyRsbuildConfig` is a global hook. If a change applies only to certain environments or depends on the current environment, use [api.modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) instead. See [Global hooks vs environment hooks](https://rsbuild.rs/plugins/dev/hooks#global-hooks-vs-environment-hooks) for details. ### [#](https://rsbuild.rs/plugins/dev/#read-the-normalized-config) Read the normalized config After the config modification hooks have run, call [api.getNormalizedConfig](https://rsbuild.rs/plugins/dev/core#apigetnormalizedconfig) without arguments to get the complete normalized config for all environments. It includes default values, so its type is narrower than the value returned by [api.getRsbuildConfig](https://rsbuild.rs/plugins/dev/core#apigetrsbuildconfig) . api.onBeforeBuild(() => { const config = api.getNormalizedConfig(); console.log(Object.keys(config.environments)); }); If no environment context is available but you need the config for one environment, pass its name to `getNormalizedConfig`: api.onBeforeBuild(() => { const config = api.getNormalizedConfig({ environment: 'web' }); console.log(config.output.target); }); See [NormalizedConfig](https://rsbuild.rs/api/javascript-api/types#normalizedconfig) and [NormalizedEnvironmentConfig](https://rsbuild.rs/api/javascript-api/types#normalizedenvironmentconfig) for their return types. ### [#](https://rsbuild.rs/plugins/dev/#current-environment-config) Read the current environment config When a hook callback includes an [environment context](https://rsbuild.rs/api/javascript-api/environment-api#environment-context) , prefer `environment.config`. It is the normalized result of merging the base config with the [current environment's config](https://rsbuild.rs/guide/advanced/environments) . api.onBeforeEnvironmentCompile(({ environment }) => { const { name, config } = environment; console.log(`${name}: ${config.output.target}`); }); ### [#](https://rsbuild.rs/plugins/dev/#read-all-environment-configs) Read all environment configs Global hooks such as [onBeforeBuild](https://rsbuild.rs/plugins/dev/hooks#onbeforebuild) and [onAfterBuild](https://rsbuild.rs/plugins/dev/hooks#onafterbuild) receive `environments`, which contains the context for every environment. Iterate over it when a plugin needs to read each environment's config: api.onBeforeBuild(({ environments }) => { for (const { name, config } of Object.values(environments)) { console.log(`${name}: ${config.output.distPath.root}`); } }); See [Multi-environment builds](https://rsbuild.rs/guide/advanced/environments) for more details about environment configs. [#](https://rsbuild.rs/plugins/dev/#modify-rspack-configuration) Modify Rspack configuration -------------------------------------------------------------------------------------------- Rsbuild plugin allows you to modify the built-in Rspack configuration, including: * [api.modifyRspackConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrspackconfig) : Modify the Rspack configuration object. * [api.modifyBundlerChain](https://rsbuild.rs/plugins/dev/hooks#modifybundlerchain) : Modify the Rspack configuration through [rspack-chain](https://github.com/rstackjs/rspack-chain) . ### [#](https://rsbuild.rs/plugins/dev/#example) Example For example, register [eslint-rspack-plugin](https://github.com/rstackjs/eslint-rspack-plugin) via Rsbuild plugin: import type { RsbuildPlugin } from '@rsbuild/core'; import ESLintRspackPlugin from 'eslint-rspack-plugin'; export const pluginEslint = (options?: Options): RsbuildPlugin => ({ name: 'plugin-eslint', setup(api) { api.modifyRspackConfig((config) => { config.plugins.push( new ESLintRspackPlugin({ // plugins options }), ); }); }, }); [#](https://rsbuild.rs/plugins/dev/#extending-plugin-api) Extending plugin API ------------------------------------------------------------------------------ When building custom tools on top of Rsbuild's [JavaScript API](https://rsbuild.rs/api/start/) , you may want to extend the existing plugin API to provide additional capabilities — for example, exposing utility functions or sharing context objects. You can achieve this by using the [rsbuild.expose()](https://rsbuild.rs/api/javascript-api/instance#rsbuildexpose) method on the Rsbuild instance. This method works the same way as the plugin's [api.expose()](https://rsbuild.rs/plugins/dev/core#apiexpose) , allowing you to expose custom methods or objects to Rsbuild plugins. For example, you can expose `getState` and `setCount` methods: myToolkit.ts import { createRsbuild } from '@rsbuild/core'; export const MY_TOOLKIT_ID = 'my-toolkit'; const rsbuild = await createRsbuild({ // ... }); const state = { count: 0, }; rsbuild.expose(MY_TOOLKIT_ID, { getState() { return state; }, setCount(count: number) { state.count = count; }, }); Plugins can then access these extended APIs using the [api.useExposed()](https://rsbuild.rs/plugins/dev/core#apiuseexposed) method: myPlugin.ts import { MY_TOOLKIT_ID } from './myToolkit'; const myPlugin = { name: 'my-plugin', setup(api) { const toolkitApi = api.useExposed(MY_TOOLKIT_ID); if (toolkitApi) { const { count } = toolkitApi.getState(); toolkitApi.setCount(count + 1); } }, }; [#](https://rsbuild.rs/plugins/dev/#dependency-declaration) Dependency declaration ---------------------------------------------------------------------------------- When publishing an Rsbuild plugin, you should declare `@rsbuild/core` in `peerDependencies` in `package.json`, and install it in `devDependencies` for local development: { "peerDependencies": { "@rsbuild/core": "^2.0.0" }, "devDependencies": { "@rsbuild/core": "^2.0.0" } } If your plugin only references types from `@rsbuild/core`, you can declare it as an optional peer dependency: { "peerDependencies": { "@rsbuild/core": "^2.0.0" }, "peerDependenciesMeta": { "@rsbuild/core": { "optional": true } } } In this case, the plugin will not produce unnecessary peer dependency warnings when it is used by higher-level tools based on Rsbuild, such as Rslib or Rspress. --- # 总览 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/index.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/#%E6%80%BB%E8%A7%88) 总览 ============================================================== 复制 Markdown [#](https://rsbuild.rs/zh/plugins/list/#%E6%8F%92%E4%BB%B6%E7%B3%BB%E7%BB%9F) 插件系统 ---------------------------------------------------------------------------------- 你可以阅读 [插件开发](https://rsbuild.rs/zh/plugins/dev/) 来了解 Rsbuild 插件的功能,以及如何开发一个 Rsbuild 插件。 [#](https://rsbuild.rs/zh/plugins/list/#%E4%BD%BF%E7%94%A8%E6%8F%92%E4%BB%B6) 使用插件 ---------------------------------------------------------------------------------- 在 Rsbuild 配置中通过 [plugins](https://rsbuild.rs/zh/config/plugins) 选项注册插件。 使用 Rsbuild 的 JavaScript API 时,通过 [addPlugins](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildaddplugins) 方法注册插件。 [#](https://rsbuild.rs/zh/plugins/list/#%E5%AE%98%E6%96%B9%E6%8F%92%E4%BB%B6) 官方插件 ---------------------------------------------------------------------------------- 以下是 Rsbuild 官方提供的插件。 ### [#](https://rsbuild.rs/zh/plugins/list/#react) React 适用于 React 框架的插件有: * [@rsbuild/plugin-react](https://rsbuild.rs/zh/plugins/list/plugin-react) :提供对 React 的支持。 * [@rsbuild/plugin-svgr](https://rsbuild.rs/zh/plugins/list/plugin-svgr) :支持将 SVG 图片转换为一个 React 组件使用。 * [@rsbuild/plugin-styled-components](https://github.com/rsbuild-contrib/rsbuild-plugin-styled-components) :提供对 styled-components 的编译时支持。 ### [#](https://rsbuild.rs/zh/plugins/list/#vue) Vue 适用于 Vue 框架的插件有: * [@rsbuild/plugin-vue](https://rsbuild.rs/zh/plugins/list/plugin-vue) :提供对 Vue 3 SFC(单文件组件)的支持。 * [@rsbuild/plugin-vue-jsx](https://github.com/rstackjs/rsbuild-plugin-vue-jsx) :提供对 Vue 3 JSX / TSX 语法的支持。 * [@rsbuild/plugin-vue2](https://github.com/rstackjs/rsbuild-plugin-vue2) :提供对 Vue 2 SFC(单文件组件)的支持。 * [@rsbuild/plugin-vue2-jsx](https://github.com/rstackjs/rsbuild-plugin-vue2-jsx) :提供对 Vue 2 JSX / TSX 语法的支持。 ### [#](https://rsbuild.rs/zh/plugins/list/#preact) Preact 适用于 Preact 框架的插件有: * [@rsbuild/plugin-preact](https://rsbuild.rs/zh/plugins/list/plugin-preact) :提供对 Preact 的支持。 ### [#](https://rsbuild.rs/zh/plugins/list/#svelte) Svelte 适用于 Svelte 框架的插件有: * [@rsbuild/plugin-svelte](https://rsbuild.rs/zh/plugins/list/plugin-svelte) :提供对 Svelte 组件(`.svelte` 文件)的支持。 ### [#](https://rsbuild.rs/zh/plugins/list/#solid) Solid 适用于 Solid 框架的插件有: * [@rsbuild/plugin-solid](https://rsbuild.rs/zh/plugins/list/plugin-solid) :提供对 Solid 的支持。 ### [#](https://rsbuild.rs/zh/plugins/list/#%E9%80%9A%E7%94%A8%E6%8F%92%E4%BB%B6) 通用插件 以下是与框架无关的通用插件: * [@rsbuild/plugin-assets-retry](https://github.com/rstackjs/rsbuild-plugin-assets-retry) :用于在静态资源加载失败时自动发起重试请求。 * [@rsbuild/plugin-babel](https://rsbuild.rs/zh/plugins/list/plugin-babel) :提供对 Babel 转译能力的支持。 * [@rsbuild/plugin-tailwindcss](https://rsbuild.rs/zh/plugins/list/plugin-tailwindcss) :使用 Tailwind CSS v4。 * [@rsbuild/plugin-sass](https://rsbuild.rs/zh/plugins/list/plugin-sass) :使用 Sass 作为 CSS 预处理器。 * [@rsbuild/plugin-less](https://rsbuild.rs/zh/plugins/list/plugin-less) :使用 Less 作为 CSS 预处理器。 * [@rsbuild/plugin-basic-ssl](https://github.com/rstackjs/rsbuild-plugin-basic-ssl) : 为 HTTPS server 生成不受信任的自签名证书。 * [@rsbuild/plugin-eslint](https://github.com/rstackjs/rsbuild-plugin-eslint) :用于在编译过程中运行 ESLint 检查。 * [@rsbuild/plugin-type-check](https://github.com/rstackjs/rsbuild-plugin-type-check) :用于在单独的进程中运行 TypeScript 类型检查。 * [@rsbuild/plugin-image-compress](https://github.com/rstackjs/rsbuild-plugin-image-compress) :压缩图片资源。 * [@rsbuild/plugin-mdx](https://github.com/rstackjs/rsbuild-plugin-mdx) :提供 MDX 支持。 * [@rsbuild/plugin-node-polyfill](https://github.com/rstackjs/rsbuild-plugin-node-polyfill) :用于注入 Node 核心模块在浏览器端的 polyfills。 * [@rsbuild/plugin-source-build](https://github.com/rstackjs/rsbuild-plugin-source-build) :用于 monorepo 场景,支持引用其他子目录的源代码,并完成构建和热更新。 * [@rsbuild/plugin-check-syntax](https://github.com/rstackjs/rsbuild-plugin-check-syntax) :检查构建产物的语法兼容性,判断是否存在导致兼容性问题的高级语法。 * [@rsbuild/plugin-css-minimizer](https://github.com/rstackjs/rsbuild-plugin-css-minimizer) :用于自定义 CSS 压缩工具,切换到 [cssnano](https://github.com/cssnano/cssnano) 或其他工具进行 CSS 压缩。 * [@rsbuild/plugin-typed-css-modules](https://github.com/rstackjs/rsbuild-plugin-typed-css-modules) :用于为 CSS Modules 文件生成类型声明。 * [@rsbuild/plugin-pug](https://github.com/rstackjs/rsbuild-plugin-pug) :提供对 Pug 模板引擎的支持。 * [@rsbuild/plugin-rem](https://github.com/rstackjs/rsbuild-plugin-rem) :用于实现移动端页面的 rem 自适应布局。 * [@rsbuild/plugin-umd](https://github.com/rstackjs/rsbuild-plugin-umd) :用于构建 UMD 格式的产物。 * [@rsbuild/plugin-yaml](https://github.com/rstackjs/rsbuild-plugin-yaml) :引用 YAML 文件,并将其转换为 JavaScript 对象。 * [@rsbuild/plugin-toml](https://github.com/rstackjs/rsbuild-plugin-toml) :引用 TOML 文件,并将其转换为 JavaScript 对象。 Tip 你可以在 [web-infra-dev/rsbuild](https://github.com/web-infra-dev/rsbuild) 和 [rstackjs](https://github.com/rstackjs) 中找到这些插件的源代码。 [#](https://rsbuild.rs/zh/plugins/list/#%E7%A4%BE%E5%8C%BA%E6%8F%92%E4%BB%B6) 社区插件 ---------------------------------------------------------------------------------- 你可以在 [awesome-rstack - Rsbuild Plugins](https://github.com/rstackjs/awesome-rstack#rsbuild-plugins) 中查看社区提供的 Rsbuild 插件。 也可以在 npm 上搜索 [rsbuild-plugin](https://npmjs.com/search?q=rsbuild-plugin&ranking=popularity) 关键词来发现更多 Rsbuild 插件。 ### [#](https://rsbuild.rs/zh/plugins/list/#react-1) React * [rsbuild-plugin-react-router](https://github.com/rstackjs/rsbuild-plugin-react-router) :提供与 React Router 的集成。 ### [#](https://rsbuild.rs/zh/plugins/list/#angular) Angular * [@ng-rsbuild/plugin-angular](https://github.com/nrwl/angular-rspack) :允许你轻松直接地构建 Angular 应用程序。 --- # Preact 插件 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/plugin-preact.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/plugin-preact#preact-%E6%8F%92%E4%BB%B6) Preact 插件 ========================================================================================= 复制 Markdown [源码](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-preact) Preact 插件提供了对 Preact 的支持,插件内部集成了 JSX 编译、React aliasing 等功能。 [#](https://rsbuild.rs/zh/plugins/list/plugin-preact#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) 快速开始 ----------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-preact#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 安装插件 执行以下命令安装插件: npm yarn pnpm bun deno npm add @rsbuild/plugin-preact -D yarn add @rsbuild/plugin-preact -D pnpm add @rsbuild/plugin-preact -D bun add @rsbuild/plugin-preact -D deno add npm:@rsbuild/plugin-preact -D Tip `@rsbuild/plugin-preact` v2 不再支持 Rsbuild 1.x。如果你的项目仍在使用 Rsbuild 1.x,请安装 `@rsbuild/plugin-preact@1`。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-preact#%E6%B3%A8%E5%86%8C%E6%8F%92%E4%BB%B6) 注册插件 在 Rsbuild 配置中注册插件: rsbuild.config.ts import { pluginPreact } from '@rsbuild/plugin-preact'; export default { plugins: [pluginPreact()], }; 注册后,即可进行 Preact 开发。 [#](https://rsbuild.rs/zh/plugins/list/plugin-preact#%E9%80%89%E9%A1%B9) 选项 --------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-preact#reactaliasesenabled) reactAliasesEnabled 是否将 `react`、`react-dom` 通过 alias 指向 `preact/compat`。 * **类型:** `boolean` * **默认值:** `true` * **示例:** 禁用别名。 pluginPreact({ reactAliasesEnabled: false, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-preact#prefreshenabled) prefreshEnabled 是否注入 [Prefresh](https://github.com/preactjs/prefresh) 用于 HMR。 * **类型:** `boolean` * **默认值:** `true` * **版本:** `>= v1.1.0` * **示例:** 禁用 Prefresh。 pluginPreact({ prefreshEnabled: false, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-preact#preactrefreshoptions) preactRefreshOptions 设置 [@rspack/plugin-preact-refresh](https://github.com/rstackjs/rspack-plugin-preact-refresh) 的选项。该值会传递给 Rspack 插件,其中 `preactPath` 会由 Rsbuild 自动配置。 * **类型:** type PreactRefreshOptions = { // @link https://rspack.rs/zh/config/module-rules#condition test?: Rspack.RuleSetCondition; include?: Rspack.RuleSetCondition | null; exclude?: Rspack.RuleSetCondition | null; overlay?: { module: string; }; }; * **默认值:** 默认值与 `@rspack/plugin-preact-refresh` 保持一致: const defaultOptions = { test: /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, exclude: /[\\/]node_modules[\\/]/, }; * **示例:** pluginPreact({ preactRefreshOptions: { test: /\.(?:jsx|tsx)$/, include: /src/, exclude: /node_modules/, }, }); --- # Vue 插件 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/plugin-vue.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/plugin-vue#vue-%E6%8F%92%E4%BB%B6) Vue 插件 ================================================================================ 复制 Markdown [源码](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-vue) Vue 插件提供了对 Vue 3 SFC(单文件组件)的支持,插件内部集成了 [rspack-vue-loader](https://npmjs.com/package/rspack-vue-loader) 。 Tip 对于 Vue 3 JSX / TSX 语法,请使用 [Vue JSX 插件](https://github.com/rstackjs/rsbuild-plugin-vue-jsx) 。 [#](https://rsbuild.rs/zh/plugins/list/plugin-vue#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) 快速开始 -------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-vue#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 安装插件 执行以下命令安装插件: npm yarn pnpm bun deno npm add @rsbuild/plugin-vue -D yarn add @rsbuild/plugin-vue -D pnpm add @rsbuild/plugin-vue -D bun add @rsbuild/plugin-vue -D deno add npm:@rsbuild/plugin-vue -D ### [#](https://rsbuild.rs/zh/plugins/list/plugin-vue#%E6%B3%A8%E5%86%8C%E6%8F%92%E4%BB%B6) 注册插件 在 Rsbuild 配置中注册插件: rsbuild.config.ts import { pluginVue } from '@rsbuild/plugin-vue'; export default { plugins: [pluginVue()], }; 注册后,即可在代码中引入 `*.vue` 单文件组件。 [#](https://rsbuild.rs/zh/plugins/list/plugin-vue#%E9%80%89%E9%A1%B9) 选项 ------------------------------------------------------------------------ 如果你需要自定义 Vue 的编译行为,可以使用以下配置项。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-vue#vueloaderoptions) vueLoaderOptions 传递给 `rspack-vue-loader` 的选项,请查阅 [Vue Loader 文档](https://vue-loader.vuejs.org/) 来了解具体用法。 * **类型:** `VueLoaderOptions` * **默认值:** const emitCss = config.output.emitCss ?? config.output.target === 'web'; const defaultOptions = { compilerOptions: { preserveWhitespace: false, }, experimentalInlineMatchResource: emitCss, }; * **示例:** pluginVue({ vueLoaderOptions: { hotReload: false, }, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-vue#splitchunks) splitChunks 当使用 Rsbuild 的 [默认拆包 preset](https://rsbuild.rs/zh/config/split-chunks#default) 时,该插件会将与 `vue` 和 `vue-router` 相关的包拆分到独立的 chunk 中。 * `lib-vue.js`:包含 `vue`、`rspack-vue-loader`,以及它们的子依赖(`@vue/shared`,`@vue/reactivity`,`@vue/runtime-dom`,`@vue/runtime-core`)。 * `lib-router.js`:包含 `vue-router`。 该选项用于控制这一行为,决定是否需要将 `vue` 和 `router` 相关的包拆分为单独的 chunk。 * **类型:** type SplitVueChunkOptions = { vue?: boolean; router?: boolean; }; * **默认值:** const defaultOptions = { vue: true, router: true, }; * **示例:** pluginVue({ splitChunks: { vue: false, router: false, }, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-vue#test) test 用于自定义 Vue 单文件组件(SFC)的匹配规则。 * **类型:** [Rspack.RuleSetCondition](https://rspack.rs/zh/config/module-rules#condition) * **默认值:** `/\.vue$/` * **版本:** `>= 1.2.1` 通过该选项,你可以扩展 Vue 插件对其他文件类型的处理能力。例如,先使用某个插件或 loader 将 `.md` 文件转换为 Vue 组件,然后可以在 Vue 插件中通过 `test` 选项同时匹配 `.vue` 和 `.md` 文件: pluginVue({ test: /\.(vue|md)$/, }); [#](https://rsbuild.rs/zh/plugins/list/plugin-vue#%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98) 常见问题 -------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-vue#deep-%E9%80%89%E6%8B%A9%E5%99%A8%E5%AF%BC%E8%87%B4%E7%BC%96%E8%AF%91%E6%8A%A5%E9%94%99) /deep/ 选择器导致编译报错 `/deep/` 是从 Vue v2.7 开始废弃的用法,它不是一个合法的 CSS 语法,因此在编译时,Lightning CSS 等 CSS 编译工具会抛出错误。 你可以使用 `:deep()` 代替它,更多用法参考 [Vue - Deep Selectors](https://vuejs.org/api/sfc-css-features.html#deep-selectors) 。 > 你也可以参考 [Vue - RFC 0023](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0023-scoped-styles-changes.md) > 了解更多。 --- # Svelte 插件 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/plugin-svelte.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/plugin-svelte#svelte-%E6%8F%92%E4%BB%B6) Svelte 插件 ========================================================================================= 复制 Markdown [源码](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-svelte) Svelte 插件提供了对 Svelte 组件(`.svelte` 文件)的支持,插件内部集成了 [svelte-loader](https://github.com/sveltejs/svelte-loader) 。 [#](https://rsbuild.rs/zh/plugins/list/plugin-svelte#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) 快速开始 ----------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svelte#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 安装插件 执行以下命令安装插件: npm yarn pnpm bun deno npm add @rsbuild/plugin-svelte -D yarn add @rsbuild/plugin-svelte -D pnpm add @rsbuild/plugin-svelte -D bun add @rsbuild/plugin-svelte -D deno add npm:@rsbuild/plugin-svelte -D Tip `@rsbuild/plugin-svelte` v2 不再支持 Rsbuild 1.x 和 Svelte 4.x。如果你的项目仍在使用这些版本,请安装 `@rsbuild/plugin-svelte@1`。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svelte#%E6%B3%A8%E5%86%8C%E6%8F%92%E4%BB%B6) 注册插件 在 Rsbuild 配置中注册插件: rsbuild.config.ts import { pluginSvelte } from '@rsbuild/plugin-svelte'; export default { plugins: [pluginSvelte()], }; 注册后,即可在代码中引入 `*.svelte` 单文件组件。 [#](https://rsbuild.rs/zh/plugins/list/plugin-svelte#%E9%80%89%E9%A1%B9) 选项 --------------------------------------------------------------------------- 如果你需要自定义 Svelte 的编译行为,可以使用以下配置项。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svelte#svelteloaderoptions) svelteLoaderOptions 传递给 `svelte-loader` 的选项,请查阅 [svelte-loader 文档](https://github.com/sveltejs/svelte-loader) 来了解具体用法。 * **类型:** `SvelteLoaderOptions` * **默认值:** const defaultOptions = { compilerOptions: { dev: isDev, }, preprocess: require('svelte-preprocess')(), emitCss: isProd && !rsbuildConfig.output.injectStyles, hotReload: isDev && rsbuildConfig.dev.hmr, }; * **示例:** pluginSvelte({ svelteLoaderOptions: { preprocess: null, }, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svelte#preprocessoptions) preprocessOptions 传递给 `svelte-preprocess` 的选项,请查阅 [svelte-preprocess 文档](https://github.com/sveltejs/svelte-preprocess/blob/c2107e529da9438ea5b8060aa471119940896e40/docs/preprocessing.md) 来了解具体用法。 * **类型:** `AutoPreprocessOptions` * **默认值:** `undefined` interface AutoPreprocessOptions { globalStyle: { ... }, replace: { ... }, typescript: { ... }, scss: { ... }, sass: { ... }, less: { ... }, stylus: { ... }, babel: { ... }, postcss: { ... }, coffeescript: { ... }, pug: { ... }, } * **示例:** pluginSvelte({ preprocessOptions: { aliases: [\ ['potato', 'potatoLanguage'],\ ['pot', 'potatoLanguage'],\ ], /** Add a custom language preprocessor */ potatoLanguage({ content, filename, attributes }) { const { code, map } = require('potato-language').render(content); return { code, map }; }, }, }); [#](https://rsbuild.rs/zh/plugins/list/plugin-svelte#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9) 注意事项 ----------------------------------------------------------------------------------------------- 目前 `svelte-loader` 暂不支持 Svelte v5 热更新,详见 [svelte-loader - Hot Reload](https://github.com/sveltejs/svelte-loader#hot-reload) 。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svelte#lesssass-%E4%B8%AD%E7%9A%84%E5%88%AB%E5%90%8D%E5%A4%84%E7%90%86) Less/Sass 中的别名处理 在 Svelte 组件中使用别名来引入 Less 或 Sass 文件时,需要手动处理别名的路径解析,否则会出现 `"file not found"` 的错误。 * **示例:** rsbuild.config.ts import { pluginSvelte } from '@rsbuild/plugin-svelte'; export default { plugins: [\ pluginSvelte({\ preprocessOptions: {\ scss: {\ importer: [\ // 处理 SCSS 文件的别名导入\ (url, prev) => {\ if (url.startsWith('@/')) {\ return { file: url.replace('@/', 'src/') };\ }\ return null;\ },\ ],\ },\ less: {\ // 推荐使用 replace 来处理别名导入,更简单\ replace: [['@/style', 'style']],\ // 使用 less plugin 来处理别名导入\ plugins: [],\ },\ },\ }),\ ], }; 通过配置 `preprocessOptions`,可以保证在 Svelte 组件中引入的 `@import '@/styles/variables.scss` 或者 `@import '@/styles/variables.less'` 能够被正确解析。 --- # Less 插件 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/plugin-less.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/plugin-less#less-%E6%8F%92%E4%BB%B6) Less 插件 =================================================================================== 复制 Markdown [源码](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-less) 使用 [Less](https://lesscss.org/) 作为 CSS 预处理器,基于 [less-loader](https://github.com/webpack/less-loader) 实现。 [#](https://rsbuild.rs/zh/plugins/list/plugin-less#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) 快速开始 --------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-less#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 安装插件 执行以下命令安装插件: npm yarn pnpm bun deno npm add @rsbuild/plugin-less -D yarn add @rsbuild/plugin-less -D pnpm add @rsbuild/plugin-less -D bun add @rsbuild/plugin-less -D deno add npm:@rsbuild/plugin-less -D ### [#](https://rsbuild.rs/zh/plugins/list/plugin-less#%E6%B3%A8%E5%86%8C%E6%8F%92%E4%BB%B6) 注册插件 在 Rsbuild 配置中注册插件: rsbuild.config.ts import { pluginLess } from '@rsbuild/plugin-less'; export default { plugins: [pluginLess()], }; 注册后,即可在代码中引入 `*.less` 或 `*.module.less` 文件,无须添加其他配置。 [#](https://rsbuild.rs/zh/plugins/list/plugin-less#%E9%80%89%E9%A1%B9) 选项 ------------------------------------------------------------------------- 如果你需要自定义 Less 的编译行为,可以使用以下配置项。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-less#lessloaderoptions) lessLoaderOptions 修改 [less-loader](https://github.com/webpack/less-loader) 的配置。 * **类型:** `Object | Function` * **默认值:** const defaultOptions = { lessOptions: { javascriptEnabled: true, paths: [path.join(rootPath, 'node_modules')], }, sourceMap: false, // Controlled by output.sourceMap }; * **示例:** 当 `lessLoaderOptions` 的值是一个对象时,它会与默认配置通过 `Object.assign` 进行浅层合并,值得注意的是,`lessOptions` 会通过 deepMerge 进行深层合并。 pluginLess({ lessLoaderOptions: { lessOptions: { javascriptEnabled: false, }, }, }); 当 `lessLoaderOptions` 的值是一个函数时,默认配置作为第一个参数传入,你可以直接修改配置对象,也可以返回一个值作为最终结果: pluginLess({ lessLoaderOptions(config) { config.lessOptions = { javascriptEnabled: false, }; }, }); Tip `lessLoaderOptions.lessOptions` 是直接传递给 Less 的配置,请参阅 [Less 文档](https://lesscss.org/usage/#less-options) 以了解所有可用选项。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-less#include) include * **类型:** [Rspack.RuleSetCondition](https://rspack.rs/zh/config/module-rules#condition) * **默认值:** `/\.less$/` * **版本:** `>= 1.1.0` 用于指定一部分 `.less` 模块,这些模块会被 `less-loader` 编译。这个值与 Rspack 中的 [rules\[\].test](https://rspack.rs/zh/config/module-rules#rulestest) 选项相同。 比如: pluginLess({ include: /\.custom\.less$/, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-less#exclude) exclude * **类型:** [Rspack.RuleSetCondition](https://rspack.rs/zh/config/module-rules#condition) * **默认值:** `undefined` 用于排除一部分 `.less` 模块,这些模块不会被 `less-loader` 编译。 比如: pluginLess({ exclude: /some-folder[\\/]foo\.less/, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-less#parallel) parallel * **类型:** `boolean` * **默认值:** `false` * **版本:** 添加于 v1.4.0 是否使用 worker 线程并行编译 Less 模块。开启后,Less 模块会被分配到多个 worker 线程中处理,降低主线程压力,并在编译大量 Less 模块时提升整体构建性能。 pluginLess({ parallel: true, }); > 该功能基于 Rspack 的 parallel loader 实现。传递给 worker 线程的选项必须符合 [HTML 结构化克隆算法](https://nodejs.org/api/worker_threads.html#portpostmessagevalue-transferlist) > 的要求,否则会传输失败。例如,不能将函数作为选项传递。详见 [Rspack - Rule.use.parallel](https://rspack.rs/zh/config/module-rules#rulesuseparallel) > 。 [#](https://rsbuild.rs/zh/plugins/list/plugin-less#%E4%BF%AE%E6%94%B9-less-%E7%89%88%E6%9C%AC) 修改 Less 版本 --------------------------------------------------------------------------------------------------------- 在某些场景下,如果你需要使用特定的 Less 版本,而不是使用 Rsbuild 内置的 Less v4,可以在项目中安装需要使用的 Less 版本,并通过 `less-loader` 的 `implementation` 选项设置。 pluginLess({ lessLoaderOptions: { implementation: require('less'), }, }); [#](https://rsbuild.rs/zh/plugins/list/plugin-less#%E5%AE%9E%E8%B7%B5) 实践 ------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-less#%E9%85%8D%E7%BD%AE%E5%A4%9A%E4%B8%AA-less-%E6%8F%92%E4%BB%B6) 配置多个 Less 插件 通过使用 `include` 和 `exclude` 选项,你可以同时注册多个 Less 插件,并为每个插件指定不同的选项。 例如: export default { plugins: [\ pluginLess({\ exclude: /\.another\.less$/,\ }),\ pluginLess({\ include: /\.another\.less$/,\ lessLoaderOptions: {\ // some custom options\ },\ }),\ ], }; [#](https://rsbuild.rs/zh/plugins/list/plugin-less#%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98) 常见问题 --------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-less#less-%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E9%99%A4%E6%B3%95%E4%B8%8D%E7%94%9F%E6%95%88) Less 文件中的除法不生效? `@rsbuild/plugin-less` 内置的 Less 版本为 v4,与 v3 版本相比,除法的写法有一些区别: // Less v3 .math { width: 2px / 2; // 1px width: 2px ./ 2; // 1px width: (2px / 2); // 1px } // Less v4 .math { width: 2px / 2; // 2px / 2 width: 2px ./ 2; // 1px width: (2px / 2); // 1px } Less 中除法的写法可以通过配置项来修改,详见 [Less - Math](https://lesscss.org/usage/#less-options-math) 。 --- # Sass 插件 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/plugin-sass.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#sass-%E6%8F%92%E4%BB%B6) Sass 插件 =================================================================================== 复制 Markdown [源码](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-sass) 使用 [Sass](https://sass-lang.com/) 作为 CSS 预处理器,基于 [sass-loader](https://github.com/webpack/sass-loader) 实现。 [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) 快速开始 --------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 安装插件 执行以下命令安装插件: npm yarn pnpm bun deno npm add @rsbuild/plugin-sass -D yarn add @rsbuild/plugin-sass -D pnpm add @rsbuild/plugin-sass -D bun add @rsbuild/plugin-sass -D deno add npm:@rsbuild/plugin-sass -D Tip * Sass 插件仅支持 @rsbuild/core >= 0.7.0 版本。 * 当 @rsbuild/core 版本小于 0.7.0 时,内置支持 Sass 插件,你不需要安装该插件。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#%E6%B3%A8%E5%86%8C%E6%8F%92%E4%BB%B6) 注册插件 在 Rsbuild 配置中注册插件: rsbuild.config.ts import { pluginSass } from '@rsbuild/plugin-sass'; export default { plugins: [pluginSass()], }; 注册后,即可在代码中引入 `*.scss`,`*.sass`,`*.module.scss` 或 `*.module.sass` 文件,无须添加其他配置。 [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#%E9%80%89%E9%A1%B9) 选项 ------------------------------------------------------------------------- 如果你需要自定义 Sass 的编译行为,可以使用以下配置项。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#sassloaderoptions) sassLoaderOptions 修改 [sass-loader](https://github.com/webpack/sass-loader) 的配置。 * **类型:** `Object | Function` * **默认值:** 使用 `sass-embedded` 的 modern compiler API,并抑制依赖项警告和 import 弃用警告。 * **示例:** 当 `sassLoaderOptions` 的值是一个对象时,它会与默认配置通过 `Object.assign` 进行浅层合并,值得注意的是,`sassOptions` 会通过 deepMerge 进行深层合并。 pluginSass({ sassLoaderOptions: { sourceMap: true, }, }); 当 `sassLoaderOptions` 的值是一个函数时,默认配置作为第一个参数传入,你可以直接修改配置对象,也可以返回一个值作为最终结果: pluginSass({ sassLoaderOptions(config) { config.additionalData = async (content, loaderContext) => { // ... }; }, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#include) include * **类型:** [Rspack.RuleSetCondition](https://rspack.rs/zh/config/module-rules#condition) * **默认值:** `/\.s(?:a|c)ss$/` * **版本:** `>= 1.1.0` 用于指定一部分 `.scss` 或 `.sass` 模块,这些模块会被 `sass-loader` 编译。这个值与 Rspack 中的 [rules\[\].test](https://rspack.rs/zh/config/module-rules#rulestest) 选项相同。 比如: pluginSass({ include: /\.custom\.scss$/, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#exclude) exclude * **类型:** [Rspack.RuleSetCondition](https://rspack.rs/zh/config/module-rules#condition) * **默认值:** `undefined` 用于排除一部分 `.sass` 或 `.scss` 模块,这些模块不会被 `sass-loader` 编译。 比如: pluginSass({ exclude: /some-folder[\\/]foo\.scss/, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#rewriteurls) rewriteUrls * **类型:** `boolean` * **默认值:** `true` * **版本:** `>= 1.2.0` 是否使用 [resolve-url-loader](https://github.com/bholloway/resolve-url-loader/tree/v5/packages/resolve-url-loader) 来重写 URL。 当启用时,`resolve-url-loader` 允许你在 Sass 文件中写相对路径的 URL,这些 URL 会被正确地从当前 Sass 文件的位置解析,而不是相对于 Sass 入口文件(例如 `main.scss`)。 如果设置为 `false`,构建性能会得到提升,但 Rsbuild 会使用 Sass 的原生 URL 解析,这意味着所有 URL 必须相对于 Sass 入口文件。 pluginSass({ rewriteUrls: false, }); [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#%E5%AE%9E%E8%B7%B5) 实践 ------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#%E4%BF%AE%E6%94%B9-sass-implementation) 修改 Sass implementation Sass 提供了多种实现,包括 [sass](https://npmjs.com/package/sass) 、[sass-embedded](https://npmjs.com/package/sass-embedded) 和 [node-sass](https://npmjs.com/package/node-sass) 。 Rsbuild 默认使用最新的 `sass-embedded` 实现。`sass-embedded` 是一个围绕原生 Dart Sass 可执行文件的 JavaScript wrapper,具备一致的 API 和最佳的性能。 如果你需要使用其他 Sass 实现,而不是使用 Rsbuild 内置的 `sass-embedded`,可以在项目中安装需要使用的 Sass 实现,并通过 `sass-loader` 的 [implementation](https://github.com/webpack/sass-loader#implementation) 选项来设置。 pluginSass({ sassLoaderOptions: { implementation: require.resolve('sass'), }, }); Tip 从 `sass-embedded` 修改为其他 Sass 实现,可能会导致构建性能显著下降。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#%E9%80%89%E6%8B%A9-sass-api) 选择 Sass API Rsbuild 默认使用最新的 `modern-compiler` API,如果你依赖了 Sass 的 `legacy` API,可以将 sass-loader 的 [api](https://github.com/webpack/sass-loader#api) 选项设置为 `legacy`,以兼容一些废弃的 Sass 写法。 pluginSass({ sassLoaderOptions: { api: 'legacy', }, }); Tip Sass 的 `legacy` API 已经被废弃,并且将在 Sass 2.0 中被移除,建议迁移到 `modern-compiler` API,详见 [Sass - Legacy JS API](https://sass-lang.com/documentation/breaking-changes/legacy-js-api/) 。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#%E5%BF%BD%E7%95%A5-sass-%E5%BA%9F%E5%BC%83%E6%8F%90%E7%A4%BA) 忽略 Sass 废弃提示 Sass 会通过 warning 日志提示你一些废弃的写法,这些写法在 Sass 未来的大版本中将会被移除,建议根据日志进行修改。如果你不想看到这些日志,可以通过 Sass 的 [silenceDeprecations](https://sass-lang.com/documentation/js-api/interfaces/stringoptions/#silenceDeprecations) 选项来忽略这些警告。 例如,`@import` 已经被 Sass 废弃,当你使用该语法时,Sass 会输出如下日志: Sass @import rules are deprecated and will be removed in Dart Sass 3.0.0. More info and automated migrator: https://sass-lang.com/d/import 0 | @import './b.scss'; `@rsbuild/plugin-sass` 默认添加了如下配置来忽略 `@import` 的警告,如果你需要忽略其他废弃警告,可以使用同样的方式。 pluginSass({ sassLoaderOptions: { sassOptions: { silenceDeprecations: ['import'], }, }, }); > 请查看 [Sass Deprecations](https://sass-lang.com/documentation/js-api/interfaces/deprecations/) > 了解更多信息。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-sass#%E9%85%8D%E7%BD%AE%E5%A4%9A%E4%B8%AA-sass-%E6%8F%92%E4%BB%B6) 配置多个 Sass 插件 通过使用 `include` 和 `exclude` 选项,你可以同时注册多个 Sass 插件,并为每个插件指定不同的选项。 例如: export default { plugins: [\ pluginSass({\ exclude: /\.another\.scss$/,\ }),\ pluginSass({\ include: /\.another\.scss$/,\ sassLoaderOptions: {\ // some custom options\ },\ }),\ ], }; --- # Rsbuild instance - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/api/javascript-api/instance.md. 菜单目录 [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuild-instance) Rsbuild instance ======================================================================================== 复制 Markdown 本章节介绍了 Rsbuild 实例对象上所有的属性和方法。 [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildcontext) rsbuild.context ------------------------------------------------------------------------------------- `context` 是一个只读对象,提供一些上下文信息,能够通过两种方式访问: 1. 通过 Rsbuild 实例的 `context` 属性访问: import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild({ // ... }); console.log(rsbuild.context); 2. 通过 Rsbuild 插件的 [api.context](https://rsbuild.rs/zh/plugins/dev/core#apicontext) 访问: export const myPlugin = { name: 'my-plugin', setup(api) { console.log(api.context); }, }; ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#contextversion) context.version 当前使用的 `@rsbuild/core` 版本。 * **类型:** type Version = string; ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#contextrootpath) context.rootPath 当前执行构建的根路径,对应调用 [createRsbuild](https://rsbuild.rs/zh/api/javascript-api/core#creatersbuild) 时传入的 `cwd` 选项。 * **类型:** type RootPath = string; ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#contextconfigfile) context.configFile 通过 [loadConfig](https://rsbuild.rs/zh/api/javascript-api/core#loadconfig) 加载的配置文件绝对路径。未加载配置文件时为 `undefined`。 * **类型:** `string | undefined` ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#contextconfigfiledependencies) context.configFileDependencies 配置文件所导入文件的绝对路径,由 [loadConfig](https://rsbuild.rs/zh/api/javascript-api/core#loadconfig) 收集。 * **类型:** `readonly string[]` * **默认值:** `[]` ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#contextdistpath) context.distPath 构建产物输出目录的绝对路径,对应 `RsbuildConfig` 中的 [output.distPath.root](https://rsbuild.rs/zh/config/output/dist-path) 配置项。 当有多个环境时,Rsbuild 会尝试获取所有环境的父 distPath 作为 `context.distPath`。 如果要获取指定环境的输出目录的绝对路径,建议使用 [environment.distPath](https://rsbuild.rs/zh/api/javascript-api/environment-api#distpath) 。 * **类型:** type DistPath = string; ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#contextcachepath) context.cachePath 构建过程中生成的缓存文件所在的绝对路径。 * **类型:** type CachePath = string; ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#contextcallername) context.callerName 当前调用 Rsbuild 的框架或工具的名称,与 [createRsbuild](https://rsbuild.rs/zh/api/javascript-api/core#creatersbuild) 方法中的 [callerName](https://rsbuild.rs/zh/api/javascript-api/core#specify-caller-name) 选项相同。 * **类型:** `string` * **默认值:** `'rsbuild'` * **示例:** myPlugin.ts export const myPlugin = { name: 'my-plugin', setup(api) { const { callerName } = api.context; if (callerName === 'rslib') { // ... } else if (callerName === 'rsbuild') { // ... } }, }; 一些基于 Rsbuild 的工具已经设置了 `callerName` 的值: | 名称 | callerName | | --- | --- | | [Rslib](https://github.com/web-infra-dev/rslib) | `'rslib'` | | [Rstest](https://github.com/web-infra-dev/rstest) | `'rstest'` | | [Rspress](https://github.com/web-infra-dev/rspress) | `'rspress'` | | [Rspeedy](https://lynxjs.org/rspeedy) | `'rspeedy'` | ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#contextdevserver) context.devServer 在开发模式下运行时的 dev server 信息。仅在 dev server 创建后可访问。 * **类型:** type DevServer = { /** 服务器运行时使用的 hostname */ hostname: string; /** 服务器实际监听的端口号 */ port: number; /** 是否使用 HTTPS 协议 */ https: boolean; }; * **示例:** import { createRsbuild } from '@rsbuild/core'; async function main() { const rsbuild = await createRsbuild({ // ... }); await rsbuild.startDevServer(); // { hostname: 'localhost', port: 3000, https: false } console.log(rsbuild.context.devServer); } ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#contextaction) context.action 当前的动作类型。 * **类型:** type Action = 'dev' | 'build' | 'preview' | undefined; `context.action` 在运行 CLI 命令或调用 Rsbuild 实例方法时设置: * `dev`: 当运行 [rsbuild dev](https://rsbuild.rs/zh/guide/basic/cli#rsbuild) 或 [rsbuild.startDevServer()](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildstartdevserver) 时设置。 * `build`: 当运行 [rsbuild build](https://rsbuild.rs/zh/guide/basic/cli#rsbuild-build) 或 [rsbuild.build()](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildbuild) 时设置。 * `preview`: 当运行 [rsbuild preview](https://rsbuild.rs/zh/guide/basic/cli#rsbuild-preview) 或 [rsbuild.preview()](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildpreview) 时设置。 示例: if (rsbuild.context.action === 'dev') { // do something } [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildlogger) rsbuild.logger ----------------------------------------------------------------------------------- `rsbuild.logger` 表示当前 Rsbuild 实例所关联的 logger,详见 [日志](https://rsbuild.rs/zh/guide/advanced/logging) 。 * **类型:** [Logger](https://rsbuild.rs/zh/api/javascript-api/core#logger) * **示例:** const rsbuild = await createRsbuild(); rsbuild.logger.info('build started'); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildbuild) rsbuild.build --------------------------------------------------------------------------------- 执行生产模式构建。该方法会生成优化后的生产构建产物,并输出到输出目录。 * **类型:** type BuildOptions = { /** * 是否监听文件变化并重新构建 * * @default false */ watch?: boolean; }; function Build(options?: BuildOptions): Promise<{ /** * Rspack 的 [stats](https://rspack.rs/zh/api/javascript-api/stats) 对象。 */ stats?: Rspack.Stats | Rspack.MultiStats; /** * 关闭构建并调用 `onCloseBuild` 钩子。 * 在监听模式下,此方法将停止监听。 */ close: () => Promise; }>; * **示例:** import { logger } from '@rsbuild/core'; // Example 1: run build await rsbuild.build(); // Example 2: build and handle the error try { await rsbuild.build(); } catch (err) { logger.error('Failed to build.'); logger.error(err); process.exit(1); } // Example 3: build and get all assets const { stats } = await rsbuild.build(); if (stats) { const { assets } = stats.toJson({ // 排除不需要的字段以提高性能 all: false, assets: true, }); console.log(assets); } ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#%E7%9B%91%E5%90%AC%E6%96%87%E4%BB%B6%E5%8F%98%E5%8C%96) 监听文件变化 如果需要自动监听文件变化并重新执行构建,可以将 `watch` 参数设置为 `true`。 await rsbuild.build({ watch: true, }); ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#close-build) 结束构建 `rsbuild.build()` 返回一个 `close()` 方法,用于结束本次构建。 在 watch 模式下,调用 `close()` 方法将会结束监听: const buildResult = await rsbuild.build({ watch: true, }); await buildResult.close(); 在非 watch 模式下,你也应该调用 `close()` 方法来结束构建,这会触发 [onCloseBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onclosebuild) 钩子,执行清理操作。 const buildResult = await rsbuild.build(); await buildResult.close(); ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#stats-object) Stats 对象 在非 watch 模式下,`rsbuild.build()` 会返回一个 Rspack 的 [stats](https://rspack.rs/zh/api/javascript-api/stats) 对象。 例如,使用 `stats.toJson()` 方法获取所有 assets 信息: const result = await rsbuild.build(); const { stats } = result; if (stats) { const { assets } = stats.toJson({ // 排除不需要的字段以提高性能 all: false, assets: true, }); console.log(assets); } [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildstartdevserver) rsbuild.startDevServer --------------------------------------------------------------------------------------------------- 启动本地 dev server。该方法会: 1. 启动一个开发服务器,用于运行你的应用 2. 自动监听文件变化并触发重新编译 * **类型:** type StartDevServerOptions = { /** * 是否在启动时静默获取端口号,不输出任何日志 * @default false */ getPortSilently?: boolean; }; type StartDevServerResult = { /** * 服务器监听的 URLs */ urls: string[]; /** * 服务器实际使用的端口号 */ port: number; server: RsbuildDevServer; }; function StartDevServer( options?: StartDevServerOptions, ): Promise; * **示例:** 启动 dev server: import { logger } from '@rsbuild/core'; // Start dev server await rsbuild.startDevServer(); // Start dev server and handle the error try { await rsbuild.startDevServer(); } catch (err) { logger.error('Failed to start dev server.'); logger.error(err); process.exit(1); } 成功启动 dev server 后,可以看到以下日志信息: ➜ Local: http://localhost:3000 ➜ Network: use --host to expose `startDevServer` 会返回以下参数: * `urls`:访问 dev server 的 URLs * `port` 实际监听的端口号 * `server`:Server 实例对象,详见 [Server API](https://rsbuild.rs/zh/api/javascript-api/server-api) const { urls, port } = await rsbuild.startDevServer(); console.log(urls); // ['http://localhost:3000', 'http://192.168.0.1:3000'] console.log(port); // 3000 ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#close-server) 关闭 server 调用 `server.close()` 方法会关闭开发服务器,触发 [onCloseDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onclosedevserver) 钩子,并执行必要的清理操作。 const { server } = await rsbuild.startDevServer(); await server.close(); ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#%E9%9D%99%E9%BB%98%E8%8E%B7%E5%8F%96%E7%AB%AF%E5%8F%A3%E5%8F%B7) 静默获取端口号 某些情况下,默认启动的端口号已经被占用,此时 Rsbuild 会自动递增端口号,直至找到一个可用端口。这个过程会输出提示日志,如果你不希望这段日志,可以将 `getPortSilently` 设置为 `true`。 await rsbuild.startDevServer({ getPortSilently: true, }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildcreatedevserver) rsbuild.createDevServer ----------------------------------------------------------------------------------------------------- * **类型:** type CreateDevServerOptions = { /** * 是否在启动时静默获取端口号,不输出任何日志 * @default false */ getPortSilently?: boolean; /** * 是否触发 Rsbuild 编译 * @default true */ runCompile?: boolean; }; function createDevServer( options?: CreateDevServerOptions, ): Promise; Rsbuild 配备了一个内置的开发服务器,当你执行 `rsbuild dev` 时,将启动 Rsbuild dev server,并提供页面预览、路由、模块热更新等功能。 * 如果你需要将 Rsbuild dev server 集成到自定义的 server 中,可以通过 `createDevServer` 方法创建一个 dev server 实例,请参考 [Server API](https://rsbuild.rs/zh/api/javascript-api/server-api) 了解所有可用的 API。 * 如果你需要直接使用 Rsbuild dev server 启动项目,可以直接使用 [rsbuild.startDevServer](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildstartdevserver) 方法。 `rsbuild.startDevServer` 实际上是以下代码的语法糖: const server = await rsbuild.createDevServer(); await server.listen(); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildpreview) rsbuild.preview ------------------------------------------------------------------------------------- 在本地启动 server 来预览生产模式构建的产物,需要在 [rsbuild.build](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildbuild) 方法之后执行。 * **类型:** type PreviewOptions = { /** * 是否在启动时静默获取端口号,不输出任何日志 * @default false */ getPortSilently?: boolean; /** * 是否检查 dist 目录存在且不为空 * @default true */ checkDistDir?: boolean; }; type StartPreviewServerResult = { /** * 服务器监听的 URLs */ urls: string[]; /** * 服务器实际使用的端口号 */ port: number; server: RsbuildPreviewServer; }; function preview(options?: PreviewOptions): Promise; * **示例:** 启动 Server: import { logger } from '@rsbuild/core'; // Start preview server await rsbuild.preview(); // Start preview server and handle the error try { await rsbuild.preview(); } catch (err) { logger.error('Failed to start preview server.'); logger.error(err); process.exit(1); } `preview` 会返回以下参数: * `urls`:访问 Server 的 URLs * `port` 实际监听的端口号 * `server`:Server 实例对象,详见 [Server API](https://rsbuild.rs/zh/api/javascript-api/server-api) const { urls, port } = await rsbuild.preview(); console.log(urls); // ['http://localhost:3000', 'http://192.168.0.1:3000'] console.log(port); // 3000 ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#%E5%85%B3%E9%97%AD-server) 关闭 server 调用 `close()` 方法会关闭预览服务器。 const { server } = await rsbuild.preview(); await server.close(); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildcreatecompiler) rsbuild.createCompiler --------------------------------------------------------------------------------------------------- 创建一个 Rspack [Compiler](https://rspack.rs/zh/api/javascript-api/compiler) 实例;如果本次构建存在多个 [environments](https://rsbuild.rs/zh/config/environments) ,则返回值为 [MultiCompiler](https://rspack.rs/zh/api/javascript-api/compiler#multicompiler) 。 * **类型:** function CreateCompiler(): Promise; * **示例:** const compiler = await rsbuild.createCompiler(); > 大部分场景下,你不需要使用该 API,除非需要进行自定义 dev server 等高级操作。 [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildaddplugins) rsbuild.addPlugins ------------------------------------------------------------------------------------------- 注册一个或多个 Rsbuild 插件,可以被多次调用。 该方法需要在开始编译前调用,如果在开始编译之后调用,则不会影响编译结果。 * **类型:** type AddPluginsOptions = { before?: string; environment?: string }; function AddPlugins( plugins: Array, options?: AddPluginsOptions, ): void; * **示例:** rsbuild.addPlugins([pluginFoo(), pluginBar()]); // 在 bar 插件之前插入 rsbuild.addPlugins([pluginFoo()], { before: 'bar' }); // 为 node 环境添加插件 rsbuild.addPlugins([pluginFoo()], { environment: 'node' }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildgetplugins) rsbuild.getPlugins ------------------------------------------------------------------------------------------- 获取当前 Rsbuild 实例中注册的所有 Rsbuild 插件。 * **类型:** function GetPlugins(options?: { /** * Get the plugins in the specified environment. * If environment is not specified, get the global plugins. */ environment: string; }): RsbuildPlugin[]; * **示例:** // get all plugins console.log(rsbuild.getPlugins()); // get plugins in `web` environment console.log(rsbuild.getPlugins({ environment: 'web' })); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildremoveplugins) rsbuild.removePlugins ------------------------------------------------------------------------------------------------- 移除一个或多个 Rsbuild 插件,可以被多次调用。 该方法需要在开始编译前调用,如果在开始编译之后调用,则不会影响编译结果。 * **类型:** function RemovePlugins( pluginNames: string[], options?: { /** * 移除指定 environment 中的插件。 * 如果未指定 environment,则会从所有 environment 中移除。 */ environment?: string; }, ): void; * **示例:** // 添加插件 const foo = pluginFoo(); rsbuild.addPlugins([foo]); // 移除插件 rsbuild.removePlugins([foo.name]); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildispluginexists) rsbuild.isPluginExists --------------------------------------------------------------------------------------------------- 判断某个插件是否已经在当前 Rsbuild 实例中注册。 * 如果未指定 `environment` 参数,则判断全局注册的插件中是否存在该插件。 * 如果指定了 `environment` 参数,则判断在指定环境中是否存在该插件。 * **类型:** function IsPluginExists( pluginName: string, options?: { /** * Whether it exists in the specified environment. * If environment is not specified, determine whether the plugin is a global plugin. */ environment: string; }, ): boolean; * **示例:** const pluginFoo = { name: 'plugin-foo', setup(api) { // ... }, }; const rsbuild = await createRsbuild({ config: { plugins: [pluginFoo], }, }); rsbuild.isPluginExists(pluginFoo.name); // true 或者检查指定环境中是否存在插件: const rsbuild = await createRsbuild({ config: { environments: { web: { plugins: [pluginFoo], }, }, }, }); rsbuild.isPluginExists(pluginFoo.name, { environment: 'web', }); // true [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildinitconfigs) rsbuild.initConfigs --------------------------------------------------------------------------------------------- 初始化并返回 Rsbuild 内部使用的 Rspack 配置。该方法会处理所有插件和配置,生成最终的 Rspack 配置。 > 通常你不需要直接调用该方法,因为调用 [rsbuild.build](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildbuild) > 和 [rsbuild.startDevServer](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildstartdevserver) > 等方法时会自动调用 `initConfigs`。 * **类型:** type InitConfigsOptions = { /** * 当前的动作类型。 * - dev: 当运行 `rsbuild dev` 或 `rsbuild.startDevServer()` 时设置。 * - build: 当运行 `rsbuild build` 或 `rsbuild.build()` 时设置。 * - preview: 当运行 `rsbuild preview` 或 `rsbuild.preview()` 时设置。 */ action?: 'dev' | 'build' | 'preview'; }; function InitConfigs( options?: InitConfigsOptions, ): Promise; * **示例:** const rspackConfigs = await rsbuild.initConfigs(); console.log(rspackConfigs); const buildConfigs = await rsbuild.initConfigs({ action: 'build', }); console.log(buildConfigs); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildinspectconfig) rsbuild.inspectConfig ------------------------------------------------------------------------------------------------- 检查和调试 Rsbuild 的内部配置。它允许你访问: * 解析后的 Rsbuild 配置 * 特定 environment 的 Rsbuild 配置 * 生成的 Rspack 配置 该方法将这些配置序列化为字符串,并支持写入磁盘以进行检查。 * **类型:** type InspectConfigOptions = { /** * 检查指定 mode 下的配置 * 可选值:'development'、'production' 或 'none' * @default 根据 `process.env.NODE_ENV` 推断:未设置时为 'development', * 匹配 'development' 或 'production' 时使用对应值,否则为 'none' */ mode?: RsbuildMode; /** * 启用详细模式,显示配置中函数的完整内容 * @default false */ verbose?: boolean; /** * 指定检查结果的输出路径 * @default '/.rsbuild' */ outputPath?: string; /** * 是否将检查结果写入磁盘 * @default false */ writeToDisk?: boolean; /** * 需要额外输出的配置 * - key: 配置的名称 * - value: 配置对象 */ extraConfigs?: Record; }; async function InspectConfig(options?: InspectConfigOptions): Promise<{ rsbuildConfig: string; bundlerConfigs: string[]; environmentConfigs: string[]; origin: { rsbuildConfig: Omit; environmentConfigs: Record; bundlerConfigs: Rspack.Configuration[]; }; }>; Tip 如果你需要在构建过程中查看 Rsbuild 和 Rspack 配置,可以使用 [调试模式](https://rsbuild.rs/zh/guide/debug/debug-mode) ,也可以通过 [onBeforeBuild](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonbeforebuild) 、[onBeforeCreateCompiler](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonbeforecreatecompiler) 等 hooks 来获取。 ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#%E7%A4%BA%E4%BE%8B) 示例 拿到字符串格式的 configs 内容: const { rsbuildConfig, bundlerConfigs } = await rsbuild.inspectConfig(); console.log(rsbuildConfig, bundlerConfigs); 直接将配置内容写入到磁盘上: await rsbuild.inspectConfig({ writeToDisk: true, }); ### [#](https://rsbuild.rs/zh/api/javascript-api/instance#%E8%BE%93%E5%87%BA%E8%B7%AF%E5%BE%84) 输出路径 你可以通过 `outputPath` 来设置输出目录。默认情况下,文件会写入 [context.distPath](https://rsbuild.rs/zh/api/javascript-api/instance#contextdistpath) 下的 `.rsbuild` 目录。 当 `outputPath` 是一个相对路径时,会相对于 `context.distPath` 进行解析。你也可以将 `outputPath` 设置为一个绝对路径,此时会直接将文件写入到该路径下。比如: import path from 'node:path'; await rsbuild.inspectConfig({ writeToDisk: true, outputPath: path.join(__dirname, 'custom-dir'), }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonbeforecreatecompiler) rsbuild.onBeforeCreateCompiler ------------------------------------------------------------------------------------------------------------------- > 功能与 [onBeforeCreateCompiler](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforecreatecompiler) > 插件 hook 一致。 `onBeforeCreateCompiler` 是在创建 Rspack Compiler 实例前触发的回调函数,当你执行 `rsbuild.startDevServer`、`rsbuild.build` 或 `rsbuild.createCompiler` 时,都会调用此钩子。 你可以通过 `bundlerConfigs` 参数获取到 Rspack 配置数组,数组中可能包含一份或多份 [Rspack 配置](https://rspack.rs/zh/config/) ,这取决于是否配置了多个 [environments](https://rsbuild.rs/zh/config/environments) 。 * **类型:** function OnBeforeCreateCompiler( callback: (params: { bundlerConfigs: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **示例:** rsbuild.onBeforeCreateCompiler(({ bundlerConfigs }) => { console.log('the Rspack config is ', bundlerConfigs); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonaftercreatecompiler) rsbuild.onAfterCreateCompiler ----------------------------------------------------------------------------------------------------------------- > 功能与 [onAfterCreateCompiler](https://rsbuild.rs/zh/plugins/dev/hooks#onaftercreatecompiler) > 插件 hook 一致。 `onAfterCreateCompiler` 是在创建 Rspack Compiler 实例后、执行构建前触发的回调函数,当你执行 `rsbuild.startDevServer`、`rsbuild.build` 或 `rsbuild.createCompiler` 时,都会调用此钩子。 你可以通过 `compiler` 参数获取到 [Compiler 实例对象](https://rspack.rs/zh/api/javascript-api/compiler) : * **类型:** function OnAfterCreateCompiler( callback: (params: { compiler: Compiler | MultiCompiler; environments: Record; }) => Promise | void, ): void; * **示例:** rsbuild.onAfterCreateCompiler(({ compiler }) => { console.log('the compiler is ', compiler); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonbeforebuild) rsbuild.onBeforeBuild ------------------------------------------------------------------------------------------------- > 功能与 [onBeforeBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforebuild) > 插件 hook 一致。 `onBeforeBuild` 是在执行生产模式构建前触发的回调函数。 你可以通过 `bundlerConfigs` 参数获取到 Rspack 配置数组,数组中可能包含一份或多份 [Rspack 配置](https://rspack.rs/zh/config/) ,这取决于是否配置了多个 [environments](https://rsbuild.rs/zh/config/environments) 。 另外,你可以通过 `isWatch` 判断是否是 watch 模式,并在 watch 模式下通过 `isFirstCompile` 来判断是否为首次构建。 * **类型:** function OnBeforeBuild( callback: (params: { isWatch: boolean; isFirstCompile: boolean; bundlerConfigs?: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **示例:** rsbuild.onBeforeBuild(({ bundlerConfigs }) => { console.log('the Rspack config is ', bundlerConfigs); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonafterbuild) rsbuild.onAfterBuild ----------------------------------------------------------------------------------------------- > 功能与 [onAfterBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onafterbuild) > 插件 hook 一致。 `onAfterBuild` 是在执行生产模式构建后触发的回调函数,你可以通过 [stats](https://rspack.rs/zh/api/javascript-api/stats) 参数获取到构建结果信息。 另外,你可以通过 `isWatch` 判断是否是 watch 模式,并在 watch 模式下通过 `isFirstCompile` 来判断是否为首次构建。 * **类型:** function OnAfterBuild( callback: (params: { isFirstCompile: boolean; isWatch: boolean; stats?: Stats | MultiStats; environments: Record; }) => Promise | void, ): void; * **示例:** rsbuild.onAfterBuild(({ stats }) => { console.log(stats?.toJson()); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonclosebuild) rsbuild.onCloseBuild ----------------------------------------------------------------------------------------------- > 功能与 [onCloseBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onclosebuild) > 插件 hook 一致。 在关闭构建时调用,可用于在构建关闭时执行清理操作。 Rsbuild CLI 会在执行 [rsbuild build](https://rsbuild.rs/zh/guide/basic/cli#rsbuild-build) 完成后自动调用此钩子,使用 JavaScript API 的用户需要手动调用 [build.close()](https://rsbuild.rs/zh/api/javascript-api/instance#close-build) 方法来触发此钩子。 * **类型:** function onCloseBuild(callback: () => Promise | void): void; * **示例:** rsbuild.onCloseBuild(async () => { console.log('close build!'); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonbeforestartdevserver) rsbuild.onBeforeStartDevServer ------------------------------------------------------------------------------------------------------------------- > 功能与 [onBeforeStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartdevserver) > 插件 hook 一致。 在启动开发服务器前调用。 通过 `server` 参数可以获取到开发服务器实例,参考 [Server API](https://rsbuild.rs/zh/api/javascript-api/server-api) 了解更多。 * **类型:** type MaybePromise = T | Promise; type OnBeforeStartDevServerFn = (params: { /** * The dev server instance, the same as the return value of `createDevServer`. */ server: RsbuildDevServer; /** * Context information for all environments. */ environments: Record; }) => MaybePromise<(() => MaybePromise) | void>; function OnBeforeStartDevServer(callback: OnBeforeStartDevServerFn): void; * **示例:** rsbuild.onBeforeStartDevServer(({ server, environments }) => { console.log('before starting dev server.'); console.log('the server is ', server); console.log('the environments contexts are: ', environments); }); > 查看 [Plugin hooks - onBeforeStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartdevserver) > 了解更多用法。 [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonafterstartdevserver) rsbuild.onAfterStartDevServer ----------------------------------------------------------------------------------------------------------------- > 功能与 [onAfterStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartdevserver) > 插件 hook 一致。 在启动开发服务器后调用。你可以通过 `port` 参数获得开发服务器监听的端口号,通过 `routes` 获得页面路由信息。 * **类型:** type Routes = Array<{ entryName: string; pathname: string; }>; function OnAfterStartDevServer( callback: (params: { port: number; routes: Routes; environments: Record; }) => Promise | void, ): void; * **示例:** rsbuild.onAfterStartDevServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonclosedevserver) rsbuild.onCloseDevServer ------------------------------------------------------------------------------------------------------- > 功能与 [onCloseDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onclosedevserver) > 插件 hook 一致。 关闭开发服务器时调用,可用于在开发服务器关闭时执行清理操作。 Rsbuild CLI 会自动在合适的时机调用此钩子,使用 JavaScript API 的用户需要手动调用 [server.close()](https://rsbuild.rs/zh/api/javascript-api/instance#close-server) 方法来触发此钩子。 * **类型:** function onCloseDevServer(callback: () => Promise | void): void; * **示例:** rsbuild.onCloseDevServer(async () => { console.log('close dev server!'); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonbeforestartpreviewserver) rsbuild.onBeforeStartPreviewServer --------------------------------------------------------------------------------------------------------------------------- > 功能与 [onBeforeStartPreviewServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartpreviewserver) > 插件 hook 一致。 在启动预览服务器前调用。 可以通过 `server` 参数访问预览服务器并注册自定义的中间件。 * **类型:** type MaybePromise = T | Promise; type OnBeforeStartPreviewServerFn = (params: { /** * 预览服务器实例 */ server: RsbuildPreviewServer; /** * 所有 environments 的上下文信息 */ environments: Record; }) => MaybePromise; function OnBeforeStartPreviewServer( callback: OnBeforeStartPreviewServerFn, ): void; * **示例:** rsbuild.onBeforeStartPreviewServer(({ server, environments }) => { console.log('before start!'); console.log('the server is ', server); console.log('the environments contexts are: ', environments); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonafterstartpreviewserver) rsbuild.onAfterStartPreviewServer ------------------------------------------------------------------------------------------------------------------------- > 功能与 [onAfterStartPreviewServer](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartpreviewserver) > 插件 hook 一致。 在启动预览服务器后调用,你可以通过 `port` 参数获得预览服务器监听的端口号,通过 `routes` 获得页面路由信息。 * **类型:** type Routes = Array<{ entryName: string; pathname: string; }>; function OnAfterStartPreviewServer( callback: (params: { port: number; routes: Routes; environments: Record; }) => Promise | void, ): void; * **示例:** rsbuild.onAfterStartPreviewServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonbeforedevcompile) rsbuild.onBeforeDevCompile ----------------------------------------------------------------------------------------------------------- > 功能与 [onBeforeDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforedevcompile) > 插件 hook 一致。 `onBeforeDevCompile` 是在执行开发环境构建前触发的回调函数。 你可以通过 `bundlerConfigs` 参数获取到 Rspack 配置数组,数组中可能包含一份或多份 [Rspack 配置](https://rspack.rs/zh/config/) ,这取决于是否配置了多个 [environments](https://rsbuild.rs/zh/config/environments) 。 另外,你可以通过 `isFirstCompile` 来判断是否为首次构建。 * **类型:** function OnBeforeDevCompile( callback: (params: { isWatch: boolean; isFirstCompile: boolean; bundlerConfigs?: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **版本:** 新增于 v1.5.0 * **示例:** rsbuild.onBeforeDevCompile(({ bundlerConfigs }) => { console.log('the Rspack configs are ', bundlerConfigs); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonafterdevcompile) rsbuild.onAfterDevCompile --------------------------------------------------------------------------------------------------------- > 功能与 [onAfterDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterdevcompile) > 插件 hook 一致。 在每次开发模式构建结束后调用,你可以通过 `isFirstCompile` 来判断是否为首次构建。 * **类型:** function OnAfterDevCompile( callback: (params: { isFirstCompile: boolean; stats: Stats | MultiStats; environments: Record; }) => Promise | void, ): void; Tip `onAfterDevCompile` 钩子在 Rsbuild v1.5.0 中新增。对于之前的版本,你可以使用功能完全相同的 `onDevCompileDone` 钩子。 * **示例:** rsbuild.onAfterDevCompile(({ isFirstCompile }) => { if (isFirstCompile) { console.log('first compile!'); } else { console.log('re-compile!'); } }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonbeforeenvironmentcompile) rsbuild.onBeforeEnvironmentCompile --------------------------------------------------------------------------------------------------------------------------- > 功能与 [onBeforeEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforeenvironmentcompile) > 插件 hook 一致。 * **版本:** 添加于 v1.5.7 * **示例:** rsbuild.onBeforeEnvironmentCompile(({ bundlerConfig, environment }) => { console.log( `the bundler config for the ${environment.name} is `, bundlerConfig, ); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonafterenvironmentcompile) rsbuild.onAfterEnvironmentCompile ------------------------------------------------------------------------------------------------------------------------- > 功能与 [onAfterEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterenvironmentcompile) > 插件 hook 一致。 * **版本:** 添加于 v1.5.7 * **示例:** rsbuild.onAfterEnvironmentCompile(({ isFirstCompile, stats }) => { console.log(stats?.toJson(), isFirstCompile); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonrestart) rsbuild.onRestart ----------------------------------------------------------------------------------------- > 功能与 [onRestart](https://rsbuild.rs/zh/plugins/dev/hooks#onrestart) > 插件 hook 一致。 当 dev server 或监听构建被请求重启时调用。 该 hook 会在以下情况中触发: * Rsbuild CLI 检测到配置文件或其依赖发生变化。 * [`dev.watchFiles`](https://rsbuild.rs/zh/config/dev/watch-files) 中 `type` 为 `'restart'` 的监听项检测到 `events` 中指定的文件事件。 * 通过 [CLI 快捷键](https://rsbuild.rs/zh/config/dev/cli-shortcuts) 手动重启 dev server。 > 普通的重新构建不会触发该 hook。 使用 JavaScript API 时,`rsbuild.startDevServer()`、`rsbuild.createDevServer()` 和 `rsbuild.build({ watch: true })` 会安装 restart watcher。只有检测到 `events` 中指定的文件事件时才会调用该 hook。默认情况下,Rsbuild 不会关闭或重启当前任务;你可以传入 [`restart` 选项](https://rsbuild.rs/zh/api/javascript-api/core#restart-handling) 来处理重启请求。 * **类型:** type WatchFileEvent = 'add' | 'change' | 'unlink'; type RestartContext = { filePath?: string; event?: WatchFileEvent; } & ( | { action: 'build'; options: BuildOptions; } | { action: 'dev'; options: StartDevServerOptions; } ); function OnRestart( callback: (context: RestartContext) => Promise | void, ): void; * `action`:当前正在重启的 Rsbuild 操作类型。 * `filePath`:触发重启的文件绝对路径,手动触发重启时为 `undefined`。 * `event`:触发重启的文件事件,手动触发重启时为 `undefined`。该属性自 v2.1.8 起可用。 * `options`:当前调用 `rsbuild.build()` 或 `rsbuild.startDevServer()` 时传入的选项。 * **版本:** 新增于 v2.1.7 * **示例:** rsbuild.onRestart(async ({ action, filePath }) => { console.log('restart!', action, filePath); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildonexit) rsbuild.onExit ----------------------------------------------------------------------------------- > 功能与 [onExit](https://rsbuild.rs/zh/plugins/dev/hooks#onexit) > 插件 hook 一致。 在进程即将退出时调用,这个钩子只能执行同步代码。 * **类型:** function OnExit(callback: (context: { exitCode: number }) => void): void; * **示例:** rsbuild.onExit(({ exitCode }) => { console.log('exit: ', exitCode); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildgetrsbuildconfig) rsbuild.getRsbuildConfig ------------------------------------------------------------------------------------------------------- > 功能与 [getRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/core#apigetrsbuildconfig) > 插件 API 一致。 获取 Rsbuild 配置。 * **类型:** type GetRsbuildConfig = { (): Readonly; (type: 'original' | 'current'): Readonly; (type: 'normalized'): NormalizedConfig; }; * **参数:** 你可以通过 `type` 参数来指定读取的 Rsbuild 配置类型: // 获取用户定义的原始 Rsbuild 配置。 getRsbuildConfig('original'); // 获取当前的 Rsbuild 配置。 // 在 Rsbuild 的不同执行阶段,该配置的内容会发生变化。 // 比如 `modifyRsbuildConfig` 钩子执行后会修改当前 Rsbuild 配置的内容。 getRsbuildConfig('current'); // 获取规范化后的 Rsbuild 配置。 // 该方法必须在 `modifyRsbuildConfig` 钩子执行完成后才能被调用。 // 等价于 `getNormalizedConfig` 方法。 getRsbuildConfig('normalized'); * **示例:** rsbuild.onBeforeBuild(() => { const config = rsbuild.getRsbuildConfig(); console.log(config.html?.title); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildgetnormalizedconfig) rsbuild.getNormalizedConfig ------------------------------------------------------------------------------------------------------------- > 功能与 [getNormalizedConfig](https://rsbuild.rs/zh/plugins/dev/core#apigetnormalizedconfig) > 插件 API 一致。 获取规范化后的完整 Rsbuild 配置(包含所有环境),或指定环境的规范化配置。该方法只能在 [modifyRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) 钩子执行完毕后调用。 与 [`getRsbuildConfig`](https://rsbuild.rs/zh/plugins/dev/core#apigetrsbuildconfig) 相比,该方法返回经过规范化处理、类型更明确的配置。例如,`config.html` 的类型不再包含 `undefined`。 使用 `getNormalizedConfig()` 获取包含所有环境的完整配置。如需获取指定环境的配置,则使用 `getNormalizedConfig({ environment: name })`。 * **类型:** type GetNormalizedConfig = { /** 获取包含所有环境的完整规范化配置 */ (): NormalizedConfig; /** 获取指定环境的规范化 Rsbuild 配置 */ (options: { environment: string }): NormalizedEnvironmentConfig; }; * **示例:** rsbuild.onBeforeBuild(() => { const config = rsbuild.getNormalizedConfig(); console.log(config.html.title); }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildexpose) rsbuild.expose ----------------------------------------------------------------------------------- > 功能与 [expose](https://rsbuild.rs/zh/plugins/dev/core#apiexpose) > 插件 API 一致。 * **版本:** 添加于 v1.5.0 * **示例:** rsbuild.expose('my-id', { value: 1, double: (val: number) => val * 2, }); 你也可以为指定 environment(对应 `config.environments` 的 key)暴露 API: rsbuild.expose( 'my-id', { value: 1, double: (val: number) => val * 2, }, { environment: 'web', }, ); 当注册在同一 environment 中的插件调用 `api.useExposed` 时,Rsbuild 会优先解析 environment 级别的 API,如果不存在,则回退到全局 API。 [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildmodifyrsbuildconfig) rsbuild.modifyRsbuildConfig ------------------------------------------------------------------------------------------------------------- > 功能与 [modifyRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) > 插件 API 一致。 * **版本:** 添加于 v1.5.0 * **示例:** rsbuild.modifyRsbuildConfig((config) => { config.html ||= {}; config.html.title = 'My Default Title'; }); [#](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildmodifyenvironmentconfig) rsbuild.modifyEnvironmentConfig --------------------------------------------------------------------------------------------------------------------- > 功能与 [modifyEnvironmentConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyenvironmentconfig) > 插件 API 一致。 * **版本:** 添加于 v1.5.0 * **示例:** rsbuild.modifyEnvironmentConfig((config, { name }) => { if (name !== 'web') { return config; } config.html.title = 'My Default Title'; }); --- # Babel plugin - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/list/plugin-babel.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/list/plugin-babel#babel-plugin) Babel plugin =========================================================================== Copy Markdown [Source Code](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-babel) Rsbuild uses SWC transpilation by default. When existing functions cannot meet the requirements, and some Babel presets or plugins need to be added for additional processing, you can use Rsbuild's Babel Plugin. [#](https://rsbuild.rs/plugins/list/plugin-babel#quick-start) Quick start ------------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-babel#install-plugin) Install plugin Run the following command: npm yarn pnpm bun deno npm add @rsbuild/plugin-babel -D yarn add @rsbuild/plugin-babel -D pnpm add @rsbuild/plugin-babel -D bun add @rsbuild/plugin-babel -D deno add npm:@rsbuild/plugin-babel -D ### [#](https://rsbuild.rs/plugins/list/plugin-babel#register-plugin) Register plugin Register the plugin in Rsbuild config: rsbuild.config.ts import { pluginBabel } from '@rsbuild/plugin-babel'; export default { plugins: [pluginBabel()], }; [#](https://rsbuild.rs/plugins/list/plugin-babel#compilation-cache) Compilation cache ------------------------------------------------------------------------------------- After using the Babel plugin, Rsbuild will perform the Babel transpilation in addition to the standard SWC transpilation, which adds additional compilation overhead. This can cause a noticeable decrease in build speed. To reduce the overhead of Babel transpilation, the `@rsbuild/plugin-babel` enables Babel compilation cache by default. If you want to disable the cache, you can set [performance.buildCache](https://rsbuild.rs/config/performance/build-cache) to `false`: rsbuild.config.ts export default { performance: { buildCache: false, }, }; [#](https://rsbuild.rs/plugins/list/plugin-babel#options) Options ----------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-babel#babelloaderoptions) babelLoaderOptions These options are passed to `babel-loader`. For details, see the [babel-loader documentation](https://github.com/babel/babel-loader) . * **Type:** `Object | Function` * **Default:** const defaultOptions = { babelrc: false, compact: config.mode === 'production', configFile: false, plugins: [\ ['@babel/plugin-proposal-decorators', config.source.decorators],\ ...(isLegacyDecorators ? ['@babel/plugin-transform-class-properties'] : []),\ ], presets: [\ [\ '@babel/preset-typescript',\ {\ allExtensions: true,\ allowDeclareFields: true,\ allowNamespaces: true,\ isTSX: true,\ optimizeConstEnums: true,\ },\ ],\ ], }; #### [#](https://rsbuild.rs/plugins/list/plugin-babel#function-type) Function type When configuration is of type `Function`, the default Babel configuration will be passed as the first parameter. You can directly modify the configuration object or return an object as the final `babel-loader` configuration. pluginBabel({ babelLoaderOptions: (config) => { // Add a Babel plugin // note: the plugin have been added to the default config to support antd load on demand config.plugins ||= []; config.plugins.push([\ 'babel-plugin-import',\ {\ libraryName: 'my-components',\ libraryDirectory: 'es',\ style: true,\ },\ ]); }, }); The second parameter of the function provides some more convenient utility functions. Please continue reading the documentation below. Tip The above example is just for reference. Usually you do not need to manually configure `babel-plugin-import`, because Rsbuild already provides a more general `source.transformImport` configuration. #### [#](https://rsbuild.rs/plugins/list/plugin-babel#object-type) Object type When configuration's type is `Object`, the config will be shallow merged with default config by `Object.assign`. Caution Note that `Object.assign` is a shallow copy and will completely overwrite the built-in `presets` or `plugins` array, please use it with caution. pluginBabel({ babelLoaderOptions: { plugins: [\ [\ 'babel-plugin-import',\ {\ libraryName: 'my-components',\ libraryDirectory: 'es',\ style: true,\ },\ ],\ ], }, }); #### [#](https://rsbuild.rs/plugins/list/plugin-babel#util-functions) Util functions When configuration is a Function, the tool functions available for the second parameter are as follows: ##### [#](https://rsbuild.rs/plugins/list/plugin-babel#addplugins) addPlugins * **Type:** `(plugins: BabelPlugin[]) => void` Add some Babel plugins. For example: pluginBabel({ babelLoaderOptions: (config, { addPlugins }) => { addPlugins([\ [\ 'babel-plugin-import',\ {\ libraryName: 'my-components',\ libraryDirectory: 'es',\ style: true,\ },\ ],\ ]); }, }); ##### [#](https://rsbuild.rs/plugins/list/plugin-babel#addpresets) addPresets * **Type:** `(presets: BabelPlugin[]) => void` Add Babel preset configuration. (No need to add presets in most cases) pluginBabel({ babelLoaderOptions: (config, { addPresets }) => { addPresets(['@babel/preset-env']); }, }); ##### [#](https://rsbuild.rs/plugins/list/plugin-babel#removeplugins) removePlugins * **Type:** `(plugins: string | string[]) => void` To remove the Babel plugin, just pass in the name of the plugin to be removed, you can pass in a single string or an array of strings. pluginBabel({ babelLoaderOptions: (config, { removePlugins }) => { removePlugins('babel-plugin-import'); }, }); ##### [#](https://rsbuild.rs/plugins/list/plugin-babel#removepresets) removePresets * **Type:** `(presets: string | string[]) => void` To remove the Babel preset configuration, pass in the name of the preset to be removed, you can pass in a single string or an array of strings. pluginBabel({ babelLoaderOptions: (config, { removePresets }) => { removePresets('@babel/preset-env'); }, }); ##### [#](https://rsbuild.rs/plugins/list/plugin-babel#modifypresetenvoptions) modifyPresetEnvOptions * **Type:** `(options: PresetEnvOptions) => void` Modify the options of an existing `@babel/preset-env` preset. If the preset is not present in `config.presets`, this function has no effect. pluginBabel({ babelLoaderOptions: (config, { addPresets, modifyPresetEnvOptions }) => { addPresets(['@babel/preset-env']); modifyPresetEnvOptions({ targets: ['chrome >= 107'], }); }, }); ##### [#](https://rsbuild.rs/plugins/list/plugin-babel#modifypresetreactoptions) modifyPresetReactOptions * **Type:** `(options: PresetReactOptions) => void` Modify the options of an existing `@babel/preset-react` preset. If the preset is not present in `config.presets`, this function has no effect. pluginBabel({ babelLoaderOptions: (config, { addPresets, modifyPresetReactOptions }) => { addPresets(['@babel/preset-react']); modifyPresetReactOptions({ runtime: 'automatic', }); }, }); ### [#](https://rsbuild.rs/plugins/list/plugin-babel#include) include * **Type:** `string | RegExp | (string | RegExp)[]` * **Default:** `undefined` Used to specify the files that need to be compiled by Babel. Due to the performance overhead of Babel compilation, matching only certain files through `include` can reduce the number of modules compiled by Babel, thereby improving build performance. For example, to only compile `.custom.js` files: pluginBabel({ include: /\.custom\.js$/, }); Tip When you configure the `include` or `exclude` options, Rsbuild will create a separate Rspack rule to apply babel-loader and swc-loader. This separate rule is completely independent of the SWC rule built into Rsbuild and is not affected by [source.include](https://rsbuild.rs/config/source/include) and [source.exclude](https://rsbuild.rs/config/source/exclude) . ### [#](https://rsbuild.rs/plugins/list/plugin-babel#exclude) exclude * **Type:** `string | RegExp | (string | RegExp)[]` * **Default:** `undefined` Used to specify the files that do not need to be compiled by Babel. Due to the performance overhead of Babel compilation, excluding certain files through `exclude` can reduce the number of modules compiled by Babel, thereby improving build performance. For example, to ignore `.js` files under `node_modules`: pluginBabel({ // Exclude .js files under node_modules to improve build performance exclude: /[\\/]node_modules[\\/].*\.js$/, }); ### [#](https://rsbuild.rs/plugins/list/plugin-babel#parallel) parallel * **Type:** `boolean` * **Default:** `false` * **Version:** `>= 2.0.0` Whether to run Babel transformations in parallel using worker threads. When enabled, JavaScript modules are processed across multiple worker threads, reducing pressure on the main thread and improving overall build performance when compiling large numbers of modules. pluginBabel({ parallel: true, }); > This feature is based on Rspack's parallel loader. Options transferred to worker threads must comply with the [HTML structured clone algorithm](https://nodejs.org/api/worker_threads.html#portpostmessagevalue-transferlist) > . Otherwise, transmission will fail. For example, functions cannot be passed as options. See [Rspack - Rule.use.parallel](https://rspack.rs/config/module-rules#rulesuseparallel) > for more details. [#](https://rsbuild.rs/plugins/list/plugin-babel#configure-multiple-plugins) Configure multiple plugins ------------------------------------------------------------------------------------------------------- By using the `include` and `exclude` options, you can register multiple `@rsbuild/plugin-babel` instances and create separate Babel rules for different files. For example: export default { plugins: [\ pluginBabel({\ exclude: /\.legacy\.js$/,\ babelLoaderOptions: {\ plugins: ['babel-plugin-modern'],\ },\ }),\ pluginBabel({\ include: /\.legacy\.js$/,\ babelLoaderOptions: {\ plugins: ['babel-plugin-legacy'],\ },\ }),\ ], }; [#](https://rsbuild.rs/plugins/list/plugin-babel#execution-order) Execution order --------------------------------------------------------------------------------- After using `@rsbuild/plugin-babel`, Rsbuild will use both `babel-loader` and `builtin:swc-loader` to compile JavaScript files, with Babel running before SWC. This means that if you are using some new ECMAScript features in your code, you may need to add Babel plugins to ensure that Babel can correctly compile these new features. For example, add the [@babel/plugin-transform-private-methods](https://www.npmjs.com/package/@babel/plugin-transform-private-methods) plugin to enable Babel to correctly compile [private properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) : pluginBabel({ babelLoaderOptions: { plugins: ['@babel/plugin-transform-private-methods'], }, }); [#](https://rsbuild.rs/plugins/list/plugin-babel#usage-guides) Usage guides --------------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-babel#use-react-compiler) Use React Compiler This section explains how to enable React Compiler with the Babel plugin. This is an optional approach, mainly useful when you are maintaining an existing Babel-based setup, using an older version of Rsbuild, or need Babel-plugin-based customization. For most projects, we recommend using the Rust-based React Compiler instead. See the [React Compiler guide](https://rsbuild.rs/guide/framework/react#react-compiler) for the recommended setup. Steps to use React Compiler with the Babel plugin: 1. Upgrade `react` and `react-dom` to v19. If you can't upgrade, install the [react-compiler-runtime](https://npmjs.com/package/react-compiler-runtime) package to run the compiled code on earlier versions. 2. Install [@rsbuild/plugin-babel](https://rsbuild.rs/plugins/list/plugin-babel) and [babel-plugin-react-compiler](https://npmjs.com/package/babel-plugin-react-compiler) . 3. Register the Babel plugin in your Rsbuild config file: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginBabel } from '@rsbuild/plugin-babel'; import { pluginReact } from '@rsbuild/plugin-react'; export default defineConfig({ plugins: [\ pluginReact(),\ pluginBabel({\ include: /\.[jt]sx?$/,\ exclude: [/[\\/]node_modules[\\/]/],\ babelLoaderOptions(opts) {\ opts.plugins ??= [];\ opts.plugins.unshift('babel-plugin-react-compiler');\ },\ }),\ ], }); Tip The `include` pattern uses `/\.[jt]sx?$/` to match `.js`, `.jsx`, `.ts`, and `.tsx` files. This ensures React Compiler can optimize both components and [custom hooks](https://react.dev/learn/reusing-logic-with-custom-hooks) , which are often defined in plain `.ts` files. The `exclude` for `node_modules` prevents the compiler from processing third-party dependencies. If you only want to compile JSX/TSX files, you can use `include: /\.(?:jsx|tsx)$/` instead, but custom hooks in `.ts` files will not be optimized. > You can also refer to the [example project](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/react-compiler-babel) > . #### [#](https://rsbuild.rs/plugins/list/plugin-babel#configure-react-compiler) Configure React Compiler To configure React Compiler through Babel, pass the compiler options to `babel-plugin-react-compiler`: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginBabel } from '@rsbuild/plugin-babel'; import { pluginReact } from '@rsbuild/plugin-react'; const ReactCompilerConfig = {/* ... */}; export default defineConfig({ plugins: [\ pluginReact(),\ pluginBabel({\ include: /\.[jt]sx?$/,\ exclude: [/[\\/]node_modules[\\/]/],\ babelLoaderOptions(opts) {\ opts.plugins ??= [];\ opts.plugins.unshift([\ 'babel-plugin-react-compiler',\ ReactCompilerConfig,\ ]);\ },\ }),\ ], }); For React 17 and 18 projects, install [react-compiler-runtime](https://npmjs.com/package/react-compiler-runtime) and specify the `target`: rsbuild.config.ts const ReactCompilerConfig = { target: '18', // '17' | '18' | '19' }; [#](https://rsbuild.rs/plugins/list/plugin-babel#debugging-configs) Debugging configs ------------------------------------------------------------------------------------- After modifying the `babel-loader` configuration, you can view the final generated configuration in [Rsbuild debug mode](https://rsbuild.rs/guide/debug/debug-mode) . First, enable debug mode by using the `DEBUG=rsbuild` option: # Debug development mode DEBUG=rsbuild pnpm dev # Debug production mode DEBUG=rsbuild pnpm build Then open the generated `rspack.config.web.mjs` file and search for the `babel-loader` keyword to see the complete `babel-loader` configuration. [#](https://rsbuild.rs/plugins/list/plugin-babel#helper-functions) Helper functions ----------------------------------------------------------------------------------- `@rsbuild/plugin-babel` provides helper functions for plugin developers and framework authors. ### [#](https://rsbuild.rs/plugins/list/plugin-babel#modifybabelloaders) modifyBabelLoaders * **Type:** function modifyBabelLoaders(options: ModifyBabelLoadersOptions): void; type ModifyBabelLoadersOptions = { chain: RspackChain; CHAIN_ID: ChainIdentifier; modifyOptions?: (options: BabelTransformOptions) => BabelTransformOptions; modifyRule?: ( rule: RspackChain.Rule, context: { babelUseId: string }, ) => void; }; * **Version:** `>= 2.1.0` `modifyBabelLoaders` allows you to modify Babel loader options and their containing rules. * `modifyOptions` updates the current `babel-loader` options and needs to return the final options. * `modifyRule` updates the matched rule. If both callbacks are provided, it runs after `modifyOptions`. Use `babelUseId` to access the Babel loader in that rule. Call it from the [`modifyBundlerChain`](https://rsbuild.rs/plugins/dev/hooks#modifybundlerchain) hook of a custom Rsbuild plugin: rsbuild.config.ts import { defineConfig, type RsbuildPlugin } from '@rsbuild/core'; import { modifyBabelLoaders, pluginBabel } from '@rsbuild/plugin-babel'; const pluginCustomizeBabel = (): RsbuildPlugin => ({ name: 'customize-babel', setup(api) { api.modifyBundlerChain((chain, { CHAIN_ID }) => { modifyBabelLoaders({ chain, CHAIN_ID, modifyOptions(options) { options.plugins ??= []; options.plugins.push('babel-plugin-example'); return options; }, modifyRule(rule) { rule.exclude.add(/[\\/]node_modules[\\/]/); }, }); }); }, }); export default defineConfig({ plugins: [pluginBabel(), pluginCustomizeBabel()], }); [#](https://rsbuild.rs/plugins/list/plugin-babel#faq) FAQ --------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/list/plugin-babel#compilation-freezes) Compilation freezes After using the babel plugin, if the compilation progress bar is stuck, but there is no Error log on the terminal, it is usually because an exception occurred during the compilation. In some cases, when Error is caught by webpack or other modules, the error log cannot be output correctly. The most common scenario is that there is an exception in the Babel config, which is caught by webpack, and webpack swallows the Error in some cases. **Solution:** If this problem occurs after you modify the Babel config, it is recommended to check for the following incorrect usages: 1. You have configured a plugin or preset that does not exist, maybe the name is misspelled, or it is not installed correctly. // wrong example pluginBabel({ babelLoaderOptions: (config, { addPlugins }) => { // The plugin has the wrong name or is not installed addPlugins('babel-plugin-not-exists'); }, }); 2. Whether multiple babel-plugin-imports are configured, but the name of each babel-plugin-import is not declared in the third item of the array. // wrong example pluginBabel({ babelLoaderOptions: (config, { addPlugins }) => { addPlugins([\ ['babel-plugin-import', { libraryName: 'antd', libraryDirectory: 'es' }],\ [\ 'babel-plugin-import',\ { libraryName: 'antd-mobile', libraryDirectory: 'es' },\ ],\ ]); }, }); // correct example pluginBabel({ babelLoaderOptions: (config, { addPlugins }) => { addPlugins([\ [\ 'babel-plugin-import',\ { libraryName: 'antd', libraryDirectory: 'es' },\ 'antd',\ ],\ [\ 'babel-plugin-import',\ { libraryName: 'antd-mobile', libraryDirectory: 'es' },\ 'antd-mobile',\ ],\ ]); }, }); --- # Tailwind CSS 插件 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/plugin-tailwindcss.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/plugin-tailwindcss#tailwind-css-%E6%8F%92%E4%BB%B6) Tailwind CSS 插件 ========================================================================================================== 复制 Markdown [源码](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-tailwindcss) 该插件基于 [@tailwindcss/webpack](https://www.npmjs.com/package/@tailwindcss/webpack) 实现,用于在 Rsbuild 中集成 [Tailwind CSS](https://tailwindcss.com/) v4。 相比基于 [@tailwindcss/postcss](https://www.npmjs.com/package/@tailwindcss/postcss) 的集成方式,该插件无需通过 PostCSS 执行 Tailwind CSS 转换,因此提供了更好的构建性能。 [#](https://rsbuild.rs/zh/plugins/list/plugin-tailwindcss#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) 快速开始 ---------------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-tailwindcss#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 安装插件 执行以下命令安装插件: npm yarn pnpm bun deno npm add @rsbuild/plugin-tailwindcss tailwindcss -D yarn add @rsbuild/plugin-tailwindcss tailwindcss -D pnpm add @rsbuild/plugin-tailwindcss tailwindcss -D bun add @rsbuild/plugin-tailwindcss tailwindcss -D deno add npm:@rsbuild/plugin-tailwindcss npm:tailwindcss -D Tip Tailwind CSS 插件支持 Rsbuild >= 2.0 和 Tailwind CSS >= 4.0。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-tailwindcss#%E6%B3%A8%E5%86%8C%E6%8F%92%E4%BB%B6) 注册插件 在 Rsbuild 配置中注册插件: rsbuild.config.ts import { pluginTailwindcss } from '@rsbuild/plugin-tailwindcss'; export default { plugins: [pluginTailwindcss()], }; ### [#](https://rsbuild.rs/zh/plugins/list/plugin-tailwindcss#%E5%BC%95%E5%85%A5-css) 引入 CSS 在 CSS 入口文件中添加 `@import` 指令,引入 Tailwind CSS: src/index.css @import 'tailwindcss'; 然后在 JavaScript 或 TypeScript 入口中引入这个 CSS 文件: src/index.ts import './index.css'; 现在你可以在 HTML 或框架组件中使用 Tailwind 的 utility classes:

Hello world!

Tip Tailwind CSS v4 不能与 Sass、Less 或 Stylus 等 CSS 预处理器一起使用,你需要将 `@import 'tailwindcss';` 语句放在 `.css` 文件的开头,详见 [Tailwind CSS - Compatibility](https://tailwindcss.com/docs/compatibility#sass-less-and-stylus) 。 [#](https://rsbuild.rs/zh/plugins/list/plugin-tailwindcss#%E6%89%AB%E6%8F%8F%E8%8C%83%E5%9B%B4) 扫描范围 ---------------------------------------------------------------------------------------------------- 默认情况下,该插件会使用 [Rsbuild 根目录](https://rsbuild.rs/zh/config/root) 作为 Tailwind CSS 的扫描基准目录(默认为 `process.cwd()`)。 Tailwind CSS 会自动从扫描基准目录下的文件中检测类名。你可以在 CSS 入口文件中使用 Tailwind CSS 的 `source(...)` 函数和 [`@source` 指令](https://tailwindcss.com/docs/detecting-classes-in-source-files#explicitly-registering-sources) 来收窄或自定义扫描范围: src/index.css @import 'tailwindcss' source('./'); 也可以禁用自动源文件检测,并显式注册需要扫描的源文件: src/index.css @import 'tailwindcss' source(none); @source './pages/**/*.html'; @source './components/**/*.{js,ts,jsx,tsx}'; `source(...)` 和 `@source` 中的相对路径会基于声明它们的 CSS 文件进行解析。 [#](https://rsbuild.rs/zh/plugins/list/plugin-tailwindcss#%E9%80%89%E9%A1%B9) 选项 -------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-tailwindcss#optimize) optimize 启用 Tailwind CSS 自带的 Lightning CSS optimization。 默认情况下,该选项在生产模式下启用,在开发模式下禁用。 * **类型:** type Optimize = | boolean | { minify?: boolean; }; * **默认值:** 生产模式下为 `true`,开发模式下为 `false` 生产模式下,Tailwind CSS 自带的 minify 会跟随 Rsbuild 的 CSS minify 配置。例如,将 [`output.minify`](https://rsbuild.rs/zh/config/output/minify) 设置为 `false` 时,默认配置下也会禁用 Tailwind CSS 自带的 minify。 当 `optimize` 为 `false` 时,Tailwind CSS 仍然会编译 Tailwind directives 并生成 utilities,但会跳过 Tailwind CSS 自带的 Lightning CSS optimization 步骤: rsbuild.config.ts pluginTailwindcss({ optimize: false, }); 如果你希望始终启用 Tailwind CSS 自带的 optimization 和 minify,可以将 `optimize` 设置为 `true`: rsbuild.config.ts pluginTailwindcss({ optimize: true, }); 如果你希望启用 Tailwind CSS 自带的 optimization,但不启用其中的 minify,可以传入对象并省略 `minify`,或者将其设置为 `false`: rsbuild.config.ts pluginTailwindcss({ optimize: { minify: false, }, }); 如果你需要显式启用 Tailwind CSS 自带的 minify: rsbuild.config.ts pluginTailwindcss({ optimize: { minify: true, }, }); --- # Solid 插件 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/plugin-solid.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#solid-%E6%8F%92%E4%BB%B6) Solid 插件 ====================================================================================== 复制 Markdown [源码](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-solid) Solid 插件提供了对 Solid 的支持,插件内部集成了 [babel-preset-solid](https://github.com/solidjs/solid/tree/main/packages/babel-preset-solid) 。 [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) 快速开始 ---------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 安装插件 执行以下命令安装插件: npm yarn pnpm bun deno npm add @rsbuild/plugin-babel @rsbuild/plugin-solid -D yarn add @rsbuild/plugin-babel @rsbuild/plugin-solid -D pnpm add @rsbuild/plugin-babel @rsbuild/plugin-solid -D bun add @rsbuild/plugin-babel @rsbuild/plugin-solid -D deno add npm:@rsbuild/plugin-babel npm:@rsbuild/plugin-solid -D ### [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#%E6%B3%A8%E5%86%8C%E6%8F%92%E4%BB%B6) 注册插件 在 Rsbuild 配置中注册插件: rsbuild.config.ts import { pluginBabel } from '@rsbuild/plugin-babel'; import { pluginSolid } from '@rsbuild/plugin-solid'; export default { plugins: [\ pluginBabel({\ include: /\.(?:jsx|tsx)$/,\ }),\ pluginSolid(),\ ], }; 注册后,即可进行 Solid 开发。 Tip 由于 Solid 的 JSX 依赖 Babel 进行编译,因此你需要额外添加 [Babel 插件](https://rsbuild.rs/zh/plugins/list/plugin-babel) 。 Babel 编译会产生额外的编译开销,在上述例子中,我们通过 `include` 来匹配 `.jsx` 和 `.tsx` 文件,从而减少 Babel 带来的性能开销。 [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#solid-v2) Solid v2 ---------------------------------------------------------------------- Solid v2 支持目前处于 beta 阶段。插件默认使用 Solid native compiler,无需安装 `@rsbuild/plugin-babel`。 安装并注册 `@rsbuild/plugin-solid` 的 beta 版本: npm yarn pnpm bun deno npm add @rsbuild/plugin-solid@beta -D yarn add @rsbuild/plugin-solid@beta -D pnpm add @rsbuild/plugin-solid@beta -D bun add @rsbuild/plugin-solid@beta -D deno add npm:@rsbuild/plugin-solid@beta -D rsbuild.config.ts import { pluginSolid } from '@rsbuild/plugin-solid'; export default { plugins: [pluginSolid()], }; [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#%E8%A7%A3%E6%9E%90%E8%A1%8C%E4%B8%BA) 解析行为 ---------------------------------------------------------------------------------------------- Solid 插件会将 `solid` 添加到 Rsbuild 的 [resolve.conditionNames](https://rsbuild.rs/zh/config/resolve/condition-names) 中,使 package exports 可以解析到 Solid 专属的入口。 在开发模式下,插件还会添加 `development`,用于解析 Solid 的开发环境运行时,并启用开发环境编译转换。你可以通过 [`dev: false`](https://rsbuild.rs/zh/plugins/list/plugin-solid#dev) 同时关闭这两项行为。 如果你配置了 `resolve.conditionNames`,插件会保留已有配置,并在前面添加这些 Solid 条件。 [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#%E9%80%89%E9%A1%B9) 选项 -------------------------------------------------------------------------- 如果你需要自定义 Solid 的编译行为,可以使用以下配置项。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#compiler) compiler JSX 编译器后端。默认使用 native compiler,你可以将此选项设置为 `'babel'`,改用 `babel-preset-solid` 编译 JSX。 * **类型:** `'native' | 'babel'` * **默认值:** `'native'` * **版本:** `>= 2.0.0` * **示例:** pluginSolid({ compiler: 'babel', }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#dev) dev 是否启用 Solid 的开发环境运行时和编译转换。设置为 `false` 可以在开发模式下同时禁用两者,设置为 `true` 可以在生产模式下同时启用两者。 如果显式配置 `solid.dev`,它会覆盖编译转换的 `dev` 设置,但不会影响运行时解析。 * **类型:** `boolean` * **默认值:** 开发模式下为 `true`,生产模式下为 `false` * **示例:** pluginSolid({ dev: false, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#refreshdisabled) refresh.disabled 是否在开发模式下禁用 Solid Refresh HMR。该选项只控制 refresh 转换,不会禁用 Rsbuild HMR。 * **类型:** `boolean` * **默认值:** `false` * **示例:** pluginSolid({ refresh: { disabled: true, }, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#refreshgranular) refresh.granular 是否生成组件级元数据,使代码变更时仅重新挂载实际发生变化的组件。 * **类型:** `boolean` * **默认值:** `true` * **版本:** `>= 2.0.0` * **示例:** pluginSolid({ refresh: { granular: false, }, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#ssr) ssr 是否生成 Solid SSR 输出。启用后,插件会为 Node.js target 设置 `generate: 'ssr'` 和 `hydratable: true`,为其他 target 设置 `generate: 'dom'` 和 `hydratable: true`。 [`solid`](https://rsbuild.rs/zh/plugins/list/plugin-solid#solid) 中的配置会覆盖这些默认值。 * **类型:** `boolean` * **默认值:** `false` * **示例:** pluginSolid({ ssr: true, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-solid#solid) solid 传递给当前 JSX 编译器的 Solid 编译选项。 * **类型:** `SolidPresetOptions` * **默认值:** `{}` * **示例:** pluginSolid({ solid: { generate: 'ssr', hydratable: true, }, }); --- # Plugin API - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/dev/core.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/dev/core#plugin-api) Plugin API ============================================================== Copy Markdown This page explains the type definitions and usage of Rsbuild plugin APIs. [#](https://rsbuild.rs/plugins/dev/core#rsbuildplugin) RsbuildPlugin -------------------------------------------------------------------- `RsbuildPlugin` is the type of the plugin object. It includes the following properties: * `name`: The name of the plugin, a unique identifier. * `setup`: The setup function of the plugin, which can be async. This function runs once when the plugin is initialized. The plugin API provides context, utility functions, and lifecycle hooks. For a complete introduction to lifecycle hooks, see [Plugin hooks](https://rsbuild.rs/plugins/dev/hooks) . * `apply`: Conditionally apply the plugin during serve or build, see [Conditional application](https://rsbuild.rs/plugins/dev/core#conditional-application) . * `enforce`: Specify the execution order of the plugin, see [enforce property](https://rsbuild.rs/plugins/dev/core#enforce-property) . * `pre`: Declare the names of pre-plugins, which will be executed before the current plugin, see [Pre-Plugins](https://rsbuild.rs/plugins/dev/core#pre-plugins) . * `post`: Declare the names of post-plugins, which will be executed after the current plugin, see [Post-Plugins](https://rsbuild.rs/plugins/dev/core#post-plugins) . * `remove`: Declare the plugins that need to be removed, you can pass an array of plugin names, see [Removing plugins](https://rsbuild.rs/plugins/dev/core#removing-plugins) . type RsbuildPlugin = { name: string; setup: (api: RsbuildPluginAPI) => Promise | void; apply?: 'serve' | 'build' | Function; enforce?: 'pre' | 'post'; pre?: string[]; post?: string[]; remove?: string[]; }; You can import this type from `@rsbuild/core`: pluginFoo.ts import type { RsbuildPlugin } from '@rsbuild/core'; export const pluginFoo = (): RsbuildPlugin => ({ name: 'plugin-foo', setup(api) { api.onAfterBuild(() => { console.log('after build!'); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/core#conditional-application) Conditional application By default, plugins are applied for both the dev server and production builds. If you want a plugin to apply only in a specific scenario, you can use the `apply` property to specify when it should be activated: * `serve`: Applies when running the dev or preview server. * `build`: Applies when running a production build. // This plugin only applies during serve const pluginServe = () => ({ name: 'plugin-serve', apply: 'serve', setup(api) { // ... }, }); // This plugin only applies during build const pluginBuild = () => ({ name: 'plugin-build', apply: 'build', setup(api) { // ... }, }); The `apply` property can also be a function that receives two parameters: `config` and `context`. type RsbuildPluginApplyFn = ( this: void, // The original Rsbuild configuration object (before plugin processing) config: RsbuildConfig, // Context object context: { // The current action type action: 'dev' | 'build' | 'preview'; }, ) => boolean; The `apply` function returns `true` to apply the plugin or `false` to skip it. const pluginBuild = () => ({ name: 'plugin-build', apply(config, { action }) { return action === 'build' && config.output?.target === 'web'; }, setup(api) { // ... }, }); Tip The `apply` property was introduced in `@rsbuild/core` v1.4.8. ### [#](https://rsbuild.rs/plugins/dev/core#enforce-property) `enforce` property By default, plugins are executed in the order they are added. Plugins can adjust their execution order by adding an `enforce` property: * `pre`: Execute the plugin before other plugins * `post`: Execute the plugin after other plugins const pluginFoo = () => ({ name: 'plugin-foo', enforce: 'pre', setup(api) { // ... }, }); const pluginBar = () => ({ name: 'plugin-bar', enforce: 'post', setup(api) { // ... }, }); This affects the order in which hooks are registered, but if a hook specifies an [order](https://rsbuild.rs/plugins/dev/hooks#callback-order) property, the `order` takes higher precedence. Tip The `enforce` property was introduced in `@rsbuild/core` v1.4.9. ### [#](https://rsbuild.rs/plugins/dev/core#pre-plugins) Pre-Plugins By setting the `pre` property, you can force some specific plugins to execute before the current plugin. The `pre` property takes higher precedence than the `enforce` property. 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` property, so the Foo plugin will always be executed before the Bar plugin. ### [#](https://rsbuild.rs/plugins/dev/core#post-plugins) Post-Plugins By setting the `post` property, you can force some specific plugins to execute after the current plugin. The `post` property takes higher precedence than the `enforce` property. 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` property, so the Foo plugin will always be executed after the Bar plugin. ### [#](https://rsbuild.rs/plugins/dev/core#removing-plugins) Removing plugins You can remove other plugins within a plugin using the `remove` property. 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. If the current plugin is registered as a [specific environment plugin](https://rsbuild.rs/guide/advanced/environments#plugins-specified-environment) , you can only remove plugins in that environment; global plugins remain in place. [#](https://rsbuild.rs/plugins/dev/core#apicontext) 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](https://rsbuild.rs/api/javascript-api/instance#rsbuildcontext) . * **Example:** const pluginFoo = () => ({ setup(api) { console.log(api.context.distPath); }, }); [#](https://rsbuild.rs/plugins/dev/core#apigetrsbuildconfig) api.getRsbuildConfig --------------------------------------------------------------------------------- Get the Rsbuild config, this method must be called after the `modifyRsbuildConfig` hook is executed. * **Type:** type GetRsbuildConfig = { (): Readonly; (type: 'original' | 'current'): Readonly; (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); }, }); [#](https://rsbuild.rs/plugins/dev/core#apigetnormalizedconfig) api.getNormalizedConfig --------------------------------------------------------------------------------------- Returns either the complete normalized Rsbuild config, including all environments, or the normalized config for a specific environment. You can call this method only after the [modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) hook has completed. Unlike [`getRsbuildConfig`](https://rsbuild.rs/plugins/dev/core#apigetrsbuildconfig) , this method returns a normalized config with narrower types. For example, the type of `config.html` no longer includes `undefined`. Use `getNormalizedConfig()` to get the complete config, including all environments. To get the config for a specific environment, use `getNormalizedConfig({ environment: name })`. * **Type:** type GetNormalizedConfig = { /** Get the complete normalized config, including all environments */ (): NormalizedConfig; /** Get the normalized config for a specific environment */ (options: { environment: string }): NormalizedEnvironmentConfig; }; * **Example:** const pluginFoo = () => ({ setup(api) { api.onBeforeBuild(({ bundlerConfigs }) => { const config = api.getNormalizedConfig(); console.log(config.html.title); }); }, }); When a plugin hook provides [`environment`](https://rsbuild.rs/api/javascript-api/environment-api#environment-context) in its callback arguments, we recommend using `environment.config` to access the normalized config for the current environment. This config is created by merging the base config with the [config for the current environment](https://rsbuild.rs/guide/advanced/environments) and then normalizing the result. const pluginFoo = () => ({ setup(api) { api.onBeforeEnvironmentCompile(({ environment }) => { const { config } = environment; console.log(config.output.target); }); }, }); [#](https://rsbuild.rs/plugins/dev/core#apilogger) api.logger ------------------------------------------------------------- A logger instance that can be used to output logs in a format consistent with Rsbuild. > See [Logging](https://rsbuild.rs/guide/advanced/logging) > for more details. * **Version:** `>= 1.4.0` * **Example:** const pluginLogging = () => ({ setup(api) { api.logger.info('This is an info message'); api.logger.warn('This is a warning message'); api.logger.error('This is an error message'); }, }); [#](https://rsbuild.rs/plugins/dev/core#apiispluginexists) api.isPluginExists ----------------------------------------------------------------------------- Determines if a plugin has been registered in the current Rsbuild instance. * If the `environment` parameter is not specified, it checks if the plugin exists in the globally registered plugins. * If the `environment` parameter is specified, it checks if the plugin exists in the specified environment. * **Type:** function IsPluginExists( pluginName: string, options?: { /** * Whether it exists in the specified environment. * If environment is not specified, determine whether the plugin is a global plugin. */ environment: string; }, ): boolean; * **Example:** export default () => ({ setup(api) { console.log(api.isPluginExists('plugin-foo')); }, }); Or check if a plugin exists in a specified environment: export default () => ({ setup(api) { console.log(api.isPluginExists('plugin-foo', { environment: 'web' })); }, }); [#](https://rsbuild.rs/plugins/dev/core#apitransform) api.transform ------------------------------------------------------------------- A simplified wrapper around [Rspack loaders](https://rspack.rs/guide/features/loader) , `api.transform` lets you easily transform the code of specific modules during the build process. You can match files by module path, query, or other conditions, and apply custom transformations to their contents. * **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. ### [#](https://rsbuild.rs/plugins/dev/core#example) 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;`; }); }, }); ### [#](https://rsbuild.rs/plugins/dev/core#descriptor-param) 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; layer?: string; issuer?: RuleSetCondition; issuerLayer?: string; with?: Record; mimetype?: RuleSetCondition; /** @deprecated Use `order` instead. */ enforce?: 'pre' | 'post'; order?: 'pre' | 'post' | 'default'; }; The `descriptor` param supports the following matching conditions: * `test`: matches module's path (without query), the same as Rspack's [rules\[\].test](https://rspack.rs/config/module-rules#rulestest) . api.transform({ test: /\.md$/ }, ({ code }) => { // ... }); * `targets`: matches the Rsbuild [output.target](https://rsbuild.rs/config/output/target) , and applies the current transform function only to the matched targets. api.transform({ test: /\.md$/, targets: ['web'] }, ({ code }) => { // ... }); * `environments`: matches the Rsbuild [environment](https://rsbuild.rs/guide/advanced/environments) name, and applies the current transform function only to the matched environments. api.transform({ test: /\.md$/, environments: ['web'] }, ({ code }) => { // ... }); * `resourceQuery`: matches module's query, the same as Rspack's [rules\[\].resourceQuery](https://rspack.rs/config/module-rules#rulesresourcequery) . // match raw query: "foo.ext?raw" 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 }) => { // ... }); * `layer`: marks the layer of the matching module, can be used to group a group of modules into one layer, the same as Rspack's [rules\[\].layer](https://rspack.rs/config/module-rules#ruleslayer) . api.transform({ test: /\.md$/, layer: 'foo' }, ({ code }) => { // ... }); * `issuerLayer`: matches the layer of the module that issues the current module, the same as Rspack's [rules\[\].issuerLayer](https://rspack.rs/config/module-rules#rulesissuerlayer) . api.transform({ test: /\.md$/, issuerLayer: 'foo' }, ({ code }) => { // ... }); * `issuer`: matches the absolute path of the module that issues the current module, the same as Rspack's [rules\[\].issuer](https://rspack.rs/config/module-rules#rulesissuer) . api.transform({ test: /\.md$/, issuer: /\.js$/ }, ({ code }) => { // ... }); * `with`: matches [import attributes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import/with) , the same as Rspack's [rules\[\].with](https://rspack.rs/config/module-rules#ruleswith) . api.transform({ test: /\.md$/, with: { type: 'url' } }, ({ code }) => { // ... }); * `mimetype`: Matches modules based on MIME type instead of file extension. It's primarily useful for data URI module (like `data:text/javascript,...`), the same as Rspack's [rules\[\].mimetype](https://rspack.rs/config/module-rules#rulesmimetype) . api.transform({ mimetype: 'text/javascript' }, ({ code }) => { // ... }); * `order`: Specifies the execution order of the transform function, corresponding to Rspack's [rules\[\].enforce](https://rspack.rs/config/module-rules#rulesenforce) . * When `order` is `pre`, the transform function will be executed before other transform functions (or Rspack loaders). * When `order` is `post`, the transform function will be executed after other transform functions (or Rspack loaders). * When `order` is `default`, the transform function will use the default loader order. api.transform({ test: /\.md$/, order: 'pre' }, ({ code }) => { // ... }); * `enforce`: Deprecated. Use `order` instead. ### [#](https://rsbuild.rs/plugins/dev/core#handler-param) 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; context: string | null; resource: string; resourcePath: string; resourceQuery: string; environment: EnvironmentContext; addDependency: (file: string) => void; addMissingDependency: (file: string) => void; addContextDependency: (context: string) => void; emitFile: Rspack.LoaderContext['emitFile']; importModule: Rspack.LoaderContext['importModule']; resolve: Rspack.LoaderContext['resolve']; }; type TransformResult = | string | Buffer | { code: string | Buffer; map?: string | Rspack.sources.RawSourceMap | null; }; type TransformHandler = ( context: TransformContext, ) => MaybePromise; The `handler` function provides the following params: * `code`: The code of the module. * `context`: The directory path of the currently processed module. The same as Rspack loader's [this.context](https://rspack.rs/api/loader-api/context#thiscontext) . * `resolve`: Resolve a module specifier. The same as Rspack loader's [this.resolve](https://rspack.rs/api/loader-api/context#thisresolve) . * `resource`: The absolute path of the module, including the query. The same as Rspack loader's [this.resource](https://rspack.rs/api/loader-api/context#thisresource) . * `resourcePath`: The absolute path of the module, without the query. The same as Rspack loader's [this.resourcePath](https://rspack.rs/api/loader-api/context#thisresourcepath) . * `resourceQuery`: The query of the module. The same as Rspack loader's [this.resourceQuery](https://rspack.rs/api/loader-api/context#thisresourcequery) . * `environment`: The [environment context](https://rsbuild.rs/api/javascript-api/environment-api#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. The same as Rspack loader's [this.addDependency](https://rspack.rs/api/loader-api/context#thisadddependency) . * `addMissingDependency`: Add an non-existing file as the dependency. The file will be watched and changes to the file will trigger rebuild. The same as Rspack loader's [this.addMissingDependency](https://rspack.rs/api/loader-api/context#thisaddmissingdependency) . * `addContextDependency`: Add an additional directory as the dependency. The directory will be watched and changes to the directory will trigger rebuild. The same as Rspack loader's [this.addContextDependency](https://rspack.rs/api/loader-api/context#thisaddcontextdependency) . * `emitFile`: Emits a file to the build output. The same as Rspack loader's [this.emitFile](https://rspack.rs/api/loader-api/context#thisemitfile) . * `importModule`: Compile and execute a module at the build time. The same as Rspack loader's [this.importModule](https://rspack.rs/api/loader-api/context#thisimportmodule) . For example: api.transform( { test: /\.md$/ }, ({ 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' }, ); ### [#](https://rsbuild.rs/plugins/dev/core#difference-with-loader) Difference with loader `api.transform` can be thought of as a lightweight implementation of Rspack loader. It provides a simple, 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. ### [#](https://rsbuild.rs/plugins/dev/core#source-maps) Source maps You can return a source map in the `transform` function, and Rsbuild will automatically merge the returned source map with source maps generated by other Rspack loaders or `transform` hooks, ensuring that the final source map correctly maps back to the original source code. api.transform({ test: /\.js$/ }, async ({ code }) => { const { transformedCode, sourceMap } = await someTransformFunction(code); return { code: transformedCode, map: sourceMap, }; }); [#](https://rsbuild.rs/plugins/dev/core#apiresolve) api.resolve --------------------------------------------------------------- Intercept and modify module request information before module resolution begins. The same as Rspack's [normalModuleFactory.hooks.resolve](https://rspack.rs/api/plugin-api/normal-module-factory-hooks#resolve) hook. * **Version:** `>= 1.0.17` * **Type:** function ResolveHook(handler: ResolveHandler): void; ### [#](https://rsbuild.rs/plugins/dev/core#example-1) Example * Modify the request of `a.js` file: api.resolve(({ resolveData }) => { if (resolveData.request === './a.js') { resolveData.request = './b.js'; } }); ### [#](https://rsbuild.rs/plugins/dev/core#handler-param-1) Handler param The `handler` parameter is a callback function that receives a module require information and allows you to modify it. * **Type:** type ResolveHandler = (context: { resolveData: Rspack.ResolveData; compiler: Rspack.Compiler; compilation: Rspack.Compilation; environment: EnvironmentContext; }) => Promise | void; The `handler` function provides the following parameters: * `resolveData`: Module request information. For details, please refer to [Rspack - resolve hook](https://rspack.rs/api/plugin-api/normal-module-factory-hooks#resolve) . * `compiler`: The Compiler object of Rspack. * `compilation`: The Compilation object of Rspack. * `environment`: The environment context of the current build. [#](https://rsbuild.rs/plugins/dev/core#apiprocessassets) api.processAssets --------------------------------------------------------------------------- Modify assets before emitting, the same as Rspack's [compilation.hooks.processAssets](https://rspack.rs/api/plugin-api/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. ### [#](https://rsbuild.rs/plugins/dev/core#example-2) 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: 'optimize' }, ({ assets, compilation }) => { const assetName = 'unwanted-script.js'; if (assets[assetName]) { compilation.deleteAsset(assetName); } }); ### [#](https://rsbuild.rs/plugins/dev/core#descriptor-param-1) 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](https://rsbuild.rs/plugins/dev/core#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](https://rsbuild.rs/config/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](https://rsbuild.rs/guide/advanced/environments) name, and applies the current processAssets function only to the matched environments. api.processAssets( { stage: 'additional', environments: ['web'] }, ({ assets }) => { // ... }, ); ### [#](https://rsbuild.rs/plugins/dev/core#handler-param-2) 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; compiler: Rspack.Compiler; compilation: Rspack.Compilation; environment: EnvironmentContext; sources: RspackSources; }) => Promise | 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](https://github.com/webpack/webpack-sources#source) . * `compiler`: The Compiler object of Rspack. * `compilation`: The Compilation object of Rspack. * `environment`: The [environment context](https://rsbuild.rs/api/javascript-api/environment-api#environment-context) of the current build. * `sources`: The [Rspack Sources](https://github.com/webpack/webpack-sources#source) object, which contains multiple classes which represent a Source. ### [#](https://rsbuild.rs/plugins/dev/core#process-assets-stages) 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. * `none` — run at `PROCESS_ASSETS_STAGE_NONE`, without selecting a specialized processing stage. * `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. [#](https://rsbuild.rs/plugins/dev/core#apiexpose) 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 * @param options Options for exposing the API */ function expose( id: string | symbol, api: T, options?: { /** * Register the exposed API for a specific environment. * If omitted, the API is registered as global. */ environment?: string; }, ): void; * **Example:** const pluginParent = () => ({ name: 'plugin-parent', setup(api) { api.expose('plugin-parent', { value: 1, double: (val: number) => val * 2, }); }, }); Tip If `api.expose` is called multiple times with the same `id` and `environment`, the latter call will overwrite the previously exposed API. ### [#](https://rsbuild.rs/plugins/dev/core#environment-scoped-api) Environment scoped API You can register an exposed API for a specific Rsbuild environment (the key of `config.environments`) by setting `options.environment`. When `api.useExposed` is called in an environment plugin, Rsbuild will first resolve the exposed API registered for the same environment, then fall back to the global exposed API. api.expose('my-api', { name: 'web' }, { environment: 'web' }); api.expose('my-api', { name: 'node' }, { environment: 'node' }); If `options.environment` is omitted, the API is registered as global and can be used as a fallback by plugins in all environments. [#](https://rsbuild.rs/plugins/dev/core#apiuseexposed) 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 * * If the current plugin is registered in an environment, Rsbuild will * first resolve the exposed API registered for the same environment, * then fall back to the global exposed API. */ function useExposed(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 } }, }); ### [#](https://rsbuild.rs/plugins/dev/core#identifiers) 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); } }, }); ### [#](https://rsbuild.rs/plugins/dev/core#type-declaration) 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(PARENT_API_ID); if (parentApi) { console.log(parentApi); } }, }); ### [#](https://rsbuild.rs/plugins/dev/core#execution-order) 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. --- # React 插件 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/plugin-react.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/plugin-react#react-%E6%8F%92%E4%BB%B6) React 插件 ====================================================================================== 复制 Markdown [源码](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-react) React 插件提供了对 React 的支持,插件内部集成了 JSX 编译、React Refresh 等功能。 [#](https://rsbuild.rs/zh/plugins/list/plugin-react#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) 快速开始 ---------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 安装插件 执行以下命令安装插件: npm yarn pnpm bun deno npm add @rsbuild/plugin-react -D yarn add @rsbuild/plugin-react -D pnpm add @rsbuild/plugin-react -D bun add @rsbuild/plugin-react -D deno add npm:@rsbuild/plugin-react -D ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#%E6%B3%A8%E5%86%8C%E6%8F%92%E4%BB%B6) 注册插件 在 Rsbuild 配置中注册插件: rsbuild.config.ts import { pluginReact } from '@rsbuild/plugin-react'; export default { plugins: [pluginReact()], }; 注册后,即可进行 React 开发。 [#](https://rsbuild.rs/zh/plugins/list/plugin-react#%E9%80%89%E9%A1%B9) 选项 -------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#swcreactoptions) swcReactOptions 用于配置 SWC 转换 React 代码的行为,等价于 SWC 的 [jsc.transform.react](https://swc.rs/docs/configuration/compilation#jsctransformreact) 选项。 * **类型:** interface ReactConfig { pragma?: string; pragmaFrag?: string; throwIfNamespace?: boolean; development?: boolean; refresh?: | boolean | { refreshReg?: string; refreshSig?: string; emitFullSignatures?: boolean; }; runtime?: 'automatic' | 'classic' | 'preserve'; importSource?: string; } * **默认值:** 使用 automatic JSX runtime,并在适用时启用开发模式转换和 Fast Refresh。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#swcreactoptionsruntime) swcReactOptions.runtime 设置在转换 JSX 时使用哪种运行时。 * **类型:** `'automatic' | 'classic' | 'preserve'` * **默认值:** `'automatic'` #### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#automatic) automatic 默认情况下,Rsbuild 使用 `runtime: 'automatic'` 来利用 React 17 中引入的 [新版 JSX 转换](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) 。 采用这种方式时,无需在每个 JSX 文件中手动导入 React。 Tip React 16.14.0 及更高版本支持新版 JSX 运行时。 #### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#classic) classic 对于 React 16.14.0 之前的版本,将 `runtime` 设置为 `'classic'`: pluginReact({ swcReactOptions: { runtime: 'classic', }, }); 当使用经典 JSX 运行时的时候,你必须在代码中手动导入 React: App.jsx import React from 'react'; function App() { return

Hello World

; } #### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#preserve) preserve 使用 `runtime: 'preserve'` 可以保持 JSX 语法原样,不做任何转换,这在开发需要保留 JSX 代码的库时非常有用。 pluginReact({ swcReactOptions: { runtime: 'preserve', }, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#swcreactoptionsimportsource) swcReactOptions.importSource 当 `runtime` 为 `'automatic'` 时,你可以通过 `importSource` 来指定 JSX runtime 的引入路径。 * **类型:** `string` * **默认值:** `'react'` 比如,在使用 [Emotion](https://emotion.sh/) 时,你可以将 `importSource` 设置为 `'@emotion/react'`: pluginReact({ swcReactOptions: { importSource: '@emotion/react', }, }); > 参考 [自定义 JSX](https://rsbuild.rs/zh/guide/framework/react#customize-jsx) > 了解更多。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#swcreactoptionsrefresh) swcReactOptions.refresh * **类型:** `boolean` * **默认值:** 当 [fastRefresh](https://rsbuild.rs/zh/plugins/list/plugin-react#fastrefresh) 和 [dev.hmr](https://rsbuild.rs/zh/config/dev/hmr) 启用时,在开发模式的 web 构建中启用 是否启用 [React Fast Refresh](https://npmjs.com/package/react-refresh) 。 大多数情况下,你应该使用插件的 [fastRefresh](https://rsbuild.rs/zh/plugins/list/plugin-react#fastrefresh) 选项来启用或禁用 Fast Refresh。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#reactcompiler) reactCompiler 启用或配置 [React Compiler](https://react.dev/learn/react-compiler) ,Rsbuild 会将该选项传递给 Rspack 的 [`builtin:swc-loader`](https://rspack.rs/zh/guide/tech/react#%E4%BD%BF%E7%94%A8-builtinswc-loader) ,对应 `jsc.transform.reactCompiler` 配置。 Tip 该选项仅在 `@rsbuild/core` v2.1.0 及以上版本中支持。 * **类型:** type ReactCompiler = | boolean | { compilationMode?: 'infer' | 'syntax' | 'annotation' | 'all'; panicThreshold?: 'none' | 'critical_errors' | 'all_errors'; target?: '17' | '18' | '19'; noEmit?: boolean; outputMode?: 'client' | 'ssr' | 'lint'; ignoreUseNoForget?: boolean; flowSuppressions?: boolean; enableReanimated?: boolean; isDev?: boolean; eslintSuppressionRules?: string[]; customOptOutDirectives?: string[]; gating?: { source: string; importSpecifierName: string; }; dynamicGating?: { source: string; }; }; * **默认值:** `undefined` 将 `reactCompiler` 设置为 `true`,即可使用默认选项启用 React Compiler: pluginReact({ reactCompiler: true, }); 对于 React 17 和 18 项目,需要安装 [`react-compiler-runtime`](https://npmjs.com/package/react-compiler-runtime) ,并设置编译目标: pluginReact({ reactCompiler: { target: '18', }, }); `reactCompiler` 的选项与 React Compiler 配置对齐。例如,你可以通过 [`compilationMode`](https://react.dev/reference/react-compiler/compilationMode) 控制哪些函数会被编译: pluginReact({ reactCompiler: { compilationMode: 'annotation', }, }); 更多选项请参考官方 [React Compiler 配置说明](https://react.dev/reference/react-compiler/configuration) 。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#splitchunks) splitChunks 当使用 Rsbuild 的 [默认拆包 preset](https://rsbuild.rs/zh/config/split-chunks#default) 时,该插件会将与 `react` 和 `react-router` 相关的包拆分到独立的 chunk 中。 * `lib-react.js`:包含 `react`、`react-dom`,以及它们的子依赖(`scheduler`)。在开发环境下,它还会包含 React Fast Refresh 运行时包(`react-refresh`、`@rspack/plugin-react-refresh`)。 * `lib-router.js`:包含 `react-router`、`react-router-dom`,以及它们的子依赖(`history`,`@remix-run/router`)。 该选项用于控制这一行为,决定是否需要将 `react` 和 `router` 相关的包拆分为单独的 chunk。 * **类型:** type SplitChunks = | boolean | { react?: boolean; router?: boolean; }; * **默认值:** `true`(等价于 `{ react: true, router: true }`) 例如,禁用所有 chunks 拆分: pluginReact({ splitChunks: false }); 或是仅禁用 `router` chunk 拆分: pluginReact({ splitChunks: { react: true, router: false, }, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#enableprofiler) enableProfiler * **类型:** `boolean` * **默认值:** `false` 当设置为 `true` 时,在生产构建中启用 React 性能分析器以用于性能分析。需要搭配 React DevTools 来检查分析结果并识别潜在的性能优化方案。分析会增加一些额外开销,因此出于性能考虑,在生产模式中默认是禁用的。 rsbuild.config.ts pluginReact({ // 仅在 REACT_PROFILER 为 true 时启用性能分析器 // 因为该选项会增加构建时间并产生一些额外开销 enableProfiler: process.env.REACT_PROFILER === 'true', }); 执行构建脚本时,设置 `REACT_PROFILER=true` 即可: package.json { "scripts": { "build:profiler": "REACT_PROFILER=true rsbuild build" } } 由于 Windows 不支持上述用法,你也可以使用 [cross-env](https://npmjs.com/package/cross-env) 来设置环境变量,这可以确保在不同的操作系统中都能正常使用: package.json { "scripts": { "build:profiler": "cross-env REACT_PROFILER=true rsbuild build" }, "devDependencies": { "cross-env": "^7.0.0" } } > 关于使用 React DevTools 进行性能分析的详细信息,请参见 [React 文档](https://legacy.reactjs.org/docs/optimizing-performance.html#profiling-components-with-the-devtools-profiler) > 。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#reactrefreshoptions) reactRefreshOptions * **类型:** type ReactRefreshOptions = { // @link https://rspack.rs/zh/config/module-rules#condition test?: Rspack.RuleSetCondition; include?: Rspack.RuleSetCondition | null; exclude?: Rspack.RuleSetCondition | null; resourceQuery?: Rspack.RuleSetCondition; library?: string; forceEnable?: boolean; injectLoader?: boolean; injectEntry?: boolean; reloadOnRuntimeErrors?: boolean; reactRefreshLoader?: string; }; * **默认值:** Rsbuild 会对内置 JavaScript 规则处理的文件应用 React Fast Refresh,但通过 `?raw` 导入的文件除外。 设置 [@rspack/plugin-react-refresh](https://github.com/rstackjs/rspack-plugin-react-refresh) 的选项,传入的值会与默认值进行浅合并。 * **示例:** pluginReact({ reactRefreshOptions: { exclude: [/some-module-to-exclude/, /[\\/]node_modules[\\/]/], }, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-react#fastrefresh) fastRefresh * **类型:** `boolean` * **默认值:** `true` 是否在开发模式下启用 [React Fast Refresh](https://npmjs.com/package/react-refresh) 。 当 `fastRefresh` 设置为 `true` 时,`@rsbuild/plugin-react` 会在启用 HMR 的开发模式 web 构建中自动注册 [@rspack/plugin-react-refresh](https://github.com/rstackjs/rspack-plugin-react-refresh) 插件。 如果你需要禁用 Fast Refresh,可以将其设置为 `false`: pluginReact({ fastRefresh: false, }); --- # SVGR 插件 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/plugin-svgr.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#svgr-%E6%8F%92%E4%BB%B6) SVGR 插件 =================================================================================== 复制 Markdown [源码](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-svgr) 默认情况下,Rsbuild 会将 SVG 图片当作静态资源处理,处理规则可参考:[静态资源](https://rsbuild.rs/zh/guide/basic/static-assets) 。 通过添加 SVGR 插件,Rsbuild 支持调用 [SVGR](https://react-svgr.com/) ,将 SVG 图片转换为一个 React 组件使用。 [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) 快速开始 --------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 安装插件 执行以下命令安装插件: npm yarn pnpm bun deno npm add @rsbuild/plugin-svgr -D yarn add @rsbuild/plugin-svgr -D pnpm add @rsbuild/plugin-svgr -D bun add @rsbuild/plugin-svgr -D deno add npm:@rsbuild/plugin-svgr -D ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#%E6%B3%A8%E5%86%8C%E6%8F%92%E4%BB%B6) 注册插件 在 Rsbuild 配置中注册插件: rsbuild.config.ts import { pluginReact } from '@rsbuild/plugin-react'; import { pluginSvgr } from '@rsbuild/plugin-svgr'; export default { plugins: [pluginReact(), pluginSvgr()], }; [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#%E7%A4%BA%E4%BE%8B) 示例 ------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#%E9%BB%98%E8%AE%A4%E7%94%A8%E6%B3%95) 默认用法 注册后,在 **JS 文件**中引用带有 `?react` 后缀的 SVG 资源时,Rsbuild 会调用 SVGR 将 SVG 图片转换为 React 组件。 App.jsx import Logo from './logo.svg?react'; export const App = () => ; 如果导入的路径不包含 `?react` 后缀,那么 SVG 会被当做普通的静态资源来处理,你会得到一个 URL 字符串或 base64 URL,参考 [静态资源](https://rsbuild.rs/zh/guide/basic/static-assets) 。 import logoURL from './static/logo.svg'; console.log(logoURL); // => "/static/svg/logo.6c12aba3ab.svg" 或 base64 URL ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#%E5%85%B7%E5%90%8D%E5%AF%BC%E5%85%A5) 具名导入 `@rsbuild/plugin-svgr` 支持具名导入 `ReactComponent` 来使用 SVGR,你需要设置 [svgrOptions.exportType](https://rsbuild.rs/zh/plugins/list/plugin-svgr#svgroptionsexporttype) 为 `'named'`: pluginSvgr({ svgrOptions: { exportType: 'named', }, }); App.jsx import { ReactComponent as Logo } from './logo.svg'; export const App = () => ; `@rsbuild/plugin-svgr` 也支持默认导入和混合导入等用法: * 通过 [svgrOptions.exportType](https://rsbuild.rs/zh/plugins/list/plugin-svgr#svgroptionsexporttype) 设置为 `'default'` 来启用默认导入。 * 通过 [mixedImport](https://rsbuild.rs/zh/plugins/list/plugin-svgr#mixedimport) 选项来启用混合导入,从而同时使用默认导入和具名导入。 [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#%E9%80%89%E9%A1%B9) 选项 ------------------------------------------------------------------------- 如果你需要自定义 SVGR 的编译行为,可以使用以下配置项: * **类型:** type PluginSvgrOptions = { /** * 修改 SVGR 选项 */ svgrOptions?: import('@svgr/core').Config; /** * 是否允许同时使用默认导入和具名导入 * @default false */ mixedImport?: boolean; /** * 自定义匹配 SVGR 转换的 query 后缀 * @default /react/ */ query?: RegExp; /** * 是否并行将 SVG 模块转换为 React 组件 * @default false */ parallel?: boolean; /** * 排除一部分 SVG 文件,这些文件不会经过 SVGR 处理 */ exclude?: Rspack.RuleSetCondition; /** * 排除一部分模块,这些模块引用的 SVG 文件不会经过 SVGR 处理 */ excludeImporter?: Rspack.RuleSetCondition; }; ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#svgroptions) svgrOptions 用于修改 SVGR 的选项,传入的对象会与默认值进行 deep merge。完整文档请参考 [SVGR - Options](https://react-svgr.com/docs/options/) 。 * **类型:** `import('@svgr/core').Config` * **默认值:** const defaultSvgrOptions = { svgo: true, svgoConfig: { plugins: [\ {\ name: 'preset-default',\ params: {\ overrides: {\ removeViewBox: false,\ },\ },\ },\ 'prefixIds',\ ], }, }; * **示例:** pluginSvgr({ svgrOptions: { svgoConfig: { datauri: 'base64', }, }, }); 当你设置 `svgoConfig.plugins` 时,同名 plugin 的配置会被自动合并,比如下面的配置会与内置的 `preset-default` 进行合并: pluginSvgr({ svgrOptions: { svgoConfig: { plugins: [\ {\ name: 'preset-default',\ params: {\ overrides: {\ cleanupIds: false,\ },\ },\ },\ ], }, }, }); 合并后的 `svgoConfig` 如下: const mergedSvgoConfig = { plugins: [\ {\ name: 'preset-default',\ params: {\ overrides: {\ removeViewBox: false,\ cleanupIds: false,\ },\ },\ },\ 'prefixIds',\ ], }; ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#svgroptionsexporttype) svgrOptions.exportType 设置 SVG React 组件的导出方式。 * **类型:** `'default' | 'named'` * **默认值:** `undefined` `exportType` 可以设置为: * `default`:使用默认导出。 * `named`:使用 `ReactComponent` 具名导出。 比如把 SVG 文件默认导出的内容设置为 React 组件: pluginSvgr({ svgrOptions: { exportType: 'default', }, }); 此时再使用默认导入,你会得到一个 React 组件,而不是 URL: import Logo from './logo.svg'; console.log(Logo); // => React 组件 同时,你也可以通过指定 `?url` 的 query 来导入 url,比如: import logo from './logo.svg?url'; console.log(logo); // => 资源 url Tip 当 `svgrOptions.exportType` 被设置为 `'default'` 时,具名导入(ReactComponent)将无法使用。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#mixedimport) mixedImport * **类型:** `boolean` * **默认值:** `false` 是否开启混合导入,允许同时使用默认导入和命名导入。 混合导入通常和 `svgrOptions.exportType: 'named'` 同时使用,比如: pluginSvgr({ mixedImport: true, svgrOptions: { exportType: 'named', }, }); 此时引用的 SVG 文件会同时导出 URL 和 React 组件: import logoUrl, { ReactComponent as Logo } from './logo.svg'; console.log(logoUrl); // -> string console.log(Logo); // -> React component Tip 启用 `mixedImport` 后,如果没有显式设置 `svgrOptions.exportType`,则默认值为 `'named'`。 #### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#%E5%B1%80%E9%99%90%E6%80%A7) 局限性 建议优先使用 `?react` 来将 SVG 转换为 React 组件,而不是使用混合导入。因为混合导入有如下局限性: 1. 包体积增加:混合导入会导致单个 SVG 模块被编译为两种代码(即使部分导出没有被使用),这会增加产物的包体积。 2. 编译速度下降:混合导入会产生额外的编译开销。即使代码中未使用到 ReactComponent 导出,SVG 文件仍然会被 SVGR 编译。而 SVGR 是基于 Babel 实现的,性能开销较大。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#query) query * **类型:** `RegExp` * **默认值:** `/react/` 用于自定义匹配 SVGR 转换的 query 后缀。 比如需要匹配带有 `?svgr` 后缀的 import 路径: pluginSvgr({ query: /svgr/, }); App.jsx import Logo from './logo.svg?svgr'; export const App = () => ; ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#parallel) parallel * **类型:** `boolean` * **默认值:** `false` * **版本:** 添加于 v2.0.4 是否使用 worker 线程并行将 SVG 模块转换为 React 组件。开启后,SVG 模块会被分配到多个 worker 线程中处理,降低主线程压力,并在编译大量 SVG 模块时提升整体构建性能。 pluginSvgr({ parallel: true, }); > 该功能基于 Rspack 的 parallel loader 实现。传递给 worker 线程的选项必须符合 [HTML 结构化克隆算法](https://nodejs.org/api/worker_threads.html#portpostmessagevalue-transferlist) > 的要求,否则会传输失败。例如,不能将函数作为选项传递。详见 [Rspack - Rule.use.parallel](https://rspack.rs/zh/config/module-rules#rulesuseparallel) > 。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#exclude) exclude * **类型:** [Rspack.RuleSetCondition](https://rspack.rs/zh/config/module-rules#condition) * **默认值:** `undefined` 用于排除一部分 SVG 模块,这些 SVG 模块不会经过 SVGR 处理。 比如,项目中包含 `a.svg` 和 `b.svg`,你可以将 `b.svg` 添加到 exclude: pluginSvgr({ svgrOptions: { exportType: 'default', }, exclude: /b\.svg/, }); 在引用时,`a.svg` 会被转换为 React 组件,`b.svg` 会被当做普通的静态资源来处理: src/index.ts import component from './a.svg'; import url from './b.svg'; console.log(component); // => React 组件 console.log(url); // => 资源 url ### [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#excludeimporter) excludeImporter * **类型:** [Rspack.RuleSetCondition](https://rspack.rs/zh/config/module-rules#condition) * **默认值:** `undefined` 用于排除一部分模块,这些模块引用的 SVG 文件不会经过 SVGR 处理。 比如,项目中包含 `page-a/index.ts` 和 `page-b/index.ts`,你可以将 `page-b` 添加到 excludeImporter: pluginSvgr({ svgrOptions: { exportType: 'default', }, excludeImporter: /\/page-b\/index\.ts/, }); * page-a 中引用的 SVG 会被转换为 React 组件: page-a/index.ts import Logo from './logo.svg'; console.log(Logo); // => React 组件 * page-b 中引用的 SVG 会被当做普通的静态资源来处理: page-b/index.ts import url from './logo.svg'; console.log(url); // => 资源 url Tip 模块路径中的 query 比 `exclude` 和 `excludeImporter` 具有更高的优先级。比如某个模块被 exclude,添加 `?react` 依然可以使它被 SVGR 转换。 [#](https://rsbuild.rs/zh/plugins/list/plugin-svgr#%E7%B1%BB%E5%9E%8B%E5%A3%B0%E6%98%8E) 类型声明 --------------------------------------------------------------------------------------------- 当你在 TypeScript 代码中引用 SVG 资源时,TypeScript 可能会提示该模块缺少类型定义: TS2307: Cannot find module './logo.svg?react' or its corresponding type declarations. 此时你需要为 SVG 资源添加类型声明文件,请在项目中创建 `src/env.d.ts` 文件,并添加相应的类型声明。 * 默认情况下,你可以添加如下类型声明: declare module '*.svg' { const content: string; export default content; } declare module '*.svg?react' { const ReactComponent: React.FunctionComponent>; export default ReactComponent; } * 如果 `svgrOptions.exportType` 的值为 `'default'`,则将类型声明设置为: declare module '*.svg' { const ReactComponent: React.FunctionComponent>; export default ReactComponent; } declare module '*.svg?react' { const ReactComponent: React.FunctionComponent>; export default ReactComponent; } * 如果 `svgrOptions.exportType` 的值为 `'named'`,则将类型声明设置为: declare module '*.svg' { export const ReactComponent: React.FunctionComponent< React.SVGProps >; } declare module '*.svg?react' { const ReactComponent: React.FunctionComponent>; export default ReactComponent; } * 如果 `svgrOptions.exportType` 的值为 `'named'`,且开启了 `mixedImport`,则将类型声明设置为: declare module '*.svg' { export const ReactComponent: React.FunctionComponent< React.SVGProps >; const content: string; export default content; } declare module '*.svg?react' { const ReactComponent: React.FunctionComponent>; export default ReactComponent; } 添加类型声明后,如果依然存在上述错误提示,请尝试重启当前 IDE,或者调整 `env.d.ts` 所在的目录,使 TypeScript 能够正确识别类型定义。 --- # 插件开发 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/dev/index.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/dev/#%E6%8F%92%E4%BB%B6%E5%BC%80%E5%8F%91) 插件开发 ================================================================================= 复制 Markdown 插件系统是 Rsbuild 架构的核心,Rsbuild 的大部分功能都是通过插件实现的,这种设计让核心保持轻量,同时提供了灵活的扩展性。 Rsbuild 插件是一个函数,它可以在不同阶段注册钩子,监听事件并执行自定义逻辑。无论你想要修改默认行为、添加新功能,还是集成第三方工具,插件都提供了丰富的 API 来实现这些需求。 [#](https://rsbuild.rs/zh/plugins/dev/#%E5%AF%B9%E6%AF%94%E5%85%B6%E4%BB%96%E6%8F%92%E4%BB%B6) 对比其他插件 ----------------------------------------------------------------------------------------------------- 在开发 Rsbuild 插件之前,你可能已经接触过 webpack、Vite、esbuild 等工具的插件系统。 总体而言,Rsbuild 的插件 API 和 esbuild 相似,与 webpack 或 Rspack 插件相比,Rsbuild 的插件 API 更加简洁和容易上手。 // esbuild plugin const esbuildPlugin = { name: 'example', setup(build) { build.onEnd(() => console.log('done')); }, }; // Rsbuild plugin const rsbuildPlugin = () => ({ name: 'example', setup(api) { api.onAfterBuild(() => console.log('done')); }, }); // Rspack plugin class RspackExamplePlugin { apply(compiler) { compiler.hooks.done.tap('RspackExamplePlugin', () => { console.log('done'); }); } } 从功能上看,Rsbuild 的插件 API 主要围绕 Rsbuild 的运行流程和构建配置,并提供一些 hooks 用于扩展。而 Rspack 的插件 API 则更加复杂和丰富,能够修改打包过程的每一个环节。 Rsbuild 插件中可以集成 Rspack 插件,如果 Rsbuild 提供的 hooks 无法满足你的需求,你也可以通过 Rspack 插件来实现功能,并在 Rsbuild 插件中注册 Rspack 插件: const rsbuildPlugin = () => ({ name: 'example', setup(api) { api.modifyRspackConfig((config) => { config.plugins.push(new RspackExamplePlugin()); }); }, }); [#](https://rsbuild.rs/zh/plugins/dev/#%E5%BC%80%E5%8F%91%E6%8F%92%E4%BB%B6) 开发插件 --------------------------------------------------------------------------------- 插件提供类似 `(options?: PluginOptions) => RsbuildPlugin` 的函数作为入口。 ### [#](https://rsbuild.rs/zh/plugins/dev/#%E6%8F%92%E4%BB%B6%E7%A4%BA%E4%BE%8B) 插件示例 pluginFoo.ts import type { RsbuildPlugin } from '@rsbuild/core'; export type PluginFooOptions = { message?: string; }; export const pluginFoo = (options: PluginFooOptions = {}): RsbuildPlugin => ({ name: 'plugin-foo', setup(api) { api.onAfterStartDevServer(() => { const msg = options.message || 'hello!'; console.log(msg); }); }, }); 注册插件: rsbuild.config.ts import { pluginFoo } from './pluginFoo'; export default { plugins: [pluginFoo({ message: 'world!' })], }; ### [#](https://rsbuild.rs/zh/plugins/dev/#%E6%8F%92%E4%BB%B6%E7%BB%93%E6%9E%84) 插件结构 函数形式的插件可以 **接受选项对象** 并 **返回插件实例**,并通过闭包机制管理内部状态。 其中各部分的作用分别为: * `name` 属性用于标注插件名称。 * `setup` 作为插件逻辑的主入口。 * `api` 对象包含了各类钩子和工具函数。 ### [#](https://rsbuild.rs/zh/plugins/dev/#%E5%91%BD%E5%90%8D%E8%A7%84%E8%8C%83) 命名规范 插件的命名规范如下: * 插件的函数命名为 `pluginAbc`,并通过具名导出。 * 插件的 `name` 采用 `scope:foo-bar` 或 `plugin-foo-bar` 格式,添加 `scope:` 可以避免和其他插件产生命名冲突。 下面是一个例子: pluginFooBar.ts import type { RsbuildPlugin } from '@rsbuild/core'; export const pluginFooBar = (): RsbuildPlugin => ({ name: 'scope:foo-bar', setup() {}, }); Tip Rsbuild 官方插件的 `name` 统一使用 `rsbuild:` 作为前缀,比如 `rsbuild:react` 对应 `@rsbuild/plugin-react`。 ### [#](https://rsbuild.rs/zh/plugins/dev/#%E6%A8%A1%E6%9D%BF%E4%BB%93%E5%BA%93) 模板仓库 [rsbuild-plugin-template](https://github.com/rstackjs/rsbuild-plugin-template) 是一个最小的 Rsbuild 插件模板仓库,你可以基于该仓库来开发你的 Rsbuild 插件。 ### [#](https://rsbuild.rs/zh/plugins/dev/#environment-plugin) Environment 插件 Rsbuild 支持同时为多个环境构建产物,并支持某个插件[仅在指定环境下运行](https://rsbuild.rs/zh/guide/advanced/environments#plugins-specified-environment) 。 当你希望你开发的插件支持作为 Environment 插件使用时,需要注意以下几点: 1. 每个 environment 有自身的 Rsbuild 配置: * 使用 [environment 上下文](https://rsbuild.rs/zh/guide/advanced/environments#environment-context) 代替 `getRsbuildConfig` 获取 environment 信息。 * 修改特定 environment 的 Rsbuild 配置时,优先使用 [modifyEnvironmentConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyenvironmentconfig) 代替 [modifyRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) ,以避免对其他 environments 产生影响。 2. 避免副作用,你的插件代码可能执行多次: * 当同一个插件在不同环境下注册多次时,会被视为多个 Rsbuild 插件(哪怕它们指向同一个插件实例),这是因为它们带有不同的 Rsbuild environment 上下文。 下面是一个 Environment 插件例子: pluginFoo.ts import type { RsbuildPlugin } from '@rsbuild/core'; export type PluginFooOptions = { title?: string; }; export const pluginFoo = (options: PluginFooOptions = {}): RsbuildPlugin => ({ name: 'plugin-foo', setup(api) { api.modifyEnvironmentConfig((config) => { config.html.title = options.title || 'My Default Title'; }); api.modifyBundlerChain((chain, { environment }) => { chain.name(environment.config.html.title); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/#%E5%BC%95%E7%94%A8%E5%85%B6%E4%BB%96%E6%8F%92%E4%BB%B6) 引用其他插件 Rsbuild 的 [plugins](https://rsbuild.rs/zh/config/plugins) 配置项支持传入一个嵌套的数组,这意味着你可以通过这种方式在插件内部引用其他 Rsbuild 插件。 例如,在 `pluginFoo` 内部引用并注册 `pluginBar`: import { pluginBar } from 'rsbuild-plugin-bar'; export const pluginFoo = (): RsbuildPlugin => { const foo = { name: 'plugin-foo', setup(api) { // ... }, }; return [foo, pluginBar()]; }; [#](https://rsbuild.rs/zh/plugins/dev/#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90) 生命周期钩子 ----------------------------------------------------------------------------------------------------- Rsbuild 在内部按照约定的生命周期进行任务调度,插件可以通过注册钩子来介入工作流程的任意阶段,并实现自己的功能。 Rsbuild 生命周期钩子的完整列表参考 [API 文档](https://rsbuild.rs/zh/plugins/dev/hooks) 。 Rsbuild 不会接管底层 Rspack 的生命周期,相关生命周期钩子的使用方式见对应文档:[Rspack Plugin API](https://rspack.rs/zh/api/plugin-api) 。 [#](https://rsbuild.rs/zh/plugins/dev/#%E8%BF%81%E7%A7%BB-vite-%E6%8F%92%E4%BB%B6) 迁移 Vite 插件 --------------------------------------------------------------------------------------------- 参考 [迁移 Vite 插件](https://rsbuild.rs/zh/guide/migration/vite-plugin) 了解如何迁移一个 Vite 插件到 Rsbuild 插件。 [#](https://rsbuild.rs/zh/plugins/dev/#read-and-modify-rsbuild-config) 读写 Rsbuild 配置 ------------------------------------------------------------------------------------ 当插件需要读取或修改项目的 Rsbuild 配置时,可以使用 Rsbuild 提供的配置 API。 ### [#](https://rsbuild.rs/zh/plugins/dev/#modify-the-base-config) 修改基础配置 在 `setup` 中注册 [api.modifyRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) ,可以在基础配置与各个 environment 的配置合并前对其进行修改: api.modifyRsbuildConfig((config) => { config.output.minify = false; }); `modifyRsbuildConfig` 是全局 hook。如果修改仅针对部分 environment,或需要根据当前 environment 调整配置,建议改用 [api.modifyEnvironmentConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyenvironmentconfig) 。详细说明请参考[全局 hooks 与 environment hooks](https://rsbuild.rs/zh/plugins/dev/hooks#global-hooks-vs-environment-hooks) 。 ### [#](https://rsbuild.rs/zh/plugins/dev/#read-the-normalized-config) 读取规范化后的配置 配置修改 hooks 执行完毕后,可以无参数调用 [api.getNormalizedConfig](https://rsbuild.rs/zh/plugins/dev/core#apigetnormalizedconfig) ,获取包含所有 environment 的完整配置。该配置已经过规范化处理并包含默认值,类型也比 [api.getRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/core#apigetrsbuildconfig) 的返回值更明确。 api.onBeforeBuild(() => { const config = api.getNormalizedConfig(); console.log(Object.keys(config.environments)); }); 如果当前没有 environment context,但需要读取某个 environment 的配置,可以将其名称传给 `getNormalizedConfig`: api.onBeforeBuild(() => { const config = api.getNormalizedConfig({ environment: 'web' }); console.log(config.output.target); }); 返回值类型请参考 [NormalizedConfig](https://rsbuild.rs/zh/api/javascript-api/types#normalizedconfig) 和 [NormalizedEnvironmentConfig](https://rsbuild.rs/zh/api/javascript-api/types#normalizedenvironmentconfig) 。 ### [#](https://rsbuild.rs/zh/plugins/dev/#current-environment-config) 读取当前环境的配置 当 hook 的回调参数中包含 [environment context](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-context) 时,建议通过 `environment.config` 获取配置。该配置由基础配置与[当前 environment 的配置](https://rsbuild.rs/zh/guide/advanced/environments) 合并并经过规范化处理后得到。 api.onBeforeEnvironmentCompile(({ environment }) => { const { name, config } = environment; console.log(`${name}: ${config.output.target}`); }); ### [#](https://rsbuild.rs/zh/plugins/dev/#read-all-environment-configs) 读取所有环境的配置 [onBeforeBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforebuild) 和 [onAfterBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onafterbuild) 等全局 hooks 会提供 `environments`,其中包含所有 environment 的上下文。当插件需要读取每个 environment 的配置时,可以遍历该对象: api.onBeforeBuild(({ environments }) => { for (const { name, config } of Object.values(environments)) { console.log(`${name}: ${config.output.distPath.root}`); } }); 多环境配置的详细说明请参考[多环境构建](https://rsbuild.rs/zh/guide/advanced/environments) 。 [#](https://rsbuild.rs/zh/plugins/dev/#%E4%BF%AE%E6%94%B9-rspack-%E9%85%8D%E7%BD%AE) 修改 Rspack 配置 ------------------------------------------------------------------------------------------------- Rsbuild 插件允许你修改内置的 Rspack 配置,包括: * [api.modifyRspackConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrspackconfig) :修改 Rspack 配置对象。 * [api.modifyBundlerChain](https://rsbuild.rs/zh/plugins/dev/hooks#modifybundlerchain) 通过 [rspack-chain](https://github.com/rstackjs/rspack-chain) 来修改 Rspack 配置。 ### [#](https://rsbuild.rs/zh/plugins/dev/#%E7%A4%BA%E4%BE%8B) 示例 比如,通过 Rsbuild 插件来注册 [eslint-rspack-plugin](https://github.com/rstackjs/eslint-rspack-plugin) : import type { RsbuildPlugin } from '@rsbuild/core'; import ESLintRspackPlugin from 'eslint-rspack-plugin'; export const pluginEslint = (options?: Options): RsbuildPlugin => ({ name: 'plugin-eslint', setup(api) { api.modifyRspackConfig((config) => { config.plugins.push( new ESLintRspackPlugin({ // plugins options }), ); }); }, }); [#](https://rsbuild.rs/zh/plugins/dev/#%E6%89%A9%E5%B1%95%E6%8F%92%E4%BB%B6-api) 扩展插件 API ----------------------------------------------------------------------------------------- 当你基于 Rsbuild 的 [JavaScript API](https://rsbuild.rs/zh/api/start/) 来实现自定义的工具时,可能希望在现有插件 API 的基础上,提供更多能力,例如添加工具方法或共享上下文对象。 此时,你可以使用 Rsbuild 实例上的 [rsbuild.expose()](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildexpose) 方法。它的作用与插件的 [api.expose()](https://rsbuild.rs/zh/plugins/dev/core#apiexpose) 一致,用于向 Rsbuild 插件暴露自定义的方法或对象。 例如,向插件暴露 `getState` 和 `setCount` 方法: myToolkit.ts import { createRsbuild } from '@rsbuild/core'; export const MY_TOOLKIT_ID = 'my-toolkit'; const rsbuild = await createRsbuild({ // ... }); const state = { count: 0, }; rsbuild.expose(MY_TOOLKIT_ID, { getState() { return state; }, setCount(count: number) { state.count = count; }, }); 然后,插件可以通过 [api.useExposed()](https://rsbuild.rs/zh/plugins/dev/core#apiuseexposed) 方法访问这些扩展 API: myPlugin.ts import { MY_TOOLKIT_ID } from './myToolkit'; const myPlugin = { name: 'my-plugin', setup(api) { const toolkitApi = api.useExposed(MY_TOOLKIT_ID); if (toolkitApi) { const { count } = toolkitApi.getState(); toolkitApi.setCount(count + 1); } }, }; [#](https://rsbuild.rs/zh/plugins/dev/#%E4%BE%9D%E8%B5%96%E5%A3%B0%E6%98%8E) 依赖声明 --------------------------------------------------------------------------------- 发布 Rsbuild 插件时,应该在 `package.json` 中声明 `@rsbuild/core` 的 `peerDependencies`,并在 `devDependencies` 中安装它用于开发: { "peerDependencies": { "@rsbuild/core": "^2.0.0" }, "devDependencies": { "@rsbuild/core": "^2.0.0" } } 如果插件只引用了 `@rsbuild/core` 的类型导出,可以将其声明为 optional peer dependency: { "peerDependencies": { "@rsbuild/core": "^2.0.0" }, "peerDependenciesMeta": { "@rsbuild/core": { "optional": true } } } 这种情况下,插件在被基于 Rsbuild 的上层工具(如 Rslib 或 Rspress)使用时,不会产生不必要的 peer dependency 警告。 --- # Plugin hooks - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /plugins/dev/hooks.md. MenuON THIS PAGE [#](https://rsbuild.rs/plugins/dev/hooks#plugin-hooks) Plugin hooks =================================================================== Copy Markdown This page outlines the plugin hooks available for Rsbuild plugins. [#](https://rsbuild.rs/plugins/dev/hooks#overview) Overview ----------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/dev/hooks#common-hooks) Common hooks * [modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) : Modify the configuration passed to Rsbuild. * [modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) : Modify the Rsbuild configuration of a specific environment. * [modifyRspackConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrspackconfig) : Modify the configuration passed to Rspack. * [modifyBundlerChain](https://rsbuild.rs/plugins/dev/hooks#modifybundlerchain) : Modify the configuration of Rspack through the chain API. * [modifyHTMLTags](https://rsbuild.rs/plugins/dev/hooks#modifyhtmltags) : Modify the tags that are injected into the HTML. * [modifyHTML](https://rsbuild.rs/plugins/dev/hooks#modifyhtml) : Modify the final HTML content. * [onBeforeCreateCompiler](https://rsbuild.rs/plugins/dev/hooks#onbeforecreatecompiler) : Called before creating a compiler instance. * [onAfterCreateCompiler](https://rsbuild.rs/plugins/dev/hooks#onaftercreatecompiler) : Called after creating a compiler instance and before building. * [onBeforeEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforeenvironmentcompile) : Called before the compilation of a single environment. * [onAfterEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onafterenvironmentcompile) : Called after the compilation of a single environment. You can get the build result information. * [onRestart](https://rsbuild.rs/plugins/dev/hooks#onrestart) : Called when a restart is requested for the dev server or watch build. * [onExit](https://rsbuild.rs/plugins/dev/hooks#onexit) : Called when the process is about to exit. ### [#](https://rsbuild.rs/plugins/dev/hooks#dev-hooks) Dev hooks Called when running the `rsbuild dev` command or the `rsbuild.startDevServer()` method: * [onBeforeStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartdevserver) : Called before starting the dev server. * [onAfterStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onafterstartdevserver) : Called after starting the dev server. * [onBeforeDevCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforedevcompile) : Called before each build in development mode. * [onAfterDevCompile](https://rsbuild.rs/plugins/dev/hooks#onafterdevcompile) : Called after each build in development mode. * [onCloseDevServer](https://rsbuild.rs/plugins/dev/hooks#onclosedevserver) : Called when the dev server is closed. ### [#](https://rsbuild.rs/plugins/dev/hooks#build-hooks) Build hooks Called when running the `rsbuild build` command or the `rsbuild.build()` method: * [onBeforeBuild](https://rsbuild.rs/plugins/dev/hooks#onbeforebuild) : Called before running the production build. * [onAfterBuild](https://rsbuild.rs/plugins/dev/hooks#onafterbuild) : Called after running the production build. You can get the build result information. * [onCloseBuild](https://rsbuild.rs/plugins/dev/hooks#onclosebuild) : Called when the build is closed. ### [#](https://rsbuild.rs/plugins/dev/hooks#preview-hooks) Preview hooks Called when running the `rsbuild preview` command or the `rsbuild.preview()` method: * [onBeforeStartPreviewServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartpreviewserver) : Called before starting the preview server. * [onAfterStartPreviewServer](https://rsbuild.rs/plugins/dev/hooks#onafterstartpreviewserver) : Called after starting the preview server. [#](https://rsbuild.rs/plugins/dev/hooks#hooks-order) Hooks order ----------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/dev/hooks#dev-hooks-1) Dev hooks When the `rsbuild dev` command or `rsbuild.startDevServer()` method is executed, Rsbuild will execute the following hooks in order: * [modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) * [modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) * [onBeforeStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartdevserver) * [modifyBundlerChain](https://rsbuild.rs/plugins/dev/hooks#modifybundlerchain) * [modifyRspackConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrspackconfig) * [onBeforeCreateCompiler](https://rsbuild.rs/plugins/dev/hooks#onbeforecreatecompiler) * [onAfterCreateCompiler](https://rsbuild.rs/plugins/dev/hooks#onaftercreatecompiler) * [onBeforeDevCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforedevcompile) * [onBeforeEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforeenvironmentcompile) * [onAfterStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onafterstartdevserver) * [modifyHTMLTags](https://rsbuild.rs/plugins/dev/hooks#modifyhtmltags) * [modifyHTML](https://rsbuild.rs/plugins/dev/hooks#modifyhtml) * [onAfterEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onafterenvironmentcompile) * [onAfterDevCompile](https://rsbuild.rs/plugins/dev/hooks#onafterdevcompile) * [onCloseDevServer](https://rsbuild.rs/plugins/dev/hooks#onclosedevserver) * [onExit](https://rsbuild.rs/plugins/dev/hooks#onexit) When rebuilding, the following hooks will be triggered again: * [onBeforeDevCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforedevcompile) * [onBeforeEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforeenvironmentcompile) * [modifyHTMLTags](https://rsbuild.rs/plugins/dev/hooks#modifyhtmltags) * [modifyHTML](https://rsbuild.rs/plugins/dev/hooks#modifyhtml) * [onAfterEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onafterenvironmentcompile) * [onAfterDevCompile](https://rsbuild.rs/plugins/dev/hooks#onafterdevcompile) ### [#](https://rsbuild.rs/plugins/dev/hooks#build-hooks-1) Build hooks When the `rsbuild build` command or `rsbuild.build()` method is executed, Rsbuild will execute the following hooks in order: * [modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) * [modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) * [modifyBundlerChain](https://rsbuild.rs/plugins/dev/hooks#modifybundlerchain) * [modifyRspackConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrspackconfig) * [onBeforeCreateCompiler](https://rsbuild.rs/plugins/dev/hooks#onbeforecreatecompiler) * [onAfterCreateCompiler](https://rsbuild.rs/plugins/dev/hooks#onaftercreatecompiler) * [onBeforeBuild](https://rsbuild.rs/plugins/dev/hooks#onbeforebuild) * [onBeforeEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforeenvironmentcompile) * [modifyHTMLTags](https://rsbuild.rs/plugins/dev/hooks#modifyhtmltags) * [modifyHTML](https://rsbuild.rs/plugins/dev/hooks#modifyhtml) * [onAfterEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onafterenvironmentcompile) * [onAfterBuild](https://rsbuild.rs/plugins/dev/hooks#onafterbuild) * [onCloseBuild](https://rsbuild.rs/plugins/dev/hooks#onclosebuild) * [onExit](https://rsbuild.rs/plugins/dev/hooks#onexit) When rebuilding, the following hooks will be triggered again: * [onBeforeBuild](https://rsbuild.rs/plugins/dev/hooks#onbeforebuild) * [onBeforeEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforeenvironmentcompile) * [modifyHTMLTags](https://rsbuild.rs/plugins/dev/hooks#modifyhtmltags) * [modifyHTML](https://rsbuild.rs/plugins/dev/hooks#modifyhtml) * [onAfterEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onafterenvironmentcompile) * [onAfterBuild](https://rsbuild.rs/plugins/dev/hooks#onafterbuild) ### [#](https://rsbuild.rs/plugins/dev/hooks#preview-hooks-1) Preview hooks When executing the `rsbuild preview` command or `rsbuild.preview()` method, Rsbuild will execute the following hooks in order: * [modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) * [modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) * [onBeforeStartPreviewServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartpreviewserver) * [onAfterStartPreviewServer](https://rsbuild.rs/plugins/dev/hooks#onafterstartpreviewserver) * [onExit](https://rsbuild.rs/plugins/dev/hooks#onexit) [#](https://rsbuild.rs/plugins/dev/hooks#global-hooks-vs-environment-hooks) Global hooks vs environment hooks ------------------------------------------------------------------------------------------------------------- In Rsbuild, some plugin hooks are global. These hooks relate to Rsbuild's startup process or other shared logic and run across all environments. For example: * `modifyRsbuildConfig` is used to modify the basic configuration of Rsbuild. The basic configuration will eventually be merged with the environment configuration; * `onBeforeStartDevServer` and `onAfterStartDevServer` are related to the Rsbuild dev server startup process, all environments share Rsbuild's dev server, middleware, and WebSocket. Correspondingly, there are some plugin hooks that are related to the current environment. These hooks are executed with a specific environment context and are triggered multiple times depending on the environment. ### [#](https://rsbuild.rs/plugins/dev/hooks#global-hooks) Global hooks * [modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) * [onBeforeStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartdevserver) * [onBeforeCreateCompiler](https://rsbuild.rs/plugins/dev/hooks#onbeforecreatecompiler) * [onAfterCreateCompiler](https://rsbuild.rs/plugins/dev/hooks#onaftercreatecompiler) * [onAfterStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onafterstartdevserver) * [onBeforeDevCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforedevcompile) * [onAfterDevCompile](https://rsbuild.rs/plugins/dev/hooks#onafterdevcompile) * [onCloseDevServer](https://rsbuild.rs/plugins/dev/hooks#onclosedevserver) * [onBeforeBuild](https://rsbuild.rs/plugins/dev/hooks#onbeforebuild) * [onAfterBuild](https://rsbuild.rs/plugins/dev/hooks#onafterbuild) * [onCloseBuild](https://rsbuild.rs/plugins/dev/hooks#onclosebuild) * [onBeforeStartPreviewServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartpreviewserver) * [onAfterStartPreviewServer](https://rsbuild.rs/plugins/dev/hooks#onafterstartpreviewserver) * [onRestart](https://rsbuild.rs/plugins/dev/hooks#onrestart) * [onExit](https://rsbuild.rs/plugins/dev/hooks#onexit) ### [#](https://rsbuild.rs/plugins/dev/hooks#environment-hooks) Environment hooks * [modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) * [modifyBundlerChain](https://rsbuild.rs/plugins/dev/hooks#modifybundlerchain) * [modifyRspackConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrspackconfig) * [modifyHTMLTags](https://rsbuild.rs/plugins/dev/hooks#modifyhtmltags) * [modifyHTML](https://rsbuild.rs/plugins/dev/hooks#modifyhtml) * [onBeforeEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onbeforeenvironmentcompile) * [onAfterEnvironmentCompile](https://rsbuild.rs/plugins/dev/hooks#onafterenvironmentcompile) [#](https://rsbuild.rs/plugins/dev/hooks#callback-order) Callback order ----------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/dev/hooks#default-behavior) 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]); ### [#](https://rsbuild.rs/plugins/dev/hooks#order-field) `order` Field When registering a hook, you can declare the order of hook through the `order` field. type HookDescriptor 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]); [#](https://rsbuild.rs/plugins/dev/hooks#common-hooks-1) Common hooks --------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) 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. Warning `modifyRsbuildConfig` is a global hook. To add support for your plugin as an [environment-specific plugin](https://rsbuild.rs/guide/advanced/environments#plugins-specified-environment) , you should use [modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) instead of `modifyRsbuildConfig`. * **Type:** type ModifyRsbuildConfigUtils = { mergeRsbuildConfig: typeof mergeRsbuildConfig; }; function ModifyRsbuildConfig( callback: ( config: RsbuildConfig, utils: ModifyRsbuildConfigUtils, ) => MaybePromise, ): 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); }); }, }); Tip `modifyRsbuildConfig` cannot be used to register additional Rsbuild plugins. This is because at the time `modifyRsbuildConfig` is executed, Rsbuild has already initialized all plugins and started executing the callbacks of the hooks. For details, please refer to [Plugin registration phase](https://rsbuild.rs/config/plugins#plugin-registration-phase) . ### [#](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) modifyEnvironmentConfig Modify the Rsbuild configuration of a specific environment. In the callback function, the config object in the parameters has already been merged with the common Rsbuild configuration. You can directly modify this config object, or you can return a new object to replace it. * **Type:** type ArrayAtLeastOne = [A, ...Array] | [...Array, A]; type ModifyEnvironmentConfigUtils = { /** Current environment name */ name: string; mergeEnvironmentConfig: ( ...configs: ArrayAtLeastOne ) => MergedEnvironmentConfig; }; function ModifyEnvironmentConfig( callback: ( config: MergedEnvironmentConfig, utils: ModifyEnvironmentConfigUtils, ) => MaybePromise, ): void; * **Example:** Set a default value for the Rsbuild config of a specified environment: const myPlugin = () => ({ setup(api) { api.modifyEnvironmentConfig((config, { name }) => { if (name !== 'web') { return config; } config.html.title = 'My Default Title'; }); }, }); * **Example:** Using `mergeEnvironmentConfig` to merge config objects, and return the merged object. import type { EnvironmentConfig } from '@rsbuild/core'; const myPlugin = () => ({ setup(api) { api.modifyEnvironmentConfig((userConfig, { mergeEnvironmentConfig }) => { const extraConfig: EnvironmentConfig = { source: { // ... }, output: { // ... }, }; // extraConfig will override fields in userConfig, // If you do not want to override the fields in userConfig, // you can adjust to `mergeEnvironmentConfig(extraConfig, userConfig)` return mergeEnvironmentConfig(userConfig, extraConfig); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#modifyrspackconfig) modifyRspackConfig To modify the Rspack config, you can directly modify the config object, or return a new object to replace the previous object. Tip `modifyRspackConfig` is executed earlier than [tools.rspack](https://rsbuild.rs/config/tools/rspack) . Therefore, the modifications made by `tools.rspack` cannot be obtained in `modifyRspackConfig`. * **Type:** type ModifyRspackConfigUtils = { environment: EnvironmentContext; environments: Record; env: string; isDev: boolean; isProd: boolean; target: RsbuildTarget; isServer: boolean; isWebWorker: boolean; CHAIN_ID: ChainIdentifier; rspack: typeof import('@rspack/core').rspack; HtmlPlugin: typeof import('html-rspack-plugin'); // more... }; function ModifyRspackConfig( callback: ( config: Rspack.Configuration, utils: ModifyRspackConfigUtils, ) => MaybePromise, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.modifyRspackConfig((config, utils) => { if (utils.env === 'development') { config.devtool = 'eval-cheap-source-map'; } }); }, }); The second parameter `utils` of the callback function is an object, which contains some utility functions and properties, see [tools.rspack - Utils](https://rsbuild.rs/config/tools/rspack#utils) for more details. ### [#](https://rsbuild.rs/plugins/dev/hooks#modifybundlerchain) modifyBundlerChain [rspack-chain](https://github.com/rstackjs/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` allows you to modify the Rspack configuration using the `rspack-chain` API, providing the same functionality as [tools.bundlerChain](https://rsbuild.rs/config/tools/bundler-chain) . * **Type:** type ModifyBundlerChainUtils = { environment: EnvironmentContext; environments: Record; env: string; isDev: boolean; isProd: boolean; target: RsbuildTarget; isServer: boolean; isWebWorker: boolean; CHAIN_ID: ChainIdentifier; rspack: typeof import('@rspack/core').rspack; HtmlPlugin: typeof import('html-rspack-plugin'); /** @deprecated Use `rspack` instead. */ bundler: typeof import('@rspack/core').rspack; }; function ModifyBundlerChain( callback: ( chain: RspackChain, utils: ModifyBundlerChainUtils, ) => Promise | void, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.modifyBundlerChain((chain, utils) => { if (utils.env === 'development') { chain.devtool('eval'); } chain .plugin('circular-dependency') .use(utils.rspack.CircularDependencyRspackPlugin); }); }, }); The second parameter `utils` of the callback function is an object, which contains some utility functions and properties, see [tools.bundlerChain - Utils](https://rsbuild.rs/config/tools/bundler-chain#utils) for more details. ### [#](https://rsbuild.rs/plugins/dev/hooks#modifyhtml) modifyHTML Modify the final HTML content. The hook receives an HTML string and a context object, and you can return a new HTML string to replace the original one. This hook is triggered after the `modifyHTMLTags` hook. * **Type:** type Context = { /** * The Compiler object of Rspack. */ compiler: Rspack.Compiler; /** * The Compilation object of Rspack. */ compilation: Rspack.Compilation; /** * The name of the HTML file, relative to the dist directory. * @example 'index.html' */ filename: string; /** * The environment context for current build. */ environment: EnvironmentContext; }; function ModifyHTML( callback: (html: string, context: Context) => MaybePromise, ): void; * **Version:** Added in v1.3.15 * **Example:** const myPlugin = () => ({ setup(api) { api.modifyHTML((html) => { return html.replace('foo', 'bar'); }); }, }); Modify HTML content based on `filename`: const myPlugin = () => ({ setup(api) { api.modifyHTML((html, { filename }) => { if (filename === 'foo.html') { return html.replace('foo', 'bar'); } return html; }); }, }); Instead of directly manipulating the HTML string, you can use [cheerio](https://github.com/cheeriojs/cheerio) or [htmlparser2](https://github.com/fb55/htmlparser2) to modify the HTML content more conveniently. For example, `cheerio` provides a jQuery-like API for HTML manipulation: import cheerio from 'cheerio'; const myPlugin = () => ({ setup(api) { api.modifyHTML((html) => { const $ = cheerio.load(html); $('h2.title').text('Hello there!'); $('h2').addClass('welcome'); return $.html(); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#modifyhtmltags) modifyHTMLTags Modify the tags that are injected into the HTML. * **Type:** type HtmlBasicTag = { // Tag name tag: string; // Attributes of the tag attrs?: Record; // innerHTML of the tag children?: string; // additional metadata metadata?: Record; }; type HTMLTags = { // Tags group inserted into headTags: HtmlBasicTag[]; // Tags group inserted into bodyTags: HtmlBasicTag[]; }; type Context = { /** * The Compiler object of Rspack. */ compiler: Rspack.Compiler; /** * 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; /** * The environment context for current build. */ environment: EnvironmentContext; }; function ModifyHTMLTags( callback: (tags: HTMLTags, context: Context) => MaybePromise, ): void; * **Example:** const tagsPlugin = () => ({ name: 'tags-plugin', setup(api) { api.modifyHTMLTags(({ headTags, bodyTags }) => { // Inject a tag into , before other tags headTags.unshift({ tag: 'script', attrs: { src: 'https://example.com/foo.js' }, }); // Inject a tag into , after other tags headTags.push({ tag: 'script', attrs: { src: 'https://example.com/bar.js' }, }); // Inject a tag into , before other tags bodyTags.unshift({ tag: 'div', children: 'before other body tags', }); // Inject a tag into , after other tags bodyTags.push({ tag: 'div', children: 'after other body tags', }); return { headTags, bodyTags }; }); }, }); See [html.tags](https://rsbuild.rs/config/html/tags) for more details on how to define tags. Tip When using `modifyHTML`, `modifyHTMLTags`, and `html.tags` options together, the execution order is as follows: 1. [modifyHTMLTags](https://rsbuild.rs/plugins/dev/hooks#modifyhtmltags) 2. [html.tags](https://rsbuild.rs/config/html/tags) 3. [modifyHTML](https://rsbuild.rs/plugins/dev/hooks#modifyhtml) ### [#](https://rsbuild.rs/plugins/dev/hooks#onbeforecreatecompiler) onBeforeCreateCompiler A callback function that is triggered before the Rspack Compiler instance is created. 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](https://rspack.rs/config/) . It depends on whether multiple [environments](https://rsbuild.rs/config/environments) are configured. * **Type:** function OnBeforeCreateCompiler( callback: (params: { bundlerConfigs: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onBeforeCreateCompiler(({ bundlerConfigs }) => { console.log('the bundler configs are ', bundlerConfigs); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onaftercreatecompiler) onAfterCreateCompiler A callback function that is triggered after the Rspack 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](https://rspack.rs/api/javascript-api/compiler) through the `compiler` parameter: * **Type:** function OnAfterCreateCompiler( callback: (params: { compiler: Compiler | MultiCompiler; environments: Record; }) => Promise | void, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onAfterCreateCompiler(({ compiler }) => { console.log('the compiler is ', compiler); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onbeforeenvironmentcompile) onBeforeEnvironmentCompile A callback function that is triggered before the compilation of a single environment. You can access the [Rspack configuration](https://rspack.rs/config/) for the current environment through the `bundlerConfig` parameter. Moreover, you can use `isWatch` to determine whether it is dev or build watch mode, and use `isFirstCompile` to determine whether it is the first build in watch mode. * **Type:** function OnBeforeEnvironmentCompile( callback: (params: { isWatch: boolean; isFirstCompile: boolean; bundlerConfig?: Rspack.Configuration; environment: EnvironmentContext; }) => Promise | void, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onBeforeEnvironmentCompile(({ bundlerConfig, environment }) => { console.log( `the bundler config for the ${environment.name} is `, bundlerConfig, ); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onafterenvironmentcompile) onAfterEnvironmentCompile A callback function that is triggered after the compilation of a single environment. You can access the build result information via the [stats](https://rspack.rs/api/javascript-api/stats) parameter. Moreover, you can use `isWatch` to determine whether it is dev or build watch mode, and use `isFirstCompile` to determine whether it is the first build. * **Type:** function OnAfterEnvironmentCompile( callback: (params: { isFirstCompile: boolean; isWatch: boolean; stats?: Stats; environment: EnvironmentContext; /** * The time it takes to build the current environment in milliseconds. */ time: number; }) => Promise | void, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onAfterEnvironmentCompile(({ isFirstCompile, stats }) => { console.log(stats?.toJson(), isFirstCompile); }); }, }); [#](https://rsbuild.rs/plugins/dev/hooks#build-hooks-2) Build hooks ------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/dev/hooks#onbeforebuild) onBeforeBuild 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](https://rspack.rs/config/) . It depends on whether multiple [environments](https://rsbuild.rs/config/environments) are configured. Moreover, you can use `isWatch` to determine whether it is watch mode, and use `isFirstCompile` to determine whether it is the first build on watch mode. * **Type:** function OnBeforeBuild( callback: (params: { isWatch: boolean; isFirstCompile: boolean; bundlerConfigs?: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onBeforeBuild(({ bundlerConfigs }) => { console.log('the bundler configs are ', bundlerConfigs); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onafterbuild) onAfterBuild A callback function that is triggered after running the production build. You can access the build result information via the [stats](https://rspack.rs/api/javascript-api/stats) parameter. Moreover, you can use `isWatch` to determine whether it is watch mode, and use `isFirstCompile` to determine whether it is the first build on watch mode. * **Type:** function OnAfterBuild( callback: (params: { isFirstCompile: boolean; isWatch: boolean; stats?: Stats | MultiStats; environments: Record; }) => Promise | void, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onAfterBuild(({ isFirstCompile, stats }) => { console.log(stats?.toJson(), isFirstCompile); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onclosebuild) onCloseBuild Called when closing the build instance. Can be used to perform cleanup operations when the building is closed. Rsbuild CLI will automatically call this hook after running [rsbuild build](https://rsbuild.rs/guide/basic/cli#rsbuild-build) , while users of the JavaScript API need to manually call the [build.close()](https://rsbuild.rs/api/javascript-api/instance#close-build) method to trigger this hook. * **Type:** function onCloseBuild(callback: () => Promise | void): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onCloseBuild(() => { console.log('close build!'); }); }, }); [#](https://rsbuild.rs/plugins/dev/hooks#dev-hooks-2) Dev hooks --------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/dev/hooks#onbeforestartdevserver) onBeforeStartDevServer Called before starting the dev server. Use the `server` parameter to get the dev server instance, see [Server API](https://rsbuild.rs/api/javascript-api/server-api) for more information. * **Type:** type MaybePromise = T | Promise; type OnBeforeStartDevServerFn = (params: { /** * The dev server instance, the same as the return value of `createDevServer`. */ server: RsbuildDevServer; /** * Context information for all environments. */ environments: Record; }) => MaybePromise<(() => MaybePromise) | void>; function OnBeforeStartDevServer(callback: OnBeforeStartDevServerFn): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onBeforeStartDevServer(({ server, environments }) => { console.log('before starting dev server.'); console.log('the server is ', server); console.log('the environments contexts are: ', environments); }); }, }); #### [#](https://rsbuild.rs/plugins/dev/hooks#register-middleware) Register middleware A common usage scenario is to register custom middleware in `onBeforeStartDevServer`: const myPlugin = () => ({ setup(api) { api.onBeforeStartDevServer(({ server }) => { server.middlewares.use((req, res, next) => { next(); }); }); }, }); When `onBeforeStartDevServer` is called, the default Rsbuild middlewares are not registered yet, so the middleware you add will run before the default middlewares. `onBeforeStartDevServer` allows you to return a callback function, which will be called when the default Rsbuild middlewares are registered. The middleware you register in the callback function will run after the default middlewares. const myPlugin = () => ({ setup(api) { api.onBeforeStartDevServer(({ server }) => { // the returned callback will be called when the default // middlewares are registered return () => { server.middlewares.use((req, res, next) => { next(); }); }; }); }, }); #### [#](https://rsbuild.rs/plugins/dev/hooks#store-server-instance) Store server instance If you need to access `server` in other hooks, you can store the `server` instance through `api.onBeforeStartDevServer`, and then access it in the hooks executed later. Note that you cannot access `server` in hooks that are executed earlier than `onBeforeStartDevServer`. import type { RsbuildDevServer } from '@rsbuild/core'; const myPlugin = () => ({ setup(api) { let devServer: RsbuildDevServer | null = null; api.onBeforeStartDevServer(({ server, environments }) => { devServer = server; }); api.transform({ test: /\.foo$/ }, ({ code }) => { if (devServer) { // access server API } return code; }); api.onCloseDevServer(() => { devServer = null; }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onafterstartdevserver) 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; environments: Record; }) => Promise | void, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onAfterStartDevServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onbeforedevcompile) onBeforeDevCompile A callback function that is triggered before the dev compile is executed. You can access the Rspack configuration array through the `bundlerConfigs` parameter. The array may contain one or more [Rspack configurations](https://rspack.rs/config/) . It depends on whether multiple [environments](https://rsbuild.rs/config/environments) are configured. Moreover, you can use `isFirstCompile` to determine whether it is the first compile. * **Type:** function OnBeforeDevCompile( callback: (params: { isWatch: boolean; isFirstCompile: boolean; bundlerConfigs?: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **Version:** Added in v1.5.0 * **Example:** const myPlugin = () => ({ setup(api) { api.onBeforeDevCompile(({ bundlerConfigs }) => { console.log('the bundler configs are ', bundlerConfigs); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onafterdevcompile) onAfterDevCompile Called after each development mode build, you can use `isFirstCompile` to determine whether it is the first build. * **Type:** function OnAfterDevCompile( callback: (params: { isFirstCompile: boolean; stats: Stats | MultiStats; environments: Record; }) => Promise | void, ): void; Tip The `onAfterDevCompile` hook was added in Rsbuild v1.5.0. For earlier versions, you can use the functionally identical `onDevCompileDone` hook. * **Example:** const myPlugin = () => ({ setup(api) { api.onAfterDevCompile(({ isFirstCompile }) => { if (isFirstCompile) { console.log('first compile!'); } else { console.log('re-compile!'); } }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onclosedevserver) onCloseDevServer Called when closing the dev server. Can be used to perform cleanup operations when the dev server is closed. Rsbuild CLI will automatically call this hook at the appropriate time, while users of the JavaScript API need to manually call the [server.close()](https://rsbuild.rs/api/javascript-api/instance#close-server) method to trigger this hook. * **Type:** function onCloseDevServer(callback: () => Promise | void): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onCloseDevServer(async () => { console.log('close dev server!'); }); }, }); [#](https://rsbuild.rs/plugins/dev/hooks#preview-hooks-2) Preview hooks ----------------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/dev/hooks#onbeforestartpreviewserver) onBeforeStartPreviewServer Called before starting the preview server. Use the `server` parameter to access the preview server and register custom middlewares. * **Type:** type MaybePromise = T | Promise; type OnBeforeStartPreviewServerFn = (params: { /** * The preview server instance. */ server: RsbuildPreviewServer; /** * Context information for all environments. */ environments: Record; }) => MaybePromise; function OnBeforeStartPreviewServer( callback: OnBeforeStartPreviewServerFn, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onBeforeStartPreviewServer(({ server, environments }) => { console.log('before start!'); console.log('the server is ', server); console.log('the environments contexts are: ', environments); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onafterstartpreviewserver) onAfterStartPreviewServer Called after starting the 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 OnAfterStartPreviewServer( callback: (params: { port: number; routes: Routes; environments: Record; }) => Promise | void, ): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onAfterStartPreviewServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); }, }); [#](https://rsbuild.rs/plugins/dev/hooks#other-hooks) Other hooks ----------------------------------------------------------------- ### [#](https://rsbuild.rs/plugins/dev/hooks#onrestart) onRestart Called when a restart is requested for the dev server or watch build. The hook is triggered in the following cases: * The Rsbuild CLI detects changes to the config file or one of its dependencies. * A configured file event occurs for a file watched by [`dev.watchFiles`](https://rsbuild.rs/config/dev/watch-files) with `type: 'restart'`. * The dev server is manually restarted through a [CLI shortcut](https://rsbuild.rs/config/dev/cli-shortcuts) . > This hook is not triggered for regular rebuilds. When using the JavaScript API, restart watchers are installed by `rsbuild.startDevServer()`, `rsbuild.createDevServer()`, and `rsbuild.build({ watch: true })`. The hook is called when a configured file event occurs. By default, Rsbuild does not close or restart the current task; you can pass the [`restart` option](https://rsbuild.rs/api/javascript-api/core#restart-handling) to handle restart requests. * **Type:** type WatchFileEvent = 'add' | 'change' | 'unlink'; type RestartContext = { filePath?: string; event?: WatchFileEvent; } & ( | { action: 'build'; options: BuildOptions; } | { action: 'dev'; options: StartDevServerOptions; } ); function OnRestart( callback: (context: RestartContext) => Promise | void, ): void; * `action`: The current Rsbuild action being restarted. * `filePath`: The absolute path of the file that triggered the restart. It is `undefined` when the restart is manually triggered. * `event`: The file event that triggered the restart. It is `undefined` when the restart is manually triggered. Available in v2.1.8 or later. * `options`: The options passed to the current `rsbuild.build()` or `rsbuild.startDevServer()` call. * **Version:** Added in v2.1.7 * **Example:** const myPlugin = () => ({ setup(api) { api.onRestart(async ({ action, event, filePath }) => { console.log('restart!', action, event, filePath); }); }, }); ### [#](https://rsbuild.rs/plugins/dev/hooks#onexit) onExit Called when the process is going to exit, this hook can only execute synchronous code. * **Type:** function OnExit(callback: (context: { exitCode: number }) => void): void; * **Example:** const myPlugin = () => ({ setup(api) { api.onExit(({ exitCode }) => { console.log('exit: ', exitCode); }); }, }); --- # Babel 插件 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/list/plugin-babel.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#babel-%E6%8F%92%E4%BB%B6) Babel 插件 ====================================================================================== 复制 Markdown [源码](https://github.com/web-infra-dev/rsbuild/tree/main/packages/plugin-babel) Rsbuild 默认使用 SWC 编译,当内置的功能无法满足诉求、需要添加一些 Babel presets 或 plugins 进行额外处理时,你可以使用 Rsbuild 的 Babel 插件。 [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B) 快速开始 ---------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E5%AE%89%E8%A3%85%E6%8F%92%E4%BB%B6) 安装插件 执行以下命令安装插件: npm yarn pnpm bun deno npm add @rsbuild/plugin-babel -D yarn add @rsbuild/plugin-babel -D pnpm add @rsbuild/plugin-babel -D bun add @rsbuild/plugin-babel -D deno add npm:@rsbuild/plugin-babel -D ### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E6%B3%A8%E5%86%8C%E6%8F%92%E4%BB%B6) 注册插件 在 Rsbuild 配置中注册插件: rsbuild.config.ts import { pluginBabel } from '@rsbuild/plugin-babel'; export default { plugins: [pluginBabel()], }; [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E7%BC%96%E8%AF%91%E7%BC%93%E5%AD%98) 编译缓存 ---------------------------------------------------------------------------------------------- 使用 Babel 插件后,Rsbuild 除了执行默认的 SWC 转译,还会执行 Babel 转译,存在额外的编译开销,这可能导致构建速度明显降低。 为了降低 Babel 转译的开销,`@rsbuild/plugin-babel` 默认开启了 Babel 编译缓存。如果你希望禁用缓存,可以将 [performance.buildCache](https://rsbuild.rs/zh/config/performance/build-cache) 设置为 `false`: rsbuild.config.ts export default { performance: { buildCache: false, }, }; [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E9%80%89%E9%A1%B9) 选项 -------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#babelloaderoptions) babelLoaderOptions 传递给 `babel-loader` 的选项,请查阅 [babel-loader 文档](https://github.com/babel/babel-loader) 来了解具体用法。 * **类型:** `Object | Function` * **默认值:** const defaultOptions = { babelrc: false, compact: config.mode === 'production', configFile: false, plugins: [\ ['@babel/plugin-proposal-decorators', config.source.decorators],\ ...(isLegacyDecorators ? ['@babel/plugin-transform-class-properties'] : []),\ ], presets: [\ [\ '@babel/preset-typescript',\ {\ allExtensions: true,\ allowDeclareFields: true,\ allowNamespaces: true,\ isTSX: true,\ optimizeConstEnums: true,\ },\ ],\ ], }; #### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#function-%E7%B1%BB%E5%9E%8B) Function 类型 当配置项为 Function 类型时,默认 Babel 配置会作为第一个参数传入,你可以直接修改配置对象,也可以返回一个对象作为最终的 `babel-loader` 配置。 pluginBabel({ babelLoaderOptions: (config) => { // 添加一个插件,比如配置某个组件库的按需引入 config.plugins ||= []; config.plugins.push([\ 'babel-plugin-import',\ {\ libraryName: 'my-components',\ libraryDirectory: 'es',\ style: true,\ },\ ]); }, }); 函数的第二个参数提供了一些方便的工具函数,请继续阅读下方文档。 Tip 以上示例仅作为参考,通常来说,你不需要手动配置 `babel-plugin-import`,因为 Rspack SWC 编译已支持 transformImport 能力,Rsbuild 也提供了更通用的 [source.transformImport](https://rsbuild.rs/zh/config/source/transform-import) 配置。 #### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#object-%E7%B1%BB%E5%9E%8B) Object 类型 当配置项的值为 `Object` 类型时,会与默认配置通过 `Object.assign` 浅合并。 Caution `Object.assign` 是浅拷贝,会完全覆盖内置的 `presets` 或 `plugins` 数组,导致内置的 presets 或 plugins 失效,请在明确影响面的情况下再使用这种方式。 pluginBabel({ babelLoaderOptions: { plugins: [\ [\ 'babel-plugin-import',\ {\ libraryName: 'my-components',\ libraryDirectory: 'es',\ style: true,\ },\ ],\ ], }, }); #### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E5%B7%A5%E5%85%B7%E5%87%BD%E6%95%B0) 工具函数 配置项为 Function 类型时,第二个参数可用的工具函数如下: ##### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#addplugins) addPlugins * **类型:** `(plugins: BabelPlugin[]) => void` 添加若干个 Babel 插件。 pluginBabel({ babelLoaderOptions: (config, { addPlugins }) => { addPlugins([\ [\ 'babel-plugin-import',\ {\ libraryName: 'my-components',\ libraryDirectory: 'es',\ style: true,\ },\ ],\ ]); }, }); ##### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#addpresets) addPresets * **类型:** `(presets: BabelPlugin[]) => void` 添加若干个 Babel 预设配置 (大多数情况下不需要增加预设)。 pluginBabel({ babelLoaderOptions: (config, { addPresets }) => { addPresets(['@babel/preset-env']); }, }); ##### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#removeplugins) removePlugins * **类型:** `(plugins: string | string[]) => void` 移除 Babel 插件,传入需要移除的插件名称即可,你可以传入单个字符串,也可以传入一个字符串数组。 pluginBabel({ babelLoaderOptions: (config, { removePlugins }) => { removePlugins('babel-plugin-import'); }, }); ##### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#removepresets) removePresets * **类型:** `(presets: string | string[]) => void` 移除 Babel 预设配置,传入需要移除的预设名称即可,你可以传入单个字符串,也可以传入一个字符串数组。 pluginBabel({ babelLoaderOptions: (config, { removePresets }) => { removePresets('@babel/preset-env'); }, }); ##### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#modifypresetenvoptions) modifyPresetEnvOptions * **类型:** `(options: PresetEnvOptions) => void` 修改已有的 `@babel/preset-env` 预设选项。如果 `config.presets` 中不存在该预设,则该函数不会产生效果。 pluginBabel({ babelLoaderOptions: (config, { addPresets, modifyPresetEnvOptions }) => { addPresets(['@babel/preset-env']); modifyPresetEnvOptions({ targets: ['chrome >= 107'], }); }, }); ##### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#modifypresetreactoptions) modifyPresetReactOptions * **类型:** `(options: PresetReactOptions) => void` 修改已有的 `@babel/preset-react` 预设选项。如果 `config.presets` 中不存在该预设,则该函数不会产生效果。 pluginBabel({ babelLoaderOptions: (config, { addPresets, modifyPresetReactOptions }) => { addPresets(['@babel/preset-react']); modifyPresetReactOptions({ runtime: 'automatic', }); }, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#include) include * **类型:** `string | RegExp | (string | RegExp)[]` * **默认值:** `undefined` 用于指定需要 Babel 编译的文件。 由于 Babel 编译存在性能开销,通过 `include` 来匹配部分文件可以减少 Babel 编译的模块数量,从而提升构建性能。 比如,只对 `.custom.js` 文件进行编译: pluginBabel({ include: /\.custom\.js$/, }); Tip 当你配置 `include` 或 `exclude` 选项时,Rsbuild 会创建一条单独的 Rspack rule 来应用 babel-loader 和 swc-loader。 这条单独的 rule 与 Rsbuild 内置的 SWC rule 是完全独立的,并且不会受到 [source.include](https://rsbuild.rs/zh/config/source/include) 和 [source.exclude](https://rsbuild.rs/zh/config/source/exclude) 的作用。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#exclude) exclude * **类型:** `string | RegExp | (string | RegExp)[]` * **默认值:** `undefined` 用于指定不需要 Babel 编译的文件。 由于 Babel 编译存在性能开销,通过 `exclude` 来排除部分文件可以减少 Babel 编译的模块数量,从而提升构建性能。 比如,忽略 `node_modules` 下的 `.js` 文件: pluginBabel({ // 排除 node_modules 下的 .js 文件以提升构建性能 exclude: /[\\/]node_modules[\\/].*\.js$/, }); ### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#parallel) parallel * **类型:** `boolean` * **默认值:** `false` * **版本:** `>= 2.0.0` 是否使用 worker 线程并行执行 Babel 转换。开启后,JavaScript 模块会被分配到多个 worker 线程中处理,降低主线程压力,并在编译大量模块时提升整体构建性能。 pluginBabel({ parallel: true, }); > 该功能基于 Rspack 的 parallel loader 实现。传递给 worker 线程的选项必须符合 [HTML 结构化克隆算法](https://nodejs.org/api/worker_threads.html#portpostmessagevalue-transferlist) > 的要求,否则会传输失败。例如,不能将函数作为选项传递。详见 [Rspack - Rule.use.parallel](https://rspack.rs/zh/config/module-rules#rulesuseparallel) > 。 [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E6%B3%A8%E5%86%8C%E5%A4%9A%E4%B8%AA%E6%8F%92%E4%BB%B6) 注册多个插件 ------------------------------------------------------------------------------------------------------------------ 通过使用 `include` 和 `exclude` 选项,你可以注册多个 `@rsbuild/plugin-babel` 实例,并为不同文件创建独立的 Babel 规则。 例如: export default { plugins: [\ pluginBabel({\ exclude: /\.legacy\.js$/,\ babelLoaderOptions: {\ plugins: ['babel-plugin-modern'],\ },\ }),\ pluginBabel({\ include: /\.legacy\.js$/,\ babelLoaderOptions: {\ plugins: ['babel-plugin-legacy'],\ },\ }),\ ], }; [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E6%89%A7%E8%A1%8C%E9%A1%BA%E5%BA%8F) 执行顺序 ---------------------------------------------------------------------------------------------- 使用 `@rsbuild/plugin-babel` 后,Rsbuild 会使用 `babel-loader` 和 `builtin:swc-loader` 分别对 JavaScript 文件进行编译,且 Babel 的执行时机早于 SWC。 这意味着,当代码中使用某些 ECMAScript 新特性时,你可能需要添加 Babel 插件,使 Babel 能够正确编译这些新特性。 例如,添加 [@babel/plugin-transform-private-methods](https://www.npmjs.com/package/@babel/plugin-transform-private-methods) 插件,使 Babel 能够正确编译 [private properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) : pluginBabel({ babelLoaderOptions: { plugins: ['@babel/plugin-transform-private-methods'], }, }); [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97) 使用指南 ---------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#use-react-compiler) 使用 React Compiler 本节介绍如何通过 Babel 插件启用 React Compiler。这是一个可选方案,主要适合维护已有 Babel 配置、使用较旧版本的 Rsbuild,或需要基于 Babel 插件进行自定义的场景。对于大多数项目,更推荐使用 Rust 版本的 React Compiler,详见 [React Compiler 指南](https://rsbuild.rs/zh/guide/framework/react#react-compiler) 。 通过 Babel 插件使用 React Compiler 的步骤如下: 1. 升级 `react` 和 `react-dom` 版本到 19。如果你暂时无法升级,可以在 React 17 或 18 项目中安装 [react-compiler-runtime](https://npmjs.com/package/react-compiler-runtime) ,以允许编译后的代码在 19 之前的版本上运行。 2. 安装 [@rsbuild/plugin-babel](https://rsbuild.rs/zh/plugins/list/plugin-babel) 和 [babel-plugin-react-compiler](https://npmjs.com/package/babel-plugin-react-compiler) 。 3. 在你的 Rsbuild 配置文件中注册 Babel 插件: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginBabel } from '@rsbuild/plugin-babel'; import { pluginReact } from '@rsbuild/plugin-react'; export default defineConfig({ plugins: [\ pluginReact(),\ pluginBabel({\ include: /\.[jt]sx?$/,\ exclude: [/[\\/]node_modules[\\/]/],\ babelLoaderOptions(opts) {\ opts.plugins ??= [];\ opts.plugins.unshift('babel-plugin-react-compiler');\ },\ }),\ ], }); Tip `include` 使用 `/\.[jt]sx?$/` 来匹配 `.js`、`.jsx`、`.ts` 和 `.tsx` 文件。这样可以确保 React Compiler 能够优化组件和[自定义 Hooks](https://zh-hans.react.dev/learn/reusing-logic-with-custom-hooks) ,因为自定义 Hooks 通常定义在 `.ts` 文件中。`exclude` 中的 `node_modules` 可以防止编译器处理第三方依赖。 如果你只想编译 JSX/TSX 文件,可以使用 `include: /\.(?:jsx|tsx)$/`,但 `.ts` 文件中的自定义 Hooks 将不会被优化。 > 你也可以参考 [示例项目](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/react-compiler-babel) > 。 #### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E9%85%8D%E7%BD%AE-react-compiler) 配置 React Compiler 通过 Babel 配置 React Compiler 时,可以将编译选项传给 `babel-plugin-react-compiler`: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginBabel } from '@rsbuild/plugin-babel'; import { pluginReact } from '@rsbuild/plugin-react'; const ReactCompilerConfig = {/* ... */}; export default defineConfig({ plugins: [\ pluginReact(),\ pluginBabel({\ include: /\.[jt]sx?$/,\ exclude: [/[\\/]node_modules[\\/]/],\ babelLoaderOptions(opts) {\ opts.plugins ??= [];\ opts.plugins.unshift([\ 'babel-plugin-react-compiler',\ ReactCompilerConfig,\ ]);\ },\ }),\ ], }); 对于 React 17 和 18 的项目,除了安装 [react-compiler-runtime](https://npmjs.com/package/react-compiler-runtime) ,还需要指定 `target`: rsbuild.config.ts const ReactCompilerConfig = { target: '18', // '17' | '18' | '19' }; [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E8%B0%83%E8%AF%95%E9%85%8D%E7%BD%AE) 调试配置 ---------------------------------------------------------------------------------------------- 当你通过配置项修改 `babel-loader` 配置后,可以在 [Rsbuild 调试模式](https://rsbuild.rs/zh/guide/debug/debug-mode) 下查看最终生成的配置。 首先通过 `DEBUG=rsbuild` 参数开启调试模式: # 调试开发模式 DEBUG=rsbuild pnpm dev # 调试生产模式 DEBUG=rsbuild pnpm build 然后打开生成的 `rspack.config.web.mjs`,搜索 `babel-loader` 关键词,即可看到完整的 `babel-loader` 配置内容。 [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#helper-functions) 辅助函数 -------------------------------------------------------------------------- `@rsbuild/plugin-babel` 提供了一些面向插件开发者和框架作者的辅助函数。 ### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#modifybabelloaders) modifyBabelLoaders * **类型:** function modifyBabelLoaders(options: ModifyBabelLoadersOptions): void; type ModifyBabelLoadersOptions = { chain: RspackChain; CHAIN_ID: ChainIdentifier; modifyOptions?: (options: BabelTransformOptions) => BabelTransformOptions; modifyRule?: ( rule: RspackChain.Rule, context: { babelUseId: string }, ) => void; }; * **版本:** `>= 2.1.0` `modifyBabelLoaders` 用于修改 Babel loader 选项及其所在的 rule。 * `modifyOptions` 修改当前的 `babel-loader` 选项,并且需要返回最终选项。 * `modifyRule` 修改匹配的 rule。如果同时提供两个回调,它会在 `modifyOptions` 之后执行。可以通过 `babelUseId` 访问该 rule 中的 Babel loader。 在自定义 Rsbuild 插件的 [`modifyBundlerChain`](https://rsbuild.rs/zh/plugins/dev/hooks#modifybundlerchain) 钩子中调用此函数: rsbuild.config.ts import { defineConfig, type RsbuildPlugin } from '@rsbuild/core'; import { modifyBabelLoaders, pluginBabel } from '@rsbuild/plugin-babel'; const pluginCustomizeBabel = (): RsbuildPlugin => ({ name: 'customize-babel', setup(api) { api.modifyBundlerChain((chain, { CHAIN_ID }) => { modifyBabelLoaders({ chain, CHAIN_ID, modifyOptions(options) { options.plugins ??= []; options.plugins.push('babel-plugin-example'); return options; }, modifyRule(rule) { rule.exclude.add(/[\\/]node_modules[\\/]/); }, }); }); }, }); export default defineConfig({ plugins: [pluginBabel(), pluginCustomizeBabel()], }); [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98) 常见问题 ---------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/list/plugin-babel#%E7%BC%96%E8%AF%91%E5%8D%A1%E6%AD%BB) 编译卡死 在使用 Babel 插件后,如果编译进度条卡死,但终端无 Error 日志时,通常是因为编译过程中出现了异常。在某些情况下,当 Error 被 webpack 或其他模块捕获后,错误日志不会被正确输出。最为常见的场景是 Babel 配置出现异常,抛出 Error 后被 webpack 捕获,而 webpack 在个别情况下吞掉了 Error。 **解决方法:** 如果你修改 Babel 配置后出现此问题,建议检查是否有以下错误用法: 1. 配置了一个不存在的 plugin 或 preset,可能是名称拼写错误,或是未正确安装。 // 错误示例 pluginBabel({ babelLoaderOptions: (config, { addPlugins }) => { // 该插件名称错误,或者未安装 addPlugins('babel-plugin-not-exists'); }, }); 2. 是否配置了多个 babel-plugin-import,但是没有在数组的第三项声明每一个 babel-plugin-import 的名称。 // 错误示例 pluginBabel({ babelLoaderOptions: (config, { addPlugins }) => { addPlugins([\ ['babel-plugin-import', { libraryName: 'antd', libraryDirectory: 'es' }],\ [\ 'babel-plugin-import',\ { libraryName: 'antd-mobile', libraryDirectory: 'es' },\ ],\ ]); }, }); // 正确示例 pluginBabel({ babelLoaderOptions: (config, { addPlugins }) => { addPlugins([\ [\ 'babel-plugin-import',\ { libraryName: 'antd', libraryDirectory: 'es' },\ 'antd',\ ],\ [\ 'babel-plugin-import',\ { libraryName: 'antd-mobile', libraryDirectory: 'es' },\ 'antd-mobile',\ ],\ ]); }, }); --- # 插件 API - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/dev/core.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/dev/core#%E6%8F%92%E4%BB%B6-api) 插件 API ========================================================================= 复制 Markdown 本章节了介绍 Rsbuild 插件的 API 类型定义和使用方法。 [#](https://rsbuild.rs/zh/plugins/dev/core#rsbuildplugin) RsbuildPlugin ----------------------------------------------------------------------- 插件对象的类型,插件对象包含以下属性: * `name`:插件的名称,唯一标识符。 * `setup`:插件逻辑的主入口函数,可以是一个异步函数。该函数仅会在初始化插件时执行一次。插件 API 对象上挂载了提供给插件使用的上下文数据、工具函数和注册生命周期钩子的函数,关于生命周期钩子的完整介绍,请阅读 [插件 hooks](https://rsbuild.rs/zh/plugins/dev/hooks) 章节。 * `apply`: 控制插件在 `serve` 或 `build` 时生效,详见 [条件启用](https://rsbuild.rs/zh/plugins/dev/core#conditional-application) 。 * `enforce`: 指定插件的执行顺序,详见 [enforce 属性](https://rsbuild.rs/zh/plugins/dev/core#enforce-property) 。 * `pre`:声明前置插件的名称,这些插件会在当前插件之前执行,详见 [前置插件](https://rsbuild.rs/zh/plugins/dev/core#pre-plugins) 。 * `post`:声明后置插件的名称,这些插件会在当前插件之后执行,详见 [后置插件](https://rsbuild.rs/zh/plugins/dev/core#post-plugins) 。 * `remove`:声明需要移除的插件,可以传入插件 name 的数组,详见 [移除插件](https://rsbuild.rs/zh/plugins/dev/core#removing-plugins) 。 type RsbuildPlugin = { name: string; setup: (api: RsbuildPluginAPI) => Promise | void; apply?: 'serve' | 'build' | Function; enforce?: 'pre' | 'post'; pre?: string[]; post?: string[]; remove?: string[]; }; 你可以从 `@rsbuild/core` 中导入该类型: pluginFoo.ts import type { RsbuildPlugin } from '@rsbuild/core'; export const pluginFoo = (): RsbuildPlugin => ({ name: 'plugin-foo', setup(api) { api.onAfterBuild(() => { console.log('after build!'); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/core#conditional-application) 条件启用 默认情况下,插件在运行开发服务器和生产构建时都会生效。如果你希望一个插件只在其中某个场景下生效,你可以通过 `apply` 属性来指定插件的生效时机: * `serve`:运行开发或预览服务器时生效 * `build`:运行生产构建时生效 // 该插件只在 serve 时生效 const pluginServe = () => ({ name: 'plugin-serve', apply: 'serve', setup(api) { // ... }, }); // 该插件只在 build 时生效 const pluginBuild = () => ({ name: 'plugin-build', apply: 'build', setup(api) { // ... }, }); `apply` 属性也可以是一个函数,函数接收 `config` 和 `context` 两个参数。 type RsbuildPluginApplyFn = ( this: void, // 原始的 Rsbuild 配置对象(未经过插件处理) config: RsbuildConfig, // 上下文对象 context: { // 当前操作的类型 action: 'dev' | 'build' | 'preview'; }, ) => boolean; `apply` 函数返回 `true` 来应用插件,返回 `false` 来跳过插件。 const pluginBuild = () => ({ name: 'plugin-build', apply(config, { action }) { return action === 'build' && config.output?.target === 'web'; }, setup(api) { // ... }, }); Tip `apply` 属性是在 `@rsbuild/core` v1.4.8 版本中引入的。 ### [#](https://rsbuild.rs/zh/plugins/dev/core#enforce-property) `enforce` 属性 默认情况下,插件会按照添加顺序依次执行,插件可以通过添加 `enforce` 属性来调整执行顺序: * `pre`:在其他插件之前执行当前插件 * `post`:在其他插件之后执行当前插件 const pluginFoo = () => ({ name: 'plugin-foo', enforce: 'pre', setup(api) { // ... }, }); const pluginBar = () => ({ name: 'plugin-bar', enforce: 'post', setup(api) { // ... }, }); `enforce` 会影响钩子注册的顺序,但如果钩子指定了 [order](https://rsbuild.rs/zh/plugins/dev/hooks#callback-order) 属性,则 `order` 具有更高的优先级。 Tip `enforce` 属性是在 `@rsbuild/core` v1.4.9 版本中引入的。 ### [#](https://rsbuild.rs/zh/plugins/dev/core#pre-plugins) 前置插件 通过设置 `pre` 属性可以强制指定某些插件在当前插件之前执行,`pre` 属性的优先级高于 `enforce` 属性。 比如有下面两个插件: const pluginFoo = { name: 'plugin-foo', }; const pluginBar = { name: 'plugin-bar', pre: ['plugin-foo'], }; Bar 插件在 `pre` 属性中配置了 Foo 插件,因此 Foo 插件一定会在 Bar 插件之前执行。 ### [#](https://rsbuild.rs/zh/plugins/dev/core#post-plugins) 后置插件 通过设置 `post` 属性可以强制指定某些插件在当前插件之后执行,`post` 属性的优先级高于 `enforce` 属性。 const pluginFoo = { name: 'plugin-foo', }; const pluginBar = { name: 'plugin-bar', post: ['plugin-foo'], }; Bar 插件在 `post` 属性中配置了 Foo 插件,因此 Foo 插件一定会在 Bar 插件之后执行。 ### [#](https://rsbuild.rs/zh/plugins/dev/core#removing-plugins) 移除插件 通过 `remove` 属性可以在一个插件中移除其他插件。 const pluginFoo = { name: 'plugin-foo', }; const pluginBar = { name: 'plugin-bar', remove: ['plugin-foo'], }; 比如同时注册上述的 Foo 和 Bar 插件,由于 Bar 插件声明 remove 了 Foo 插件,因此 Foo 插件不会生效。 需要注意的是:如果当前插件注册为[特定环境插件](https://rsbuild.rs/zh/guide/advanced/environments#plugins-specified-environment) ,则仅支持移除同环境插件,不能移除全局插件。 [#](https://rsbuild.rs/zh/plugins/dev/core#apicontext) api.context ------------------------------------------------------------------ `api.context` 是一个只读对象,提供一些上下文信息。 `api.context` 的内容与 `rsbuild.context` 完全一致,请参考 [rsbuild.context](https://rsbuild.rs/zh/api/javascript-api/instance#rsbuildcontext) 。 * **示例:** const pluginFoo = () => ({ setup(api) { console.log(api.context.distPath); }, }); [#](https://rsbuild.rs/zh/plugins/dev/core#apigetrsbuildconfig) api.getRsbuildConfig ------------------------------------------------------------------------------------ 获取 Rsbuild 配置。 * **类型:** type GetRsbuildConfig = { (): Readonly; (type: 'original' | 'current'): Readonly; (type: 'normalized'): NormalizedConfig; }; * **参数:** 你可以通过 `type` 参数来指定读取的 Rsbuild 配置类型: // 获取用户定义的原始 Rsbuild 配置。 getRsbuildConfig('original'); // 获取当前的 Rsbuild 配置。 // 在 Rsbuild 的不同执行阶段,该配置的内容会发生变化。 // 比如 `modifyRsbuildConfig` 钩子执行后会修改当前 Rsbuild 配置的内容。 getRsbuildConfig('current'); // 获取规范化后的 Rsbuild 配置。 // 该方法必须在 `modifyRsbuildConfig` 钩子执行完成后才能被调用。 // 等价于 `getNormalizedConfig` 方法。 getRsbuildConfig('normalized'); * **示例:** const pluginFoo = () => ({ setup(api) { const config = api.getRsbuildConfig(); console.log(config.html?.title); }, }); [#](https://rsbuild.rs/zh/plugins/dev/core#apigetnormalizedconfig) api.getNormalizedConfig ------------------------------------------------------------------------------------------ 获取规范化后的完整 Rsbuild 配置(包含所有环境),或指定环境的规范化配置。该方法只能在 [modifyRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) 钩子执行完毕后调用。 与 [`getRsbuildConfig`](https://rsbuild.rs/zh/plugins/dev/core#apigetrsbuildconfig) 相比,该方法返回经过规范化处理、类型更明确的配置。例如,`config.html` 的类型不再包含 `undefined`。 使用 `getNormalizedConfig()` 获取包含所有环境的完整配置。如需获取指定环境的配置,则使用 `getNormalizedConfig({ environment: name })`。 * **类型:** type GetNormalizedConfig = { /** 获取包含所有环境的完整规范化配置 */ (): NormalizedConfig; /** 获取指定环境的规范化 Rsbuild 配置 */ (options: { environment: string }): NormalizedEnvironmentConfig; }; * **示例:** const pluginFoo = () => ({ setup(api) { api.onBeforeBuild(({ bundlerConfigs }) => { const config = api.getNormalizedConfig(); console.log(config.html.title); }); }, }); 当插件钩子的回调参数中包含 [`environment`](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-context) 时,建议通过 `environment.config` 获取当前环境的规范化配置。该配置由基础配置与[当前环境的配置](https://rsbuild.rs/zh/guide/advanced/environments) 合并并经过规范化处理后得到。 const pluginFoo = () => ({ setup(api) { api.onBeforeEnvironmentCompile(({ environment }) => { const { config } = environment; console.log(config.output.target); }); }, }); [#](https://rsbuild.rs/zh/plugins/dev/core#apilogger) api.logger ---------------------------------------------------------------- 提供统一日志输出格式的实例,可以用于输出与 Rsbuild 一致的日志格式。 > 详见 [日志](https://rsbuild.rs/zh/guide/advanced/logging) > 。 * **版本:** `>= 1.4.0` * **示例:** const pluginLogging = () => ({ setup(api) { api.logger.info('This is an info message'); api.logger.warn('This is a warning message'); api.logger.error('This is an error message'); }, }); [#](https://rsbuild.rs/zh/plugins/dev/core#apiispluginexists) api.isPluginExists -------------------------------------------------------------------------------- 判断某个插件是否已经在当前 Rsbuild 实例中注册。 * 如果未指定 `environment` 参数,则判断全局注册的插件中是否存在该插件。 * 如果指定了 `environment` 参数,则判断在指定环境中是否存在该插件。 * **类型:** function IsPluginExists( pluginName: string, options?: { /** * Whether it exists in the specified environment. * If environment is not specified, determine whether the plugin is a global plugin. */ environment: string; }, ): boolean; * **示例:** export default () => ({ setup(api) { console.log(api.isPluginExists('plugin-foo')); }, }); 或者检查指定环境中是否存在插件: export default () => ({ setup(api) { console.log(api.isPluginExists('plugin-foo', { environment: 'web' })); }, }); [#](https://rsbuild.rs/zh/plugins/dev/core#apitransform) api.transform ---------------------------------------------------------------------- `api.transform` 是 [Rspack loader](https://rspack.rs/zh/guide/features/loader) 的简化封装,让你能够在构建过程中轻松转换特定模块的代码。 你可以通过模块路径、查询参数或其他条件匹配文件,并对其内容应用自定义转换。 * **类型:** function Transform( descriptor: TransformDescriptor, handler: TransformHandler, ): void; `api.transform` 接受两个参数: * `descriptor`:一个对象,用于描述模块的匹配条件。 * `handler`:一个转换函数,接收模块当前的代码,并返回转换后的代码。 ### [#](https://rsbuild.rs/zh/plugins/dev/core#%E7%A4%BA%E4%BE%8B) 示例 比如匹配以 `.pug` 为后缀的模块,并转换为 JavaScript 代码: 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;`; }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/core#descriptor-%E5%8F%82%E6%95%B0) descriptor 参数 `descriptor` 参数是一个对象,用于描述模块的匹配条件。 * **类型:** type TransformDescriptor = { test?: RuleSetCondition; targets?: RsbuildTarget[]; environments?: string[]; resourceQuery?: RuleSetCondition; raw?: boolean; layer?: string; issuer?: RuleSetCondition; issuerLayer?: string; with?: Record; mimetype?: RuleSetCondition; /** @deprecated 请使用 `order` */ enforce?: 'pre' | 'post'; order?: 'pre' | 'post' | 'default'; }; `descriptor` 参数支持设置以下匹配条件: * `test`:匹配模块的路径(不包含 query),等价于 Rspack 的 [rules\[\].test](https://rspack.rs/zh/config/module-rules#rulestest) 。 api.transform({ test: /\.md$/ }, ({ code }) => { // ... }); * `targets`:匹配 Rsbuild [output.target](https://rsbuild.rs/zh/config/output/target) ,仅对匹配的 targets 应用当前 transform 函数。 api.transform({ test: /\.md$/, targets: ['web'] }, ({ code }) => { // ... }); * `environments`:匹配 Rsbuild [environment](https://rsbuild.rs/zh/guide/advanced/environments) name,仅对匹配的 environments 应用当前 transform 函数。 api.transform({ test: /\.md$/, environments: ['web'] }, ({ code }) => { // ... }); * `resourceQuery`:匹配模块的 query,等价于 Rspack 的 [rules\[\].resourceQuery](https://rspack.rs/zh/config/module-rules#rulesresourcequery) 。 // 匹配 raw query: "foo.ext?raw" api.transform({ resourceQuery: /^\?raw$/ }, ({ code }) => { // ... }); * `raw`:如果 `raw` 为 `true`,则 transform 函数将接收到 Buffer 类型的代码,而不是 string 类型。 api.transform({ test: /\.node$/, raw: true }, ({ code }) => { // ... }); * `layer`:标识匹配的模块的 [layer](https://rspack.rs/zh/guide/features/layer#layer) ,可以将一组模块聚合到一个 layer 中,等同于 Rspack 的 [rules\[\].layer](https://rspack.rs/zh/config/module-rules#ruleslayer) 。 api.transform({ test: /\.md$/, layer: 'foo' }, ({ code }) => { // ... }); * `issuerLayer`:与"引入当前模块"的模块的 [layer](https://rspack.rs/zh/guide/features/layer#layer) 进行匹配,等同于 Rspack 的 [rules\[\].issuerLayer](https://rspack.rs/zh/config/module-rules#rulesissuerlayer) 。 api.transform({ test: /\.md$/, issuerLayer: 'foo' }, ({ code }) => { // ... }); * `issuer`:匹配"引入当前模块"的模块的绝对路径,等同于 Rspack 的 [rules\[\].issuer](https://rspack.rs/zh/config/module-rules#rulesissuer) 。 api.transform({ test: /\.md$/, issuer: /\.js$/ }, ({ code }) => { // ... }); * `with`:匹配 [import attributes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import/with) ,等同于 Rspack 的 [rules\[\].with](https://rspack.rs/zh/config/module-rules#ruleswith) 。 api.transform({ test: /\.md$/, with: { type: 'url' } }, ({ code }) => { // ... }); * `mimetype`:根据 MIME 类型(而非文件扩展名)匹配模块。主要用于 data URI 模块(例如 `data:text/javascript,...`),等同于 Rspack 的 [rules\[\].mimetype](https://rspack.rs/zh/config/module-rules#rulesmimetype) 。 api.transform({ mimetype: 'text/javascript' }, ({ code }) => { // ... }); * `order`:指定 transform 函数的执行顺序,对应 Rspack 的 [rules\[\].enforce](https://rspack.rs/zh/config/module-rules#rulesenforce) 。 * 当 `order` 为 `pre` 时,transform 函数会在其他 transform 函数(或 Rspack loader)之前执行。 * 当 `order` 为 `post` 时,transform 函数会在其他 transform 函数(或 Rspack loader)之后执行。 * 当 `order` 为 `default` 时,transform 函数会使用默认的 loader 顺序。 api.transform({ test: /\.md$/, order: 'pre' }, ({ code }) => { // ... }); * `enforce`:已废弃,请使用 `order` 代替。 ### [#](https://rsbuild.rs/zh/plugins/dev/core#handler-%E5%8F%82%E6%95%B0) handler 参数 handler 参数是一个转换函数,接收模块当前的代码,并返回转换后的代码。 * **类型:** type TransformContext = { code: string; context: string | null; resource: string; resourcePath: string; resourceQuery: string; environment: EnvironmentContext; addDependency: (file: string) => void; addMissingDependency: (file: string) => void; addContextDependency: (context: string) => void; emitFile: Rspack.LoaderContext['emitFile']; importModule: Rspack.LoaderContext['importModule']; resolve: Rspack.LoaderContext['resolve']; }; type TransformResult = | string | Buffer | { code: string | Buffer; map?: string | Rspack.sources.RawSourceMap | null; }; type TransformHandler = ( context: TransformContext, ) => MaybePromise; handler 函数提供以下参数: * `code`:模块的代码。 * `context`:当前被处理的模块所在的目录路径,与 Rspack loader 的 [this.context](https://rspack.rs/zh/api/loader-api/context#thiscontext) 相同。 * `resolve`:解析一个模块标识符。与 Rspack loader 的 [this.resolve](https://rspack.rs/zh/api/loader-api/context#thisresolve) 相同。 * `resource`:模块的绝对路径,包含 query,与 Rspack loader 的 [this.resource](https://rspack.rs/zh/api/loader-api/context#thisresource) 相同。 * `resourcePath`:模块的绝对路径,不包含 query,与 Rspack loader 的 [this.resourcePath](https://rspack.rs/zh/api/loader-api/context#thisresourcepath) 相同。 * `resourceQuery`:模块路径上的 query,与 Rspack loader 的 [this.resourceQuery](https://rspack.rs/zh/api/loader-api/context#thisresourcequery) 相同。 * `environment`: 当前构建的 [environment 上下文](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-context) . * `addDependency`:添加一个额外的文件作为依赖。该文件将被监听,并在发生变更时触发重新构建。与 Rspack loader 的 [this.addDependency](https://rspack.rs/zh/api/loader-api/context#thisadddependency) 相同。 * `addMissingDependency`:添加一个不存在的文件作为依赖。该文件将被监听,并在发生变更时触发重新构建。与 Rspack loader 的 [this.addMissingDependency](https://rspack.rs/zh/api/loader-api/context#thisaddmissingdependency) 相同。 * `addContextDependency`:添加一个额外的目录作为依赖。该目录将被监听,并在发生变更时触发重新构建。与 Rspack loader 的 [this.addContextDependency](https://rspack.rs/zh/api/loader-api/context#thisaddcontextdependency) 相同。 * `emitFile`:将一个文件输出到构建结果中。与 Rspack loader 的 [this.emitFile](https://rspack.rs/zh/api/loader-api/context#thisemitfile) 相同。 * `importModule`:在构建时编译并执行一个模块。与 Rspack loader 的 [this.importModule](https://rspack.rs/zh/api/loader-api/context#thisimportmodule) 相同。 比如: api.transform( { test: /\.md$/ }, ({ 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' }, ); ### [#](https://rsbuild.rs/zh/plugins/dev/core#%E4%B8%8E-loader-%E7%9A%84%E5%8C%BA%E5%88%AB) 与 loader 的区别 `api.transform` 可以理解为 Rspack loader 的一个轻量化实现,它提供了简单易用的 API,并在底层自动调用 Rspack loader 进行代码转换。 在 Rsbuild 插件中,你可以通过 `api.transform` 快速实现代码转换功能,能够满足大部分常见场景,而无须学习 Rspack loader 的编写方法。 注意,对于一些复杂的代码转换场景,`api.transform` 可能无法满足,此时你可以使用 Rspack loader 进行实现。 ### [#](https://rsbuild.rs/zh/plugins/dev/core#source-maps) Source maps 你可以在 `transform` 函数中返回一个 source map,Rsbuild 会自动将返回的 source map 与其他 Rspack loader 或 `transform` hook 生成的 source maps 合并,使最终的 source map 能够正确映射到原始源代码。 api.transform({ test: /\.js$/ }, async ({ code }) => { const { transformedCode, sourceMap } = await someTransformFunction(code); return { code: transformedCode, map: sourceMap, }; }); [#](https://rsbuild.rs/zh/plugins/dev/core#apiresolve) api.resolve ------------------------------------------------------------------ 在模块解析开始之前,拦截并修改模块的请求信息。等价于 Rspack 的 [normalModuleFactory.hooks.resolve](https://rspack.rs/zh/api/plugin-api/normal-module-factory-hooks#resolve) hook。 * **版本:** `>= 1.0.17` * **类型:** function ResolveHook(handler: ResolveHandler): void; ### [#](https://rsbuild.rs/zh/plugins/dev/core#%E7%A4%BA%E4%BE%8B-1) 示例 * 修改 `a.js` 文件请求: api.resolve(({ resolveData }) => { if (resolveData.request === './a.js') { resolveData.request = './b.js'; } }); ### [#](https://rsbuild.rs/zh/plugins/dev/core#handler-%E5%8F%82%E6%95%B0-1) `handler` 参数 handler 参数是一个回调函数,接收一个模块的请求信息,并允许你修改它。 * **类型:** type ResolveHandler = (context: { resolveData: Rspack.ResolveData; compiler: Rspack.Compiler; compilation: Rspack.Compilation; environment: EnvironmentContext; }) => Promise | void; handler 函数提供以下参数: * `resolveData`:当前模块请求信息,详情可参考 [Rspack - resolve 钩子](https://rspack.rs/zh/api/plugin-api/normal-module-factory-hooks#resolve) 。 * `compiler`:Rspack 的 Compiler 对象。 * `compilation`:Rspack 的 Compilation 对象。 * `environment`: 当前构建的 [environment 上下文](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-context) 。 [#](https://rsbuild.rs/zh/plugins/dev/core#apiprocessassets) api.processAssets ------------------------------------------------------------------------------ 在输出产物之前对 assets 进行修改,等价于 Rspack 的 [compilation.hooks.processAssets](https://rspack.rs/zh/api/plugin-api/compilation-hooks#processassets) hook。 * **版本:** `>= 1.0.0` * **类型:** function processAssets( descriptor: ProcessAssetsDescriptor, handler: ProcessAssetsHandler, ): void; `api.processAssets` 接受两个参数: * `descriptor`:一个对象,用于描述 processAssets 触发的 stage 和匹配条件。 * `handler`:一个回调函数,接收 assets 对象并允许你修改它。 ### [#](https://rsbuild.rs/zh/plugins/dev/core#%E7%A4%BA%E4%BE%8B-2) 示例 * 在 `additional` 阶段输出一个新的 asset: api.processAssets( { stage: 'additional' }, ({ assets, sources, compilation }) => { const source = new sources.RawSource('This is a new asset!'); compilation.emitAsset('new-asset.txt', source); }, ); * 更新一个已经存在的 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); }, ); * 移除一个 asset: api.processAssets({ stage: 'optimize' }, ({ assets, compilation }) => { const assetName = 'unwanted-script.js'; if (assets[assetName]) { compilation.deleteAsset(assetName); } }); ### [#](https://rsbuild.rs/zh/plugins/dev/core#descriptor-%E5%8F%82%E6%95%B0-1) descriptor 参数 descriptor 参数是一个对象,用于描述 processAssets 触发的 stage 和匹配条件。 * **类型:** type ProcessAssetsDescriptor = { stage: ProcessAssetsStage; targets?: RsbuildTarget[]; environments?: string[]; }; descriptor 参数支持设置以下属性: * `stage`:Rspack 内部将 processAssets 划分为多个 stages(参考 [process assets stages](https://rsbuild.rs/zh/plugins/dev/core#process-assets-stages) ,你可以根据需要进行的操作来选择合适的 stage。 api.processAssets({ stage: 'additional' }, ({ assets }) => { // ... }); * `targets`:匹配 Rsbuild [output.target](https://rsbuild.rs/zh/config/output/target) ,仅对匹配的 targets 应用当前 processAssets 函数。 api.processAssets({ stage: 'additional', targets: ['web'] }, ({ assets }) => { // ... }); * `environments`:匹配 Rsbuild [environment](https://rsbuild.rs/zh/guide/advanced/environments) name,仅对匹配的 environments 应用当前 processAssets 函数。 api.processAssets( { stage: 'additional', environments: ['web'] }, ({ assets }) => { // ... }, ); ### [#](https://rsbuild.rs/zh/plugins/dev/core#handler-%E5%8F%82%E6%95%B0-2) handler 参数 handler 参数是一个回调函数,接收一个 assets 对象,并允许你修改它。 * **类型:** type ProcessAssetsHandler = (context: { assets: Record; compiler: Rspack.Compiler; compilation: Rspack.Compilation; environment: EnvironmentContext; sources: RspackSources; }) => Promise | void; handler 函数提供以下参数: * `assets`:一个对象,其中 key 是 asset 的路径名,值是由 [Source](https://github.com/webpack/webpack-sources#source) 表示的 asset 数据。 * `compiler`:Rspack 的 Compiler 对象。 * `compilation`:Rspack 的 Compilation 对象。 * `environment`: 当前构建的 [environment 上下文](https://rsbuild.rs/zh/api/javascript-api/environment-api#environment-context) . * `sources`:[Rspack Sources](https://github.com/webpack/webpack-sources#source) 对象,它包含了多种表示 Sources 的 classes。 ### [#](https://rsbuild.rs/zh/plugins/dev/core#process-assets-stages) Process assets stages 下面是支持的 stage 列表,Rspack 会按由上至下的顺序依次执行这些 stages,请根据你需要进行的操作来选择合适的 stage。 * `additional` — 在编译中添加额外的 asset。 * `pre-process` — asset 进行了基础的预处理。 * `derived` — 从现有 asset 中派生新的 asset。 * `additions` — 为现有的 asset 添加额外的内容,例如 banner 或初始代码。 * `none` — 在 `PROCESS_ASSETS_STAGE_NONE` 阶段运行,不指定专门的处理阶段。 * `optimize` — 以通用的方式优化现有 asset。 * `optimize-count` — 优化现有 asset 的数量,例如,进行合并操作。 * `optimize-compatibility` — 优化现有 asset 的兼容性,例如添加 polyfills 或者 vendor prefixes。 * `optimize-size` — 优化现有 asset 的大小,例如进行压缩或者删除空格。 * `dev-tooling` — 为 asset 添加开发者工具,例如,提取 source map。 * `optimize-inline` — 将 asset 内联到其他 asset 中来优化现有 asset 数量。 * `summarize` — 整理现有 asset 列表。 * `optimize-hash` — 优化 asset 的 hash 值,例如,生成基于 asset 内容的真实 hash 值。 * `optimize-transfer` — 优化已有 asset 的转换操作,例如对 asset 进行压缩,并作为独立的 asset。 * `analyse` — 分析已有 asset。 * `report` — 创建用于上报的 asset。 [#](https://rsbuild.rs/zh/plugins/dev/core#apiexpose) api.expose ---------------------------------------------------------------- 用于插件间通信。 `api.expose` 可以显式暴露当前插件的一些属性或方法,其他插件可以通过 `api.useExposed` 来获取这些 API。 * **类型:** /** * @param id 唯一标识符,使用 Symbol 可以避免命名冲突 * @param api 需要暴露的属性或方法,建议使用对象格式 * @param options 暴露 API 时使用的选项 */ function expose( id: string | symbol, api: T, options?: { /** * 为指定 environment 注册暴露的 API。 * 如果未设置,则注册为全局 API。 */ environment?: string; }, ): void; * **示例:** const pluginParent = () => ({ name: 'plugin-parent', setup(api) { api.expose('plugin-parent', { value: 1, double: (val: number) => val * 2, }); }, }); Tip 如果 `api.expose` 被多次调用且使用了相同的 `id` 和 `environment`,则后一次调用会覆盖前一次调用暴露的 API。 ### [#](https://rsbuild.rs/zh/plugins/dev/core#environment-%E7%BA%A7%E5%88%AB%E7%9A%84-api) Environment 级别的 API 你可以通过设置 `options.environment`(对应 `config.environments` 的 key)为指定 environment 注册暴露的 API。 当在 environment plugin 中调用 `api.useExposed` 时,Rsbuild 会优先解析同一 environment 注册的 API,如果不存在,则回退到全局 API。 api.expose('my-api', { name: 'web' }, { environment: 'web' }); api.expose('my-api', { name: 'node' }, { environment: 'node' }); 如果未设置 `options.environment`,则 API 会被注册为全局 API,可以作为所有 environment 中插件的 fallback。 [#](https://rsbuild.rs/zh/plugins/dev/core#apiuseexposed) api.useExposed ------------------------------------------------------------------------ 用于插件间通信。 `api.useExposed` 可以获取到其他插件暴露的属性或方法。 * **类型:** /** * @param id 唯一标识符 * @returns 获取的属性或方法 * * 如果当前插件注册在某个 environment 中,Rsbuild 会优先解析同一 * environment 注册的 API,如果不存在,则回退到全局 API。 */ function useExposed(id: string | symbol): T | undefined; * **示例:** 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 } }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/core#%E6%A0%87%E8%AF%86%E7%AC%A6) 标识符 你可以使用 Symbol 作为唯一标识符,从而避免潜在的命名冲突: // 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); } }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/core#%E7%B1%BB%E5%9E%8B%E5%A3%B0%E6%98%8E) 类型声明 你可以通过函数的泛型来声明类型: // pluginParent.ts export type ParentAPI = { // ... }; // pluginChild.ts import type { ParentAPI } from './pluginParent'; const pluginChild = () => ({ name: 'plugin-child', setup(api) { const parentApi = api.useExposed(PARENT_API_ID); if (parentApi) { console.log(parentApi); } }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/core#%E6%89%A7%E8%A1%8C%E9%A1%BA%E5%BA%8F) 执行顺序 在进行插件间通信时,你需要留意插件的执行顺序。 比如,在上面的示例中,如果 `pluginParent` 未注册,或者注册顺序晚于 `pluginChild`,那么 `api.useExposed('plugin-parent')` 会返回一个 `undefined`。 你可以使用插件对象的 `pre`、`post` 选项,以及插件 hook 的 `order` 选项来保证顺序是正确的。 --- # 插件 hooks - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/plugins/dev/hooks.md. 菜单目录 [#](https://rsbuild.rs/zh/plugins/dev/hooks#plugin-hooks) 插件 hooks ================================================================== 复制 Markdown 本章节介绍 Rsbuild 插件可用的 hooks。 [#](https://rsbuild.rs/zh/plugins/dev/hooks#%E6%80%BB%E8%A7%88) 总览 ------------------------------------------------------------------ ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#common-hooks) Common hooks * [modifyRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) :修改传递给 Rsbuild 的配置。 * [modifyEnvironmentConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyenvironmentconfig) : 修改特定 environment 的 Rsbuild 配置。 * [modifyRspackConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrspackconfig) :修改传递给 Rspack 的配置。 * [modifyBundlerChain](https://rsbuild.rs/zh/plugins/dev/hooks#modifybundlerchain) :通过 chain API 修改 Rspack 的配置。 * [modifyHTMLTags](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtmltags) :修改注入到 HTML 中的标签。 * [modifyHTML](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtml) :修改最终的 HTML 内容。 * [onBeforeCreateCompiler](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforecreatecompiler) :在创建 compiler 实例前调用。 * [onAfterCreateCompiler](https://rsbuild.rs/zh/plugins/dev/hooks#onaftercreatecompiler) :在创建 compiler 实例后、执行构建前调用。 * [onBeforeEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforeenvironmentcompile) : 在每次执行单个 environment 的构建前调用。 * [onAfterEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterenvironmentcompile) : 在每次单个 environment 的构建结束后调用。 * [onRestart](https://rsbuild.rs/zh/plugins/dev/hooks#onrestart) :当 dev server 或监听构建被请求重启时调用。 * [onExit](https://rsbuild.rs/zh/plugins/dev/hooks#onexit) :在进程即将退出时调用。 ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#dev-hooks) Dev hooks 在执行 `rsbuild dev` 命令或 `rsbuild.startDevServer()` 方法时调用: * [onBeforeStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartdevserver) :在启动开发服务器前调用。 * [onAfterStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartdevserver) :在启动开发服务器后调用。 * [onBeforeDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforedevcompile) :在每次执行开发环境构建前调用。 * [onAfterDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterdevcompile) :在每次开发模式构建结束后调用。 * [onCloseDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onclosedevserver) :在关闭开发服务器时调用。 ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#build-hooks) Build hooks 在执行 `rsbuild build` 命令或 `rsbuild.build()` 方法时调用: * [onBeforeBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforebuild) :在执行生产模式构建前调用。 * [onAfterBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onafterbuild) :在执行生产模式构建后调用,可以获取到构建结果信息。 * [onCloseBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onclosebuild) :在关闭构建时调用。 ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#preview-hooks) Preview hooks 在执行 `rsbuild preview` 命令或 `rsbuild.preview()` 方法时调用: * [onBeforeStartPreviewServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartpreviewserver) :在启动预览服务器前调用。 * [onAfterStartPreviewServer](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartpreviewserver) :在启动预览服务器后调用。 [#](https://rsbuild.rs/zh/plugins/dev/hooks#hooks-%E9%A1%BA%E5%BA%8F) Hooks 顺序 ------------------------------------------------------------------------------ ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#dev-hooks-1) Dev hooks 执行 `rsbuild dev` 命令或 `rsbuild.startDevServer()` 方法时,Rsbuild 会依次执行以下 hooks: * [modifyRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) * [modifyEnvironmentConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyenvironmentconfig) * [onBeforeStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartdevserver) * [modifyBundlerChain](https://rsbuild.rs/zh/plugins/dev/hooks#modifybundlerchain) * [modifyRspackConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrspackconfig) * [onBeforeCreateCompiler](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforecreatecompiler) * [onAfterCreateCompiler](https://rsbuild.rs/zh/plugins/dev/hooks#onaftercreatecompiler) * [onBeforeDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforedevcompile) * [onBeforeEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforeenvironmentcompile) * [onAfterStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartdevserver) * [modifyHTMLTags](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtmltags) * [modifyHTML](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtml) * [onAfterEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterenvironmentcompile) * [onAfterDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterdevcompile) * [onCloseDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onclosedevserver) * [onExit](https://rsbuild.rs/zh/plugins/dev/hooks#onexit) 当 rebuild 时,以下 hooks 会再次触发: * [onBeforeDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforedevcompile) * [onBeforeEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforeenvironmentcompile) * [modifyHTMLTags](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtmltags) * [modifyHTML](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtml) * [onAfterEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterenvironmentcompile) * [onAfterDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterdevcompile) ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#build-hooks-1) Build hooks 执行 `rsbuild build` 命令或 `rsbuild.build()` 方法时,Rsbuild 会依次执行以下 hooks: * [modifyRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) * [modifyEnvironmentConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyenvironmentconfig) * [modifyBundlerChain](https://rsbuild.rs/zh/plugins/dev/hooks#modifybundlerchain) * [modifyRspackConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrspackconfig) * [onBeforeCreateCompiler](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforecreatecompiler) * [onAfterCreateCompiler](https://rsbuild.rs/zh/plugins/dev/hooks#onaftercreatecompiler) * [onBeforeBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforebuild) * [onBeforeEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforeenvironmentcompile) * [modifyHTMLTags](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtmltags) * [modifyHTML](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtml) * [onAfterEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterenvironmentcompile) * [onAfterBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onafterbuild) * [onCloseBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onclosebuild) * [onExit](https://rsbuild.rs/zh/plugins/dev/hooks#onexit) 当 rebuild 时,以下 hooks 会再次触发: * [onBeforeBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforebuild) * [onBeforeEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforeenvironmentcompile) * [modifyHTMLTags](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtmltags) * [modifyHTML](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtml) * [onAfterEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterenvironmentcompile) * [onAfterBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onafterbuild) ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#preview-hooks-1) Preview hooks 执行 `rsbuild preview` 命令或 `rsbuild.preview()` 方法时,Rsbuild 会依次执行以下 hooks: * [modifyRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) * [modifyEnvironmentConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyenvironmentconfig) * [onBeforeStartPreviewServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartpreviewserver) * [onAfterStartPreviewServer](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartpreviewserver) * [onExit](https://rsbuild.rs/zh/plugins/dev/hooks#onexit) [#](https://rsbuild.rs/zh/plugins/dev/hooks#global-hooks-vs-environment-hooks) Global hooks vs environment hooks ---------------------------------------------------------------------------------------------------------------- 在 Rsbuild 中,有一些插件 hooks 是全局 hooks,这些 hook 的执行往往和 Rsbuild 自身的启动流程或全局逻辑相关,在所有 environment 下共享。如: * `modifyRsbuildConfig` 用来修改 Rsbuild 的基础配置,基础配置最终会和 environment 配置合并; * `onBeforeStartDevServer`、`onAfterStartDevServer` 和 Rsbuild dev server 启动流程相关,所有 environments 共享 Rsbuild 的开发服务器、中间件、WebSocket。 与之对应的,有一些插件 hooks 是和当前 environment 相关的 hook,这些 hook 执行时会带有特定的 environment 上下文,并根据 environment 的不同而触发多次。 ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#global-hooks) Global hooks * [modifyRsbuildConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) * [onBeforeStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartdevserver) * [onBeforeCreateCompiler](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforecreatecompiler) * [onAfterCreateCompiler](https://rsbuild.rs/zh/plugins/dev/hooks#onaftercreatecompiler) * [onAfterStartDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartdevserver) * [onBeforeDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforedevcompile) * [onAfterDevCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterdevcompile) * [onCloseDevServer](https://rsbuild.rs/zh/plugins/dev/hooks#onclosedevserver) * [onBeforeBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforebuild) * [onAfterBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onafterbuild) * [onCloseBuild](https://rsbuild.rs/zh/plugins/dev/hooks#onclosebuild) * [onBeforeStartPreviewServer](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartpreviewserver) * [onAfterStartPreviewServer](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartpreviewserver) * [onRestart](https://rsbuild.rs/zh/plugins/dev/hooks#onrestart) * [onExit](https://rsbuild.rs/zh/plugins/dev/hooks#onexit) ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#environment-hooks) Environment hooks * [modifyEnvironmentConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyenvironmentconfig) * [modifyBundlerChain](https://rsbuild.rs/zh/plugins/dev/hooks#modifybundlerchain) * [modifyRspackConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrspackconfig) * [modifyHTMLTags](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtmltags) * [modifyHTML](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtml) * [onBeforeEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforeenvironmentcompile) * [onAfterEnvironmentCompile](https://rsbuild.rs/zh/plugins/dev/hooks#onafterenvironmentcompile) [#](https://rsbuild.rs/zh/plugins/dev/hooks#callback-order) 回调函数顺序 ------------------------------------------------------------------ ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#%E9%BB%98%E8%AE%A4%E8%A1%8C%E4%B8%BA) 默认行为 如果多个插件注册了相同的 hook,那么 hook 的回调函数会按照注册时的顺序执行。 在以下例子中,控制台会依次输出 `'1'` 和 `'2'`: const plugin1 = () => ({ setup(api) { api.modifyRsbuildConfig(() => console.log('1')); }, }); const plugin2 = () => ({ setup(api) { api.modifyRsbuildConfig(() => console.log('2')); }, }); rsbuild.addPlugins([plugin1, plugin2]); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#order-%E5%AD%97%E6%AE%B5) order 字段 在注册 hook 时,可以通过 `order` 字段来声明 hook 的顺序。 type HookDescriptor any> = { handler: T; order: 'pre' | 'post' | 'default'; }; 在以下例子中,控制台会依次输出 `'2'` 和 `'1'`,因为 plugin2 在调用 modifyRsbuildConfig 时设置了 order 为 `pre`。 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]); [#](https://rsbuild.rs/zh/plugins/dev/hooks#common-hooks-1) Common hooks ------------------------------------------------------------------------ ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrsbuildconfig) modifyRsbuildConfig 修改传递给 Rsbuild 的配置项,你可以直接修改传入的 config 对象,也可以返回一个新的对象来替换传入的对象。 Warning `modifyRsbuildConfig` 为全局 hook。如果你希望你开发的插件支持[仅在特定的 environment 下生效](https://rsbuild.rs/zh/guide/advanced/environments#plugins-specified-environment) ,应避免使用 `modifyRsbuildConfig`,可使用 [modifyEnvironmentConfig](https://rsbuild.rs/zh/plugins/dev/hooks#modifyenvironmentconfig) 代替。 * **类型:** type ModifyRsbuildConfigUtils = { mergeRsbuildConfig: typeof mergeRsbuildConfig; }; function ModifyRsbuildConfig( callback: ( config: RsbuildConfig, utils: ModifyRsbuildConfigUtils, ) => MaybePromise, ): void; * **示例:** 为某个配置项设置一个默认值: const myPlugin = () => ({ setup(api) { api.modifyRsbuildConfig((config) => { config.html ||= {}; config.html.title = 'My Default Title'; }); }, }); * **示例:** 通过 `mergeRsbuildConfig` 合并配置多个对象,并返回合并后的对象。 import type { RsbuildConfig } from '@rsbuild/core'; const myPlugin = () => ({ setup(api) { api.modifyRsbuildConfig((userConfig, { mergeRsbuildConfig }) => { const extraConfig: RsbuildConfig = { source: { // ... }, output: { // ... }, }; // extraConfig 会覆盖 userConfig 里的字段, // 如果你不希望覆盖 userConfig,可以调整为 `mergeRsbuildConfig(extraConfig, userConfig)` return mergeRsbuildConfig(userConfig, extraConfig); }); }, }); Tip `modifyRsbuildConfig` 不能用于注册额外的 Rsbuild 插件。这是因为在执行 `modifyRsbuildConfig` 时,Rsbuild 已经初始化了所有插件,并开始执行 hooks 的回调函数。详情可参考 [插件注册时机](https://rsbuild.rs/zh/config/plugins#plugin-registration-phase) 。 ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#modifyenvironmentconfig) modifyEnvironmentConfig 修改特定 environment 的 Rsbuild 配置。 在回调函数中,入参里的 config 对象已经合并了公共的 Rsbuild 配置,你可以直接修改这个 config 对象,也可以返回一个新的对象来替换它。 * **类型:** type ArrayAtLeastOne = [A, ...Array] | [...Array, A]; type ModifyEnvironmentConfigUtils = { /** 当前 environment 名称 */ name: string; mergeEnvironmentConfig: ( ...configs: ArrayAtLeastOne ) => MergedEnvironmentConfig; }; function ModifyEnvironmentConfig( callback: ( config: MergedEnvironmentConfig, utils: ModifyEnvironmentConfigUtils, ) => MaybePromise, ): void; * **示例:** 为指定 environment 的 Rsbuild config 设置一个默认值: const myPlugin = () => ({ setup(api) { api.modifyEnvironmentConfig((config, { name }) => { if (name !== 'web') { return config; } config.html.title = 'My Default Title'; }); }, }); * **示例:** 通过 `mergeEnvironmentConfig` 合并配置多个对象,并返回合并后的对象。 import type { EnvironmentConfig } from '@rsbuild/core'; const myPlugin = () => ({ setup(api) { api.modifyEnvironmentConfig((userConfig, { mergeEnvironmentConfig }) => { const extraConfig: EnvironmentConfig = { source: { // ... }, output: { // ... }, }; // extraConfig 会覆盖 userConfig 里的字段 // 如果你不希望覆盖 userConfig,可以调整为 `mergeEnvironmentConfig(extraConfig, userConfig)` return mergeEnvironmentConfig(userConfig, extraConfig); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#modifyrspackconfig) modifyRspackConfig 修改 Rspack 配置,你可以直接修改传入的 config 对象,也可以返回一个新的对象来替换传入的对象。 Tip `modifyRspackConfig` 的执行时机早于 [tools.rspack](https://rsbuild.rs/zh/config/tools/rspack) 。因此,无法在 `modifyRspackConfig` 中获取到 `tools.rspack` 所做的修改。 * **类型:** type ModifyRspackConfigUtils = { environment: EnvironmentContext; environments: Record; env: string; isDev: boolean; isProd: boolean; target: RsbuildTarget; isServer: boolean; isWebWorker: boolean; CHAIN_ID: ChainIdentifier; rspack: typeof import('@rspack/core').rspack; HtmlPlugin: typeof import('html-rspack-plugin'); // more... }; function ModifyRspackConfig( callback: ( config: Rspack.Configuration, utils: ModifyRspackConfigUtils, ) => MaybePromise, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.modifyRspackConfig((config, utils) => { if (utils.env === 'development') { config.devtool = 'eval-cheap-source-map'; } }); }, }); 回调函数的第二个参数 `utils` 是一个对象,包含了一些工具函数和属性,详见 [tools.rspack - 工具对象](https://rsbuild.rs/zh/config/tools/rspack#utils) 。 ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#modifybundlerchain) modifyBundlerChain [rspack-chain](https://github.com/rstackjs/rspack-chain) 是一个用于配置 Rspack 的工具库。它提供了链式 API,使得配置 Rspack 变得更加灵活。通过使用 `rspack-chain`,你可以更方便地修改和扩展 Rspack 配置,而不需要直接操作复杂的配置对象。 `modifyBundlerChain` 允许你使用 `rspack-chain` API 来修改 Rspack 的配置,它的用法与 [tools.bundlerChain](https://rsbuild.rs/zh/config/tools/bundler-chain) 相同。 * **类型:** type ModifyBundlerChainUtils = { environment: EnvironmentContext; environments: Record; env: string; isDev: boolean; isProd: boolean; target: RsbuildTarget; isServer: boolean; isWebWorker: boolean; CHAIN_ID: ChainIdentifier; rspack: typeof import('@rspack/core').rspack; HtmlPlugin: typeof import('html-rspack-plugin'); /** @deprecated 请使用 `rspack` */ bundler: typeof import('@rspack/core').rspack; }; function ModifyBundlerChain( callback: ( chain: RspackChain, utils: ModifyBundlerChainUtils, ) => Promise | void, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.modifyBundlerChain((chain, utils) => { if (utils.env === 'development') { chain.devtool('eval'); } chain .plugin('circular-dependency') .use(utils.rspack.CircularDependencyRspackPlugin); }); }, }); 回调函数的第二个参数 `utils` 是一个对象,包含了一些工具函数和属性,详见 [tools.bundlerChain - 工具对象](https://rsbuild.rs/zh/config/tools/bundler-chain#utils) 。 ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtml) modifyHTML 修改最终的 HTML 内容。该钩子接收一个 HTML 字符串和上下文对象,你可以返回一个新的 HTML 字符串来替换原始内容。 这个钩子在 [modifyHTMLTags](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtmltags) 钩子之后触发。 * **类型:** type Context = { /** * Rspack 的 Compiler 对象 */ compiler: Rspack.Compiler; /** * Rspack 的 Compilation 对象 */ compilation: Rspack.Compilation; /** * HTML 文件的名称,相对于 dist 目录 * @example 'index.html' */ filename: string; /** * 当前构建的 environment 上下文 */ environment: EnvironmentContext; }; function ModifyHTML( callback: (html: string, context: Context) => MaybePromise, ): void; * **版本:** 添加于 v1.3.15 * **示例:** const myPlugin = () => ({ setup(api) { api.modifyHTML((html) => { return html.replace('foo', 'bar'); }); }, }); 基于 `filename` 来修改 HTML 内容: const myPlugin = () => ({ setup(api) { api.modifyHTML((html, { filename }) => { if (filename === 'foo.html') { return html.replace('foo', 'bar'); } return html; }); }, }); 与直接操作 HTML 字符串相比,你可以借助 [cheerio](https://github.com/cheeriojs/cheerio) 或 [htmlparser2](https://github.com/fb55/htmlparser2) 等库来更便捷地修改 HTML 内容。 以 `cheerio` 为例,它提供了类似 jQuery 的 API 来操作 HTML: import cheerio from 'cheerio'; const myPlugin = () => ({ setup(api) { api.modifyHTML((html) => { const $ = cheerio.load(html); $('h2.title').text('Hello there!'); $('h2').addClass('welcome'); return $.html(); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtmltags) modifyHTMLTags 修改注入到 HTML 中的标签。 * **类型:** type HtmlBasicTag = { // 标签名 tag: string; // 标签的属性 attrs?: Record; // 标签的 innerHTML children?: string; // 额外的元信息 metadata?: Record; }; type HTMLTags = { // 插入到 的标签组 headTags: HtmlBasicTag[]; // 插入到 的标签组 bodyTags: HtmlBasicTag[]; }; type Context = { /** * Rspack 的 Compiler 对象 */ compiler: Rspack.Compiler; /** * Rspack 的 Compilation 对象 */ compilation: Rspack.Compilation; /** * 静态资源的 URL 前缀 * @example 'https://example.com/' */ assetPrefix: string; /** * HTML 文件的名称,相对于 dist 目录 * @example 'index.html' */ filename: string; /** * 当前构建的 environment 上下文 */ environment: EnvironmentContext; }; function ModifyHTMLTags( callback: (tags: HTMLTags, context: Context) => MaybePromise, ): void; * **示例:** const tagsPlugin = () => ({ name: 'tags-plugin', setup(api) { api.modifyHTMLTags(({ headTags, bodyTags }) => { // 在 中插入一个标签,位于其他标签之前 headTags.unshift({ tag: 'script', attrs: { src: 'https://example.com/foo.js' }, }); // 在 中插入一个标签,位于其他标签之后 headTags.push({ tag: 'script', attrs: { src: 'https://example.com/bar.js' }, }); // 在 中插入一个标签,位于其他标签之前 bodyTags.unshift({ tag: 'div', children: 'before other body tags', }); // 在 中插入一个标签,位于其他标签之后 bodyTags.push({ tag: 'div', children: 'after other body tags', }); return { headTags, bodyTags }; }); }, }); 查看 [html.tags](https://rsbuild.rs/zh/config/html/tags) 了解如何定义标签。 Tip 当同时使用 `modifyHTML`,`modifyHTMLTags` 和 `html.tags` 选项时,执行顺序如下: 1. [modifyHTMLTags](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtmltags) 2. [html.tags](https://rsbuild.rs/zh/config/html/tags) 3. [modifyHTML](https://rsbuild.rs/zh/plugins/dev/hooks#modifyhtml) ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforecreatecompiler) onBeforeCreateCompiler `onBeforeCreateCompiler` 是在创建 Rspack Compiler 实例前触发的回调函数,当你执行 `rsbuild.startDevServer`、`rsbuild.build` 或 `rsbuild.createCompiler` 时,都会调用此钩子。 你可以通过 `bundlerConfigs` 参数获取到 Rspack 配置数组,数组中可能包含一份或多份 [Rspack 配置](https://rspack.rs/zh/config/) ,这取决于是否配置了多个 [environments](https://rsbuild.rs/zh/config/environments) 。 * **类型:** function OnBeforeCreateCompiler( callback: (params: { bundlerConfigs: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onBeforeCreateCompiler(({ bundlerConfigs }) => { console.log('the bundler configs are ', bundlerConfigs); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onaftercreatecompiler) onAfterCreateCompiler `onAfterCreateCompiler` 是在创建 Rspack Compiler 实例后、执行构建前触发的回调函数,当你执行 `rsbuild.startDevServer`、`rsbuild.build` 或 `rsbuild.createCompiler` 时,都会调用此钩子。 你可以通过 `compiler` 参数获取到 [Compiler 实例对象](https://rspack.rs/zh/api/javascript-api/compiler) : * **类型:** function OnAfterCreateCompiler( callback: (params: { compiler: Compiler | MultiCompiler; environments: Record; }) => Promise | void, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onAfterCreateCompiler(({ compiler }) => { console.log('the compiler is ', compiler); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforeenvironmentcompile) onBeforeEnvironmentCompile `onBeforeEnvironmentCompile` 是在执行单个 environment 的构建前触发的回调函数。 你可以通过 `bundlerConfig` 参数获取到当前 environment 对应的 [Rspack 配置](https://rspack.rs/zh/config/) 。 另外,你可以通过 `isWatch` 判断是否是 dev 或者 build watch 模式,并在 watch 模式下通过 `isFirstCompile` 来判断是否为首次构建。 * **类型:** function OnBeforeEnvironmentCompile( callback: (params: { isWatch: boolean; isFirstCompile: boolean; bundlerConfig?: Rspack.Configuration; environment: EnvironmentContext; }) => Promise | void, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onBeforeEnvironmentCompile(({ bundlerConfig, environment }) => { console.log( `the bundler config for the ${environment.name} is `, bundlerConfig, ); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onafterenvironmentcompile) onAfterEnvironmentCompile `onAfterEnvironmentCompile` 是在执行单个 environment 的构建后触发的回调函数,你可以通过 [stats](https://rspack.rs/zh/api/javascript-api/stats) 参数获取到构建结果信息。 另外,你可以通过 `isWatch` 判断是否是 dev 或者 build watch 模式,并通过 `isFirstCompile` 来判断是否为首次构建。 * **类型:** function OnAfterEnvironmentCompile( callback: (params: { isFirstCompile: boolean; isWatch: boolean; stats?: Stats; environment: EnvironmentContext; /** * The time it takes to build the current environment in milliseconds. */ time: number; }) => Promise | void, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onAfterEnvironmentCompile(({ isFirstCompile, stats }) => { console.log(stats?.toJson(), isFirstCompile); }); }, }); [#](https://rsbuild.rs/zh/plugins/dev/hooks#build-hooks-2) Build hooks ---------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforebuild) onBeforeBuild `onBeforeBuild` 是在执行生产模式构建前触发的回调函数。 你可以通过 `bundlerConfigs` 参数获取到 Rspack 配置数组,数组中可能包含一份或多份 [Rspack 配置](https://rspack.rs/zh/config/) ,这取决于是否配置了多个 [environments](https://rsbuild.rs/zh/config/environments) 。 另外,你可以通过 `isWatch` 判断是否是 watch 模式,并在 watch 模式下通过 `isFirstCompile` 来判断是否为首次构建。 * **类型:** function OnBeforeBuild( callback: (params: { isWatch: boolean; isFirstCompile: boolean; bundlerConfigs?: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onBeforeBuild(({ bundlerConfigs }) => { console.log('the bundler configs are ', bundlerConfigs); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onafterbuild) onAfterBuild `onAfterBuild` 是在执行生产模式构建后触发的回调函数,你可以通过 [stats](https://rspack.rs/zh/api/javascript-api/stats) 参数获取到构建结果信息。 另外,你可以通过 `isWatch` 判断是否是 watch 模式,并在 watch 模式下通过 `isFirstCompile` 来判断是否为首次构建。 * **类型:** function OnAfterBuild( callback: (params: { isFirstCompile: boolean; isWatch: boolean; stats?: Stats | MultiStats; environments: Record; }) => Promise | void, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onAfterBuild(({ isFirstCompile, stats }) => { console.log(stats?.toJson(), isFirstCompile); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onclosebuild) onCloseBuild 在关闭构建时调用,可用于在构建关闭时执行清理操作。 Rsbuild CLI 会在执行 [rsbuild build](https://rsbuild.rs/zh/guide/basic/cli#rsbuild-build) 完成后自动调用此钩子,使用 JavaScript API 的用户需要手动调用 [build.close()](https://rsbuild.rs/zh/api/javascript-api/instance#close-build) 方法来触发此钩子。 * **类型:** function onCloseBuild(callback: () => Promise | void): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onCloseBuild(() => { console.log('close build!'); }); }, }); [#](https://rsbuild.rs/zh/plugins/dev/hooks#dev-hooks-2) Dev hooks ------------------------------------------------------------------ ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartdevserver) onBeforeStartDevServer 在启动开发服务器前调用。 通过 `server` 参数可以获取到开发服务器实例,参考 [Server API](https://rsbuild.rs/zh/api/javascript-api/server-api) 了解更多。 * **类型:** type MaybePromise = T | Promise; type OnBeforeStartDevServerFn = (params: { /** * The dev server instance, the same as the return value of `createDevServer`. */ server: RsbuildDevServer; /** * Context information for all environments. */ environments: Record; }) => MaybePromise<(() => MaybePromise) | void>; function OnBeforeStartDevServer(callback: OnBeforeStartDevServerFn): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onBeforeStartDevServer(({ server, environments }) => { console.log('before starting dev server.'); console.log('the server is ', server); console.log('the environments contexts are: ', environments); }); }, }); #### [#](https://rsbuild.rs/zh/plugins/dev/hooks#%E6%B3%A8%E5%86%8C%E4%B8%AD%E9%97%B4%E4%BB%B6) 注册中间件 一个常见的使用场景是在 `onBeforeStartDevServer` 中注册自定义的中间件: const myPlugin = () => ({ setup(api) { api.onBeforeStartDevServer(({ server }) => { server.middlewares.use((req, res, next) => { next(); }); }); }, }); 当 `onBeforeStartDevServer` 被调用时,Rsbuild 内置的中间件还未注册,因此你添加的中间件会早于内置中间件执行。 `onBeforeStartDevServer` 允许你返回一个回调函数,当 Rsbuild 内置的中间件注册完成后,会执行你返回的回调函数,在回调函数中注册的中间件会晚于内置中间件执行。 const myPlugin = () => ({ setup(api) { api.onBeforeStartDevServer(({ server }) => { // the returned callback will be called when the default // middlewares are registered return () => { server.middlewares.use((req, res, next) => { next(); }); }; }); }, }); #### [#](https://rsbuild.rs/zh/plugins/dev/hooks#%E4%BF%9D%E5%AD%98-server-%E5%AE%9E%E4%BE%8B) 保存 server 实例 如果你需要在其他 hooks 中访问 `server`,可以通过 `onBeforeStartDevServer` 来存储 `server` 实例,并在执行后续的 hooks 时访问它。注意你不能在执行时机早于 `onBeforeStartDevServer` 的 hooks 中访问 `server`。 import type { RsbuildDevServer } from '@rsbuild/core'; const myPlugin = () => ({ setup(api) { let devServer: RsbuildDevServer | null = null; api.onBeforeStartDevServer(({ server, environments }) => { devServer = server; }); api.transform({ test: /\.foo$/ }, ({ code }) => { if (devServer) { // access server API } return code; }); api.onCloseDevServer(() => { devServer = null; }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartdevserver) onAfterStartDevServer 在启动开发服务器后调用。你可以通过 `port` 参数获得开发服务器监听的端口号,通过 `routes` 获得页面路由信息。 * **类型:** type Routes = Array<{ entryName: string; pathname: string; }>; function OnAfterStartDevServer( callback: (params: { port: number; routes: Routes; environments: Record; }) => Promise | void, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onAfterStartDevServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforedevcompile) onBeforeDevCompile `onBeforeDevCompile` 是在执行开发环境构建前触发的回调函数。 你可以通过 `bundlerConfigs` 参数获取到 Rspack 配置数组,数组中可能包含一份或多份 [Rspack 配置](https://rspack.rs/zh/config/) ,这取决于是否配置了多个 [environments](https://rsbuild.rs/zh/config/environments) 。 另外,你可以通过 `isFirstCompile` 来判断是否为首次构建。 * **类型:** function OnBeforeDevCompile( callback: (params: { isWatch: boolean; isFirstCompile: boolean; bundlerConfigs?: Rspack.Configuration[]; environments: Record; }) => Promise | void, ): void; * **版本:** 新增于 v1.5.0 * **示例:** const myPlugin = () => ({ setup(api) { api.onBeforeDevCompile(({ bundlerConfigs }) => { console.log('the bundler configs are ', bundlerConfigs); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onafterdevcompile) onAfterDevCompile 在每次开发模式构建结束后调用,你可以通过 `isFirstCompile` 来判断是否为首次构建。 * **类型:** function OnAfterDevCompile( callback: (params: { isFirstCompile: boolean; stats: Stats | MultiStats; environments: Record; }) => Promise | void, ): void; Tip `onAfterDevCompile` 钩子在 Rsbuild v1.5.0 中新增。对于之前的版本,你可以使用功能完全相同的 `onDevCompileDone` 钩子。 * **示例:** const myPlugin = () => ({ setup(api) { api.onAfterDevCompile(({ isFirstCompile }) => { if (isFirstCompile) { console.log('first compile!'); } else { console.log('re-compile!'); } }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onclosedevserver) onCloseDevServer 关闭开发服务器时调用,可用于在开发服务器关闭时执行清理操作。 Rsbuild CLI 会自动在合适的时机调用此钩子,使用 JavaScript API 的用户需要手动调用 [server.close()](https://rsbuild.rs/zh/api/javascript-api/instance#close-server) 方法来触发此钩子。 * **类型:** function onCloseDevServer(callback: () => Promise | void): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onCloseDevServer(async () => { console.log('close dev server!'); }); }, }); [#](https://rsbuild.rs/zh/plugins/dev/hooks#preview-hooks-2) Preview hooks -------------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onbeforestartpreviewserver) onBeforeStartPreviewServer 在启动预览服务器前调用。 可以通过 `server` 参数访问预览服务器并注册自定义的中间件。 * **类型:** type MaybePromise = T | Promise; type OnBeforeStartPreviewServerFn = (params: { /** * 预览服务器实例 */ server: RsbuildPreviewServer; /** * 所有 environments 的上下文信息 */ environments: Record; }) => MaybePromise; function OnBeforeStartPreviewServer( callback: OnBeforeStartPreviewServerFn, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onBeforeStartPreviewServer(({ server, environments }) => { console.log('before start!'); console.log('the server is ', server); console.log('the environments contexts are: ', environments); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onafterstartpreviewserver) onAfterStartPreviewServer 在启动预览服务器后调用,你可以通过 `port` 参数获得预览服务器监听的端口号,通过 `routes` 获得页面路由信息。 * **类型:** type Routes = Array<{ entryName: string; pathname: string; }>; function OnAfterStartPreviewServer( callback: (params: { port: number; routes: Routes; environments: Record; }) => Promise | void, ): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onAfterStartPreviewServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); }, }); [#](https://rsbuild.rs/zh/plugins/dev/hooks#other-hooks) Other hooks -------------------------------------------------------------------- ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onrestart) onRestart 当 dev server 或监听构建被请求重启时调用。 该 hook 会在以下情况中触发: * Rsbuild CLI 检测到配置文件或其依赖发生变化。 * [`dev.watchFiles`](https://rsbuild.rs/zh/config/dev/watch-files) 中 `type` 为 `'restart'` 的监听项检测到 `events` 中指定的文件事件。 * 通过 [CLI 快捷键](https://rsbuild.rs/zh/config/dev/cli-shortcuts) 手动重启 dev server。 > 普通的重新构建不会触发该 hook。 使用 JavaScript API 时,`rsbuild.startDevServer()`、`rsbuild.createDevServer()` 和 `rsbuild.build({ watch: true })` 会安装 restart watcher。只有检测到 `events` 中指定的文件事件时才会调用该 hook。默认情况下,Rsbuild 不会关闭或重启当前任务;你可以传入 [`restart` 选项](https://rsbuild.rs/zh/api/javascript-api/core#restart-handling) 来处理重启请求。 * **类型:** type WatchFileEvent = 'add' | 'change' | 'unlink'; type RestartContext = { filePath?: string; event?: WatchFileEvent; } & ( | { action: 'build'; options: BuildOptions; } | { action: 'dev'; options: StartDevServerOptions; } ); function OnRestart( callback: (context: RestartContext) => Promise | void, ): void; * `action`:当前正在重启的 Rsbuild 操作类型。 * `filePath`:触发重启的文件绝对路径,手动触发重启时为 `undefined`。 * `event`:触发重启的文件事件,手动触发重启时为 `undefined`。该属性自 v2.1.8 起可用。 * `options`:当前调用 `rsbuild.build()` 或 `rsbuild.startDevServer()` 时传入的选项。 * **版本:** 新增于 v2.1.7 * **示例:** const myPlugin = () => ({ setup(api) { api.onRestart(async ({ action, event, filePath }) => { console.log('restart!', action, event, filePath); }); }, }); ### [#](https://rsbuild.rs/zh/plugins/dev/hooks#onexit) onExit 在进程即将退出时调用,这个钩子只能执行同步代码。 * **类型:** function OnExit(callback: (context: { exitCode: number }) => void): void; * **示例:** const myPlugin = () => ({ setup(api) { api.onExit(({ exitCode }) => { console.log('exit: ', exitCode); }); }, }); --- # Debug mode - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/debug/debug-mode.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/debug/debug-mode#debug-mode) Debug mode ==================================================================== Copy Markdown Rsbuild provides a debug mode to troubleshoot problems. Add the `DEBUG=rsbuild` environment variable when you run a build to enable it. # Debug in development mode DEBUG=rsbuild pnpm dev # Debug in production mode DEBUG=rsbuild pnpm build In debug mode, Rsbuild prints additional log information and writes the Rsbuild and Rspack configs to the `dist` directory so you can inspect them. [#](https://rsbuild.rs/guide/debug/debug-mode#log-information) Log information ------------------------------------------------------------------------------ In debug mode, the terminal shows logs that start with `rsbuild`, including internal operations and the Rspack version in use. $ DEBUG=rsbuild pnpm dev ... rsbuild 10:00:00 configuration loaded from: /path/to/... rsbuild 10:00:00 registering default plugins rsbuild 10:00:00 default plugins registered ... Rsbuild also prints the following message to indicate that it has written the generated build configurations to disk. Open these files to review the contents. config inspection completed, generated files: - Rsbuild config: /Project/demo/dist/.rsbuild/rsbuild.config.mjs - Rspack config (web): /Project/demo/dist/.rsbuild/rspack.config.web.mjs [#](https://rsbuild.rs/guide/debug/debug-mode#rsbuild-config-file) Rsbuild config file -------------------------------------------------------------------------------------- In debug mode, Rsbuild automatically generates a `dist/.rsbuild/rsbuild.config.mjs` file that contains the final Rsbuild config after the framework finishes processing your settings. The structure of the file is as follows: rsbuild.config.mjs export default { dev: { // some configs... }, source: { // some configs... }, // other configs... }; For a complete introduction to Rsbuild config, please see the [Configure Rsbuild](https://rsbuild.rs/guide/configuration/rsbuild) chapter. [#](https://rsbuild.rs/guide/debug/debug-mode#rspack-config-file) Rspack config file ------------------------------------------------------------------------------------ Rsbuild also creates a `dist/.rsbuild/rspack.config.web.mjs` file with the final Rspack config that Rsbuild passes to Rspack. The structure of the file is as follows: rspack.config.web.mjs export default { resolve: { // some resolve configs... }, module: { // some Rspack loaders... }, plugins: [\ // some Rspack plugins...\ ], // other configs... }; For a complete introduction to Rspack configs, please see [Rspack official documentation](https://rspack.rs/config/) . --- # JSON - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/basic/json-files.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/basic/json-files#json) JSON ======================================================== Copy Markdown Rsbuild supports importing JSON files in code, and also supports importing [YAML](https://yaml.org/) and [TOML](https://toml.io/en/) files, converting them to JSON format. [#](https://rsbuild.rs/guide/basic/json-files#json-file) JSON file ------------------------------------------------------------------ You can import JSON files directly in JavaScript files. ### [#](https://rsbuild.rs/guide/basic/json-files#example) Example example.json { "name": "foo", "items": [1, 2] } index.js import example from './example.json'; console.log(example.name); // 'foo'; console.log(example.items); // [1, 2]; ### [#](https://rsbuild.rs/guide/basic/json-files#named-import) Named import Rsbuild also supports importing JSON files using named imports: import { name } from './example.json'; console.log(name); // 'foo'; [#](https://rsbuild.rs/guide/basic/json-files#yaml-file) YAML file ------------------------------------------------------------------ [YAML](https://yaml.org/) is a data serialization language commonly used for writing configuration files. Rsbuild provides the [@rsbuild/plugin-yaml](https://github.com/rstackjs/rsbuild-plugin-yaml) . After registering the plugin, you can import `.yaml` or `.yml` files in JavaScript and they will be automatically converted to JavaScript objects. rsbuild.config.ts import { pluginYaml } from '@rsbuild/plugin-yaml'; export default { plugins: [pluginYaml()], }; ### [#](https://rsbuild.rs/guide/basic/json-files#example-1) Example example.yaml --- hello: world foo: bar: baz import example from './example.yaml'; console.log(example.hello); // 'world'; console.log(example.foo); // { bar: 'baz' }; [#](https://rsbuild.rs/guide/basic/json-files#toml-file) TOML file ------------------------------------------------------------------ [TOML](https://toml.io/) is a semantically explicit, easy-to-read configuration file format. Rsbuild provides the [@rsbuild/plugin-toml](https://github.com/rstackjs/rsbuild-plugin-toml) . After registering the plugin, you can import `.toml` files in JavaScript and it will be automatically converted to JavaScript objects. rsbuild.config.ts import { pluginToml } from '@rsbuild/plugin-toml'; export default { plugins: [pluginToml()], }; ### [#](https://rsbuild.rs/guide/basic/json-files#example-2) Example example.toml hello = "world" [foo] bar = "baz" import example from './example.toml'; console.log(example.hello); // 'world'; console.log(example.foo); // { bar: 'baz' }; [#](https://rsbuild.rs/guide/basic/json-files#type-declaration) Type declaration -------------------------------------------------------------------------------- When you import YAML or TOML files in TypeScript code, use one of the following methods to add type declarations: * Method 1: If the `@rsbuild/core` package is installed, you can add the [preset types](https://rsbuild.rs/guide/basic/typescript#preset-types) provided by `@rsbuild/core` to `tsconfig.json`: tsconfig.json { "compilerOptions": { "types": ["@rsbuild/core/types"] } } * Method 2: Manually add the required type declarations: src/env.d.ts declare module '*.yaml' { const content: Record; export default content; } declare module '*.yml' { const content: Record; export default content; } declare module '*.toml' { const content: Record; export default content; } --- # Build profiling - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/debug/build-profiling.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/debug/build-profiling#build-profiling) Build profiling =================================================================================== Copy Markdown Running a performance analysis helps you identify bottlenecks in your project so you can optimize the right areas. [#](https://rsbuild.rs/guide/debug/build-profiling#using-rsdoctor) Using Rsdoctor --------------------------------------------------------------------------------- Rsdoctor is a build analyzer that visualizes how long each loader and plugin takes to compile. See [Use Rsdoctor](https://rsbuild.rs/guide/debug/rsdoctor) for more information. [#](https://rsbuild.rs/guide/debug/build-profiling#nodejs-profiling) Node.js profiling -------------------------------------------------------------------------------------- A build runs both JavaScript and Rust code and incurs communication overhead between them. JavaScript overhead is usually higher than Rust overhead. Use Node.js profiling to understand where time is spent in JavaScript and pinpoint bottlenecks. For example, to capture a [CPU profile](https://nodejs.org/docs/v20.17.0/api/cli.html#--cpu-prof) , run the following commands from your project root: # dev node --cpu-prof ./node_modules/@rsbuild/core/bin/rsbuild.js dev # build node --cpu-prof ./node_modules/@rsbuild/core/bin/rsbuild.js build # Set higher precision sampling interval node --cpu-prof --cpu-prof-interval=100 ./node_modules/@rsbuild/core/bin/rsbuild.js build These commands generate a `*.cpuprofile` file. You can use [speedscope](https://github.com/jlfwong/speedscope) to visualize it: # Install speedscope npm install -g speedscope # View cpuprofile content # Replace the name with the local file name speedscope CPU.date.000000.00000.0.001.cpuprofile [#](https://rsbuild.rs/guide/debug/build-profiling#rspack-profiling) Rspack profiling ------------------------------------------------------------------------------------- Set the `RSPACK_PROFILE` environment variable to capture an Rspack build performance profile. package.json { "scripts": { "dev:profile": "RSPACK_PROFILE=OVERVIEW rsbuild", "build:profile": "RSPACK_PROFILE=OVERVIEW rsbuild build" } } Because Windows does not support this syntax, you can use [cross-env](https://npmjs.com/package/cross-env) to set environment variables across different systems: package.json { "scripts": { "dev:profile": "cross-env RSPACK_PROFILE=OVERVIEW rsbuild", "build:profile": "cross-env RSPACK_PROFILE=OVERVIEW rsbuild build" }, "devDependencies": { "cross-env": "^7.0.0" } } By default, Rspack uses the `logger` trace layer and writes the profile output to `.rspack-profile-${timestamp}-${pid}/rspack.log` under the project root. When `RSPACK_TRACE_OUTPUT` is a relative file path, it is resolved inside the generated `.rspack-profile-${timestamp}-${pid}` directory; absolute paths are used as-is. Set `RSPACK_TRACE_OUTPUT=stdout` or `RSPACK_TRACE_OUTPUT=stderr` explicitly if you need terminal output. Tip * When shutting down the dev server, press `CTRL + D` instead of `CTRL + C` so Rspack can finish recording performance data. * For more information about Rspack profiling, refer to [Rspack - Tracing](https://rspack.rs/contribute/development/tracing) . --- # General FAQ - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/faq/general.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/faq/general#general-faq) General FAQ ================================================================= Copy Markdown ### [#](https://rsbuild.rs/guide/faq/general#what-is-the-relationship-between-rsbuild-and-rspack) What is the relationship between Rsbuild and Rspack? Rspack is the underlying bundler for Rsbuild. The goal of Rsbuild is to provide out-of-the-box build capabilities for Rspack users, so developers can start a web project with zero configuration. The main differences between Rspack and Rsbuild are: * Rspack projects need to be configured from scratch, while Rsbuild provides default best practice configurations and supports extending Rspack configurations. * Rspack projects require integration with loaders and plugins from the community to support different scenarios, while Rsbuild provides official plugins and default support for common frontend frameworks and build capabilities. * The capabilities of the Rspack CLI are comparable to the webpack CLI but more streamlined, while Rsbuild provides a more powerful CLI and a more complete dev server. * * * ### [#](https://rsbuild.rs/guide/faq/general#can-rsbuild-be-used-to-build-libraries-or-ui-components) Can Rsbuild be used to build libraries or UI components? Rsbuild is designed for building web applications out of the box. For libraries and UI components, we recommend using [Rslib](https://github.com/web-infra-dev/rslib) , a library development tool based on Rsbuild that reuses Rsbuild's configuration and plugins. --- # Testing - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/advanced/testing.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/advanced/testing#testing) Testing ============================================================== Copy Markdown Rsbuild doesn't include built-in testing frameworks, but integrates seamlessly with popular testing tools. This guide shows how to add [unit testing](https://rsbuild.rs/guide/advanced/testing#unit-testing) and [end-to-end testing](https://rsbuild.rs/guide/advanced/testing#end-to-end-testing) to Rsbuild applications. [#](https://rsbuild.rs/guide/advanced/testing#unit-testing) Unit testing ------------------------------------------------------------------------ Unit tests verify individual components and functions in isolation. Rsbuild can work with testing frameworks like [Rstest](https://rstest.rs/) , [Vitest](https://vitest.dev/) , [Jest](https://jestjs.io/) , and others. The following example uses Rstest to show how to add unit tests to an Rsbuild application. ### [#](https://rsbuild.rs/guide/advanced/testing#rstest) Rstest [Rstest](https://rstest.rs/) is a testing framework built on Rsbuild that provides first-class support for Rsbuild applications. It offers Jest-compatible APIs while natively supporting modern features like TypeScript and ESM. #### [#](https://rsbuild.rs/guide/advanced/testing#installing) Installing npm yarn pnpm bun deno npm add @rstest/core @rstest/adapter-rsbuild -D yarn add @rstest/core @rstest/adapter-rsbuild -D pnpm add @rstest/core @rstest/adapter-rsbuild -D bun add @rstest/core @rstest/adapter-rsbuild -D deno add npm:@rstest/core npm:@rstest/adapter-rsbuild -D #### [#](https://rsbuild.rs/guide/advanced/testing#configuring-scripts) Configuring scripts Add test scripts to your `package.json`: { "scripts": { "test": "rstest", "test:watch": "rstest -w" } } #### [#](https://rsbuild.rs/guide/advanced/testing#writing-tests) Writing tests Create test files, for example: src/utils.ts export function add(a: number, b: number) { return a + b; } src/utils.test.ts import { expect, test } from '@rstest/core'; import { add } from './utils'; test('should add two numbers correctly', () => { expect(add(1, 2)).toBe(3); expect(add(-1, 1)).toBe(0); }); #### [#](https://rsbuild.rs/guide/advanced/testing#running-tests) Running tests # Run tests npm run test # Run and watch npm run test:watch #### [#](https://rsbuild.rs/guide/advanced/testing#configuring-rstest) Configuring Rstest Create an `rstest.config.ts` file in the root of your project, and use [@rstest/adapter-rsbuild](https://rstest.rs/guide/integration/rsbuild#reuse-rsbuild-config) to reuse your existing Rsbuild configuration: rstest.config.ts import { defineConfig } from '@rstest/core'; import { withRsbuildConfig } from '@rstest/adapter-rsbuild'; export default defineConfig({ extends: withRsbuildConfig(), // Additional rstest-specific configuration }); You can add Rstest-specific options in the same configuration file, such as test file matching patterns, setup files, and code coverage. These are the basic steps for using Rstest. Check the [Rstest documentation](https://rstest.rs/guide/start/) for more usage details. ### [#](https://rsbuild.rs/guide/advanced/testing#examples) Examples The [rstack-examples](https://github.com/rstackjs/rstack-examples/tree/main/rstest) repository includes a collection of Rstest examples that demonstrate common usage patterns and practices. [#](https://rsbuild.rs/guide/advanced/testing#end-to-end-testing) End-to-end testing ------------------------------------------------------------------------------------ End-to-end testing validates complete user workflows, ensuring your application functions correctly in real browser environments. For E2E testing, we recommend Playwright, a modern end-to-end testing framework. See the [Playwright documentation](https://playwright.dev/docs/intro) for details. --- # Glossary - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/start/glossary.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/start/glossary#glossary) Glossary ============================================================== Copy Markdown [#](https://rsbuild.rs/guide/start/glossary#bundler) Bundler ------------------------------------------------------------ Module bundlers like [Rspack](https://rspack.rs/) and [webpack](https://webpack.js.org/) . The main goal of bundlers is to combine JavaScript, CSS, and other files so the output can run in the browser, Node.js, or other environments. When bundlers process web applications, they build a dependency graph and combine each module into one or more bundles. [#](https://rsbuild.rs/guide/start/glossary#csr) CSR ---------------------------------------------------- CSR stands for "Client-Side Rendering". It means the page is rendered in the browser using JavaScript, and logic such as data fetching, templates, and routing runs on the client rather than the server. In CSR, the server sends an empty HTML shell and JavaScript to the browser, and the browser fetches data from the server's API and renders dynamic content. [#](https://rsbuild.rs/guide/start/glossary#environment) Environment -------------------------------------------------------------------- The runtime environment for build outputs. See [Multi-environment builds](https://rsbuild.rs/guide/advanced/environments) . [#](https://rsbuild.rs/guide/start/glossary#micro-frontend) Micro-frontend -------------------------------------------------------------------------- Micro-frontend (MFE) is an architecture style similar to microservices. It is composed of multiple independently delivered frontend applications that form a cohesive whole. MFE decomposes frontend applications into smaller, simpler applications that can be developed, tested, and deployed independently while still appearing as a single product to users. It primarily solves two problems: * Maintaining large, complex applications becomes difficult over time. * Cross-team collaboration becomes inefficient. [#](https://rsbuild.rs/guide/start/glossary#modernjs) Modern.js --------------------------------------------------------------- [Modern.js](https://github.com/web-infra-dev/modern.js) is an open-source web engineering system from ByteDance that provides multiple solutions to help developers solve problems in different development scenarios. [#](https://rsbuild.rs/guide/start/glossary#module-federation) Module Federation -------------------------------------------------------------------------------- Module Federation is an architectural pattern for JavaScript application decomposition (similar to microservices on the server-side), allowing you to share code and resources between multiple JavaScript applications (or micro-frontends). See [Module Federation](https://rsbuild.rs/guide/advanced/module-federation) for more details. [#](https://rsbuild.rs/guide/start/glossary#rspack) Rspack ---------------------------------------------------------- [Rspack](https://rspack.rs/) is a high-performance JavaScript bundler written in Rust. It offers strong compatibility with the webpack ecosystem, so it can replace webpack seamlessly while delivering lightning-fast build speeds. [#](https://rsbuild.rs/guide/start/glossary#rspress) Rspress ------------------------------------------------------------ [Rspress](https://github.com/web-infra-dev/rspress) is a fast static site generator based on Rsbuild. [#](https://rsbuild.rs/guide/start/glossary#ssr) SSR ---------------------------------------------------- SSR stands for "Server-Side Rendering". It means that the HTML of the web page is generated by the server and sent to the client, rather than sending only an empty HTML shell and relying on JavaScript to generate the page content. See [Server-side rendering (SSR)](https://rsbuild.rs/guide/advanced/ssr) for more details. [#](https://rsbuild.rs/guide/start/glossary#swc) SWC ---------------------------------------------------- SWC (Speedy Web Compiler) is a transformer and minifier for JavaScript and TypeScript written in Rust. See [Configure SWC](https://rsbuild.rs/guide/configuration/swc) for more details. [#](https://rsbuild.rs/guide/start/glossary#more) More ------------------------------------------------------ See additional glossary terms in [Rspack - Glossary](https://rspack.rs/misc/glossary) . --- # Wasm - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/basic/wasm-assets.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/basic/wasm-assets#wasm) Wasm ========================================================= Copy Markdown Rsbuild provides native support for WebAssembly (WASM) modules, allowing you to import and use `.wasm` files directly in your project. What is WebAssembly WebAssembly (Wasm) is a portable, high-performance binary format designed to execute CPU-intensive computing tasks in modern web browsers, bringing near-native performance and reliability to the web platform. [#](https://rsbuild.rs/guide/basic/wasm-assets#import) Import ------------------------------------------------------------- You can reference a WebAssembly module in a JavaScript file using named imports: index.js import { add } from './add.wasm'; console.log(add); // [native code] console.log(add(1, 2)); // 3 WebAssembly modules can also be imported via dynamic import: index.js import('./add.wasm').then(({ add }) => { console.log('---- Async Wasm Module'); console.log(add); // [native code] console.log(add(1, 2)); // 3 }); You can also get the path of a WebAssembly module using the `new URL` syntax: index.js const wasmURL = new URL('./add.wasm', import.meta.url); console.log(wasmURL.pathname); // "/static/wasm/[contenthash:10].module.wasm" [#](https://rsbuild.rs/guide/basic/wasm-assets#source-import) Source import --------------------------------------------------------------------------- You can use [Source Phase Imports](https://github.com/tc39/proposal-source-phase-imports) to get a compiled `WebAssembly.Module` instead of the module exports: index.js import source wasmModule from './add.wasm'; const instance = await WebAssembly.instantiate(wasmModule); const { add } = instance.exports; console.log(add(1, 2)); // 3 This is useful when you need to instantiate a Wasm module yourself, create multiple instances with different imports, or transfer the module to a worker. Tip `import source` is supported in Rsbuild v2.1.0 and later. [#](https://rsbuild.rs/guide/basic/wasm-assets#output-directory) Output directory --------------------------------------------------------------------------------- When you import a `.wasm` asset, Rsbuild outputs it to the `dist/static/wasm` directory by default. You can change the output directory for `.wasm` files using the [output.distPath](https://rsbuild.rs/config/output/dist-path) configuration: export default { output: { distPath: { wasm: 'resource/wasm', }, }, }; [#](https://rsbuild.rs/guide/basic/wasm-assets#type-declaration) Type declaration --------------------------------------------------------------------------------- When you import a WebAssembly file in TypeScript code, you usually need to add the corresponding type declaration. For example, if the `add.wasm` file exports an `add()` method, you can create an `add.wasm.d.ts` file in the same directory and add the corresponding type declaration: add.wasm.d.ts export const add: (num1: number, num2: number) => number; --- # Use Rsdoctor - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/debug/rsdoctor.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/debug/rsdoctor#use-rsdoctor) Use Rsdoctor ====================================================================== Copy Markdown [Rsdoctor](https://rsdoctor.rs/) is a build analyzer tailored for the Rspack ecosystem. Rsdoctor aims to be a one-stop, intelligent build analyzer that makes the build process transparent, predictable, and optimizable through visualization and smart analysis, helping teams pinpoint bottlenecks, improve performance, and raise engineering quality. Use Rsdoctor to debug build outputs or the build process. [#](https://rsbuild.rs/guide/debug/rsdoctor#quick-start) Quick start -------------------------------------------------------------------- In an Rsbuild project, enable Rsdoctor as follows: 1. Install the Rsdoctor plugin: npm yarn pnpm bun deno npm add @rsdoctor/rspack-plugin -D yarn add @rsdoctor/rspack-plugin -D pnpm add @rsdoctor/rspack-plugin -D bun add @rsdoctor/rspack-plugin -D deno add npm:@rsdoctor/rspack-plugin -D 2. Set the `RSDOCTOR=true` environment variable before running the CLI command: package.json { "scripts": { "dev:rsdoctor": "RSDOCTOR=true rsbuild", "build:rsdoctor": "RSDOCTOR=true rsbuild build" } } Because Windows does not support this syntax, you can use [cross-env](https://npmjs.com/package/cross-env) to set environment variables across different systems: package.json { "scripts": { "dev:rsdoctor": "cross-env RSDOCTOR=true rsbuild", "build:rsdoctor": "cross-env RSDOCTOR=true rsbuild build" }, "devDependencies": { "cross-env": "^7.0.0" } } After running these scripts, Rsbuild automatically registers the Rsdoctor plugin and opens the build analysis page when the build finishes. See the [Rsdoctor documentation](https://rsdoctor.rs/) for all features. [#](https://rsbuild.rs/guide/debug/rsdoctor#options) Options ------------------------------------------------------------ To configure the [options](https://rsdoctor.rs/config/options/options) exposed by the Rsdoctor plugin, manually register the plugin: rsbuild.config.ts import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default { tools: { rspack: { plugins: [\ process.env.RSDOCTOR === 'true' &&\ new RsdoctorRspackPlugin({\ // plugin options\ }),\ ], }, }, }; --- # Module Federation - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/advanced/module-federation.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/advanced/module-federation#module-federation) Module Federation ============================================================================================ Copy Markdown Module Federation is an architectural pattern for decomposing JavaScript applications. Similar to server-side microservices, it lets multiple JavaScript applications (or micro-frontends) share code and resources. The Rspack team works closely with the Module Federation maintainers to deliver first-class support. [#](https://rsbuild.rs/guide/advanced/module-federation#use-cases) Use cases ---------------------------------------------------------------------------- Module Federation has several typical use cases, including: * Allowing independent applications (called "micro-frontends" in micro-frontend architecture) to share modules without recompiling the entire application. * Enabling different teams to work on different parts of the same application without needing to recompile the entire application. * Providing dynamic code loading and sharing between applications at runtime. Module Federation can help you: * Reduce code duplication * Improve code maintainability * Reduce the overall size of applications * Improve application performance [#](https://rsbuild.rs/guide/advanced/module-federation#how-to-use) How to use ------------------------------------------------------------------------------ Module Federation (MF) currently offers multiple major versions; choose the one that fits your needs. The key characteristics of each version are: | Version | Description | Features | Use Cases | | --- | --- | --- | --- | | MF v2.0 | Enhanced version of Module Federation, built on Module Federation v1.5 | \- Provides additional out-of-the-box features such as dynamic TS type hints, Chrome DevTools, preloading, etc.
\- Better suited for micro-frontend architecture supporting large-scale web applications
\- Includes all features of Module Federation 1.5 | Projects that need MF 2.0's advanced capabilities | | MF v1.5 | Version built into Rspack | \- Supports module export, module loading, dependency sharing capabilities of Module Federation v1.0
\- Added runtime plugin functionality, enabling users to extend the behavior and functionality of module federation | Projects that don't need the extra capabilities of MF 2.0 | ### [#](https://rsbuild.rs/guide/advanced/module-federation#module-federation-v20) Module Federation v2.0 [Module Federation 2.0](https://module-federation.io/blog/announcement.html) provides additional out-of-the-box features based on Module Federation, such as dynamic TS type hints, Chrome DevTools, Runtime plugins, and preloading, making it better suited for large-scale micro-frontend architectures. You need to install the additional [@module-federation/rsbuild-plugin](https://npmjs.com/package/@module-federation/rsbuild-plugin) plugin to use Module Federation v2.0. rsbuild.config.ts import { pluginModuleFederation } from '@module-federation/rsbuild-plugin'; export default defineConfig({ plugins: { pluginModuleFederation({ name: 'remote', // other options }), }, }); Please refer to the [Module Federation v2.0 official documentation](https://module-federation.io/) for detailed usage. ### [#](https://rsbuild.rs/guide/advanced/module-federation#module-federation-v15) Module Federation v1.5 This is the version built into Rspack. In addition to supporting Module Federation v1.0's capabilities such as module export, module loading, and dependency sharing, it also adds runtime plugin functionality, letting you extend the behavior and functionality of module federation. You can enable it through Rsbuild's [moduleFederation.options](https://rsbuild.rs/config/module-federation/options) without installing additional plugins. rsbuild.config.ts export default defineConfig({ moduleFederation: { options: { name: 'remote', // other options }, }, }); [#](https://rsbuild.rs/guide/advanced/module-federation#example-repositories) Example repositories -------------------------------------------------------------------------------------------------- Rsbuild provides Module Federation example projects you can explore: * [Module Federation v2.0 Example](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/module-federation-enhanced) * [Module Federation v1.5 Example](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/module-federation) [#](https://rsbuild.rs/guide/advanced/module-federation#limitations) Limitations -------------------------------------------------------------------------------- Module Federation is currently incompatible with [output.module](https://rsbuild.rs/config/output/module) . The Module Federation runtime does not yet support ESM output. Avoid setting `output.module: true` in a Module Federation application; otherwise, loading may fail at runtime. --- # Upgrading Rsbuild - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/upgrade/upgrade-rsbuild.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/upgrade/upgrade-rsbuild#upgrading-rsbuild) Upgrading Rsbuild ========================================================================================= Copy Markdown This section explains how to upgrade your project's Rsbuild dependencies to the latest version. Tip See [npm - @rsbuild/core](https://npmjs.com/package/@rsbuild/core) to view the latest version. [#](https://rsbuild.rs/guide/upgrade/upgrade-rsbuild#semantic-versioning) Semantic versioning --------------------------------------------------------------------------------------------- Rsbuild follows the [Semantic Versioning](https://semver.org/) specification. * Major version: contains incompatible API changes. * Minor version: contains backward compatible features and fixes. * Patch version: contains backward compatible bug fixes. [#](https://rsbuild.rs/guide/upgrade/upgrade-rsbuild#changelog) Changelog ------------------------------------------------------------------------- Visit [GitHub - release](https://github.com/web-infra-dev/rsbuild/releases) to view the changes for each version of Rsbuild. [#](https://rsbuild.rs/guide/upgrade/upgrade-rsbuild#using-taze) Using taze --------------------------------------------------------------------------- We recommend using [Taze](https://github.com/antfu-collective/taze) to upgrade the Rsbuild version. Taze is a CLI tool for updating npm dependencies. ### [#](https://rsbuild.rs/guide/upgrade/upgrade-rsbuild#usage) Usage Run the following command to upgrade all dependencies that include `rsbuild` in their names: npx taze --include /rsbuild/ -w The result will look similar to: rsbuild - 3 patch @rsbuild/core dev ~1mo ^1.0.0 → ^1.2.0 @rsbuild/plugin-react dev ~1mo ^1.0.0 → ^1.2.0 @rsbuild/plugin-type-check dev ~1mo ^1.0.0 → ^1.2.0 ℹ changes written to package.json, run npm i to install updates. You can also adjust the `include` pattern to match specific packages. For example, to upgrade only packages under the `@rsbuild` scope: npx taze --include /@rsbuild/ -w ### [#](https://rsbuild.rs/guide/upgrade/upgrade-rsbuild#options) Options Here are some examples of using Taze options: * In a monorepo, you can add the `-r` option to upgrade recursively: npx taze --include /rsbuild/ -w -r * Add `-l` to upgrade locked versions: npx taze --include /rsbuild/ -w -l * To upgrade to a major version: npx taze major --include /rsbuild/ -w > For more options, please refer to the [taze documentation](https://github.com/antfu-collective/taze) > . --- # Logging - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/advanced/logging.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/advanced/logging#logging) Logging ============================================================== Copy Markdown This guide explains how to control Rsbuild log output, customize the logger for a specific instance, and access the logger in different scenarios. > Rsbuild's logger is based on `rslog`. See [rslog](https://github.com/rstackjs/rslog) > for more methods and options. [#](https://rsbuild.rs/guide/advanced/logging#log-levels) Log levels -------------------------------------------------------------------- ### [#](https://rsbuild.rs/guide/advanced/logging#nodejs-side) Node.js side [logLevel](https://rsbuild.rs/config/log-level) controls the log level of the current Rsbuild instance on the Node.js side, such as build logs in the terminal, dev server logs, and plugin logs. For example, when `logLevel` is set to `warn`, Rsbuild only outputs warning and error logs: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; export default defineConfig({ logLevel: 'warn', }); ### [#](https://rsbuild.rs/guide/advanced/logging#browser-side) Browser side [dev.client.logLevel](https://rsbuild.rs/config/dev/client#loglevel) controls the client log level shown in the browser console. By default, `dev.client.logLevel` inherits the root [logLevel](https://rsbuild.rs/config/log-level) . rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; export default defineConfig({ dev: { client: { logLevel: 'warn', }, }, }); [#](https://rsbuild.rs/guide/advanced/logging#custom-logger) Custom logger -------------------------------------------------------------------------- Each Rsbuild instance creates its own logger when it is initialized. You can create a custom logger instance with [createLogger](https://rsbuild.rs/api/javascript-api/core#createlogger) and attach it to the current Rsbuild instance through [customLogger](https://rsbuild.rs/config/custom-logger) . For example, the following config makes the current instance output only `warn` and `error` logs: rsbuild.config.ts import { createLogger, defineConfig } from '@rsbuild/core'; const customLogger = createLogger({ level: 'warn', }); export default defineConfig({ customLogger, }); ### [#](https://rsbuild.rs/guide/advanced/logging#custom-prefix) Custom prefix You can use `prefix` to add a fixed prefix to each log message: rsbuild.config.ts import { createLogger } from '@rsbuild/core'; const logger = createLogger({ prefix: '[web]', }); logger.info('hello'); // info [web] hello ### [#](https://rsbuild.rs/guide/advanced/logging#override-log-methods) Override log methods You can use `override()` to replace some logger methods with a custom output format: rsbuild.config.ts import { createLogger } from '@rsbuild/core'; const logger = createLogger(); logger.override({ info(message) { console.log(`[info] ${message}`); }, warn(message) { console.warn(`[warn] ${message}`); }, }); logger.info('hello'); // [info] hello logger.warn('world'); // [warn] world [#](https://rsbuild.rs/guide/advanced/logging#instance-logger) Instance logger ------------------------------------------------------------------------------ You can access the logger on an Rsbuild instance in the following ways: 1. [rsbuild.logger](https://rsbuild.rs/api/javascript-api/instance#rsbuildlogger) : Access the logger of the current instance in the JavaScript API. import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild(); rsbuild.logger.info('Hello from rsbuild.logger'); 2. [api.logger](https://rsbuild.rs/plugins/dev/core#apilogger) : Access the logger of the current instance inside a plugin. const pluginLoggerDemo = () => ({ name: 'plugin-logger-demo', setup(api) { api.logger.info('Hello from plugin logger'); }, }); [#](https://rsbuild.rs/guide/advanced/logging#global-logger) Global logger -------------------------------------------------------------------------- Rsbuild also provides a shared global logger singleton, available through [logger](https://rsbuild.rs/api/javascript-api/core#logger) . import { logger } from '@rsbuild/core'; logger.info('Hello from global logger'); * If the log level of the global logger is changed, Rsbuild instances created afterward inherit the updated log level. [#](https://rsbuild.rs/guide/advanced/logging#logger-methods) Logger methods ---------------------------------------------------------------------------- All logger instances provide the same methods: import { logger } from '@rsbuild/core'; // A gradient welcome log logger.greet(`\n➜ Rsbuild v1.0.0\n`); // Info logger.info('This is an info message'); // Start logger.start('This is a start message'); // Warn logger.warn('This is a warning message'); // Ready logger.ready('This is a ready message'); // Success logger.success('This is a success message'); // Error logger.error('This is an error message'); logger.error(new Error('This is an error message with stack')); // Debug logger.debug('This is a debug message'); // Same as console.log logger.log('This is a log message'); [#](https://rsbuild.rs/guide/advanced/logging#debug-mode) Debug mode -------------------------------------------------------------------- When [debug mode](https://rsbuild.rs/guide/debug/debug-mode) is enabled, Rsbuild automatically raises the log level to `verbose` to output more detailed logs for troubleshooting. --- # HMR FAQ - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/faq/hmr.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/faq/hmr#hmr-faq) HMR FAQ ===================================================== Copy Markdown ### [#](https://rsbuild.rs/guide/faq/hmr#how-to-troubleshoot-hmr-issues) How to troubleshoot HMR issues? There are several possible reasons why HMR may not work. This document covers the most common causes and provides troubleshooting guidance. Before troubleshooting, it's helpful to understand how HMR works: HMR principle 1. The browser establishes a WebSocket connection with the dev server for real-time communication. 2. When the dev server finishes recompiling, it sends a notification to the browser via WebSocket. The browser then sends a `hot-update.(js|json)` request to the dev server to load the newly compiled module. 3. After receiving the new module, React projects use React Refresh (an official React tool) to update components. Other frameworks have similar tools. After understanding how HMR works, you can follow these troubleshooting steps: #### [#](https://rsbuild.rs/guide/faq/hmr#1-check-the-websocket-connection) 1\. Check the WebSocket connection Open the browser console and check for the presence of the `[HMR] connected.` log. * If present, the WebSocket connection is working correctly. Continue with the following steps. * If not present, open the Network panel in Chrome and check the status of the `ws://[host]:[port]/rsbuild-hmr` request. If the request failed, this indicates that HMR failed because the WebSocket connection was not established. The WebSocket connection can fail for various reasons, such as a network proxy preventing the WebSocket request from reaching the dev server. Check whether the WebSocket request address matches your dev server address. If it doesn't match, configure the WebSocket request address using [dev.client](https://rsbuild.rs/config/dev/client) . #### [#](https://rsbuild.rs/guide/faq/hmr#2-check-the-hot-update-requests) 2\. Check the hot-update requests When you modify a module's code and trigger a recompilation, the browser sends several `hot-update.json` and `hot-update.js` requests to the dev server to fetch the updated code. Try modifying a module and inspect the content of the `hot-update.(js|json)` requests. If the request contains the latest code, the hot update request is working correctly. If the request content is incorrect, it's likely due to a network proxy. Check whether the `hot-update.(js|json)` request address matches your dev server address. If it doesn't match, adjust the proxy rules to route the `hot-update.(js|json)` requests to the dev server address. #### [#](https://rsbuild.rs/guide/faq/hmr#3-check-for-other-causes) 3\. Check for other causes If the above steps don't reveal any issues, other factors may be causing HMR to fail. For example, the code may not meet React's HMR requirements. Refer to the following questions for further troubleshooting. * * * ### [#](https://rsbuild.rs/guide/faq/hmr#hmr-not-working-with-external-react) HMR not working with external React? To ensure HMR works properly, you need to use the development builds of React and ReactDOM. If you exclude React via `externals` during bundling, the production build of React is typically injected through a CDN, which can cause HMR to fail. export default { output: { externals: { react: 'React', 'react-dom': 'ReactDOM', }, }, }; To solve this problem, reference the React development builds and install React DevTools. Hot reloading will then work properly. If you're unsure which React build you're using, refer to the [React documentation - Use the Production Build](https://legacy.reactjs.org/docs/optimizing-performance.html#use-the-production-build) . * * * ### [#](https://rsbuild.rs/guide/faq/hmr#hmr-not-working-with-filename-hash-in-development-mode) HMR not working with filename hash in development mode? Typically, filename hashes should only be set in production mode (when `process.env.NODE_ENV === 'production'`). Setting filename hashes in development mode can cause HMR to fail, especially for CSS files. This is because the hash changes every time the file content changes, preventing tools like [mini-css-extract-plugin](https://npmjs.com/package/mini-css-extract-plugin) from reading the latest file content. * Correct usage: export default { output: { filename: { css: process.env.NODE_ENV === 'production' ? '[name].[contenthash:10].css' : '[name].css', }, }, }; * Incorrect usage: export default { output: { filename: { css: '[name].[contenthash:10].css', }, }, }; * * * ### [#](https://rsbuild.rs/guide/faq/hmr#hmr-not-working-with-https) HMR not working with HTTPS? When HTTPS is enabled, the HMR connection may fail due to certificate issues. If you open the console, you'll see an HMR connection failed error. » WebSocket connection to 'wss://localhost:3000/rsbuild-hmr' failed: [HMR] disconnected. Attempting to reconnect. To solve this problem, click "Advanced" -> "Proceed to \[domain\] (unsafe)" in the Chrome warning page. > Tip: When accessing the page via localhost, the "Your connection is not private" warning may not appear. In that case, access the page via a network domain instead. --- # Hot module replacement - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/advanced/hmr.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/advanced/hmr#hot-module-replacement) Hot module replacement ======================================================================================== Copy Markdown Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running, without a full page reload. This significantly speeds up development in several ways: * Preserves application state that would be lost during a full reload. * Saves valuable development time by updating only what changed. * Instantly updates the browser when modifying CSS/JS in source code, similar to changing styles directly in the browser's dev tools. [#](https://rsbuild.rs/guide/advanced/hmr#hmr-toggle) HMR toggle ---------------------------------------------------------------- Rsbuild has built-in support for HMR, which is enabled by default in development mode. If you don't need HMR, set [dev.hmr](https://rsbuild.rs/config/dev/hmr) to `false`. This disables HMR and React Refresh, and Rsbuild falls back to [dev.liveReload](https://rsbuild.rs/config/dev/live-reload) . rsbuild.config.ts export default { dev: { hmr: false, }, }; To disable both HMR and live reload, set [dev.hmr](https://rsbuild.rs/config/dev/hmr) and [dev.liveReload](https://rsbuild.rs/config/dev/live-reload) to `false`. This prevents WebSocket requests to the dev server, and the page won't refresh automatically when files change. rsbuild.config.ts export default { dev: { hmr: false, liveReload: false, }, }; [#](https://rsbuild.rs/guide/advanced/hmr#specify-hmr-url) Specify HMR URL -------------------------------------------------------------------------- By default, Rsbuild uses the host and port number of the current page to construct the WebSocket URL for HMR. If the HMR connection fails, specify the WebSocket URL using the [dev.client](https://rsbuild.rs/config/dev/client) config. rsbuild.config.ts export default { dev: { client: { host: 'localhost', protocol: 'ws', }, }, }; [#](https://rsbuild.rs/guide/advanced/hmr#file-watching) File watching ---------------------------------------------------------------------- By default, Rsbuild doesn't watch files in the `.git/` and `node_modules/` directories. Changes to these files won't trigger a rebuild, which reduces memory usage and improves build performance. To watch these directories, configure Rspack's [watchOptions.ignored](https://rspack.rs/config/watch#watchoptionsignored) to override the default behavior. For example, to watch the `node_modules/` directory while ignoring `.git/`: rsbuild.config.ts export default { tools: { rspack: { watchOptions: { ignored: /\.git/, }, }, }, }; [#](https://rsbuild.rs/guide/advanced/hmr#faq) FAQ -------------------------------------------------- Refer to [HMR FAQ](https://rsbuild.rs/guide/faq/hmr) . --- # Deployment - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/basic/deployment.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/basic/deployment#deployment) Deployment ==================================================================== Copy Markdown This section explains how to deploy Rsbuild projects to static hosting and runtime platforms. [#](https://rsbuild.rs/guide/basic/deployment#background-information) Background information -------------------------------------------------------------------------------------------- Before starting the deployment, you should understand the following: * The CLI commands used for building and previewing outputs. * The directory structure of the build outputs. * The URL prefix of static assets. ### [#](https://rsbuild.rs/guide/basic/deployment#build-commands) Build commands The build commands provided by Rsbuild are: * [build command](https://rsbuild.rs/guide/basic/cli#rsbuild-build) , used to generate the build outputs for production deployment. * [preview command](https://rsbuild.rs/guide/basic/cli#rsbuild-preview) , used to preview the production build outputs locally. Note that you must first execute the `rsbuild build` command to generate the build outputs. package.json { "scripts": { "build": "rsbuild build", "preview": "rsbuild preview" } } Tip The preview command is only used for local preview. Do not use it for production servers, as it is not designed for that. ### [#](https://rsbuild.rs/guide/basic/deployment#output-directory) Output directory Rsbuild's build outputs typically include HTML, JS, CSS, and other assets, and are output to the `dist` directory by default. You can change the name and structure of the dist directory with configuration options. See the [Output files](https://rsbuild.rs/guide/basic/output-files) section for more information. dist ├── static │ ├── image │ ├── css │ └── js └── [name].html ### [#](https://rsbuild.rs/guide/basic/deployment#asset-prefix) Asset prefix We can divide the build output into two parts: **HTML files** and **static assets**: * HTML files refer to files with the `.html` suffix in the output directory, which usually need to be deployed on the server. * Static assets are located in the `static` directory of the output folder, which contains assets such as JavaScript, CSS, and images. They can be deployed either on the server or on a CDN. If you deploy static assets to a subdirectory on the server, set [output.assetPrefix](https://rsbuild.rs/config/output/asset-prefix) as the base path: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; export default defineConfig({ output: { assetPrefix: '/some-base-folder/', }, }); If you prefer to serve static assets from a CDN for better performance instead of alongside the HTML on your server, set [output.assetPrefix](https://rsbuild.rs/config/output/asset-prefix) to the CDN address so the application can reference the assets correctly. rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; export default defineConfig({ output: { assetPrefix: 'https://cdn.com/path/', }, }); With this configuration, when referencing static assets in HTML, the specified prefix will be automatically added. For example: [#](https://rsbuild.rs/guide/basic/deployment#deployment-platforms) Deployment platforms ---------------------------------------------------------------------------------------- The following sections describe how to deploy on several common platforms. > Platform names are listed in alphabetical order. ### [#](https://rsbuild.rs/guide/basic/deployment#cloudflare) Cloudflare Cloudflare provides several ways to deploy Rsbuild projects. Use Cloudflare Pages when you only need static hosting for the generated output. Use Cloudflare Workers when your application needs to run in the Workers runtime. #### [#](https://rsbuild.rs/guide/basic/deployment#cloudflare-pages) Cloudflare Pages [Cloudflare Pages](https://developers.cloudflare.com/pages/) is a static site hosting platform provided by Cloudflare. You can follow the [Cloudflare Pages - Git integration guide](https://developers.cloudflare.com/pages/get-started/git-integration/) to integrate with Git and deploy your site to Cloudflare Pages. When configuring, complete the following fields under "Build settings": * **Build command**: fill in the project's build command, typically `npm run build`. * **Build output directory**: fill in the project's output directory, which defaults to `dist`. Then click the **Save and Deploy** button to start the deployment. #### [#](https://rsbuild.rs/guide/basic/deployment#cloudflare-workers) Cloudflare workers Cloudflare Workers is a runtime deployment target rather than static hosting. For Rsbuild projects that need to run in the Cloudflare Workers runtime, [rsbuild-cloudflare](https://github.com/Nsttt/rsbuild-cloudflare) is an experimental plugin that reads Wrangler configuration, serves development requests through Miniflare, and emits deployable Worker output. ### [#](https://rsbuild.rs/guide/basic/deployment#github-pages) GitHub pages [GitHub Pages](https://pages.github.com/) is a static site hosting service that takes HTML, CSS, and JavaScript files straight from a repository on GitHub. The following are step-by-step instructions for deploying to GitHub Pages. 1. Configure the URL prefix for static assets using [output.assetPrefix](https://rsbuild.rs/config/output/asset-prefix) . rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; export default defineConfig({ output: { // Please replace with the repository name. // For example, "/my-project/" assetPrefix: '//', }, }); 2. Open the "Settings" page of your GitHub repository, click "Pages" in the left menu to access the GitHub Pages configuration page. 3. Select "Source" → "GitHub Actions" and click "create your own" to create a GitHub Action configuration file. 4. Paste the following content into the editor and name the file `github-pages.yml` (you can adjust the content and filename as needed). github-pages.yml # Sample workflow for building and deploying a Rsbuild site to GitHub Pages name: Rsbuild Deployment on: # Runs on pushes targeting the default branch push: branches: ['main'] # Allows you to run this workflow manually from the actions tab workflow_dispatch: # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages permissions: contents: read pages: write id-token: write # Allow only one concurrent deployment concurrency: group: 'pages' cancel-in-progress: false jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Use Node.js uses: actions/setup-node@v6 with: node-version: 24 package-manager-cache: false # If you use other package managers like yarn or pnpm, # you will need to install them first - name: Install dependencies run: npm i - name: Build run: npm run build - name: Setup Pages uses: actions/configure-pages@v6 - name: Upload artifact uses: actions/upload-pages-artifact@v4 with: path: './dist' - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v5 5. Commit and wait for GitHub Actions to execute. Once complete, you can visit `https://.github.io//` to view the deployed page. ### [#](https://rsbuild.rs/guide/basic/deployment#netlify) Netlify [Netlify Core](https://netlify.com/) is a frontend cloud solution for developers to build and deploy future-proof digital solutions with modern, composable tooling. #### [#](https://rsbuild.rs/guide/basic/deployment#add-new-site) Add new site Netlify provides a detailed guide. You can follow the instructions in [Netlify - Add new site](https://docs.netlify.com/welcome/add-new-site/) , configure the basic settings, and start the deployment. You need to configure the following fields: * **Build command**: fill in the project's build command, typically `npm run build`. * **Publish directory**: fill in the project's output directory, which defaults to `dist`. Then click the **Deploy site** button to start the deployment. #### [#](https://rsbuild.rs/guide/basic/deployment#custom-domains) Custom domains If you want to make your sites accessible at custom domain names, you can configure this in Netlify's "Domain management" section. > Detailed guide: [Netlify - Custom domains](https://docs.netlify.com/domains-https/custom-domains/) > . ### [#](https://rsbuild.rs/guide/basic/deployment#vercel) Vercel [Vercel](https://vercel.com/) is a platform for developers that provides the tools, workflows, and infrastructure you need to build and deploy your web apps faster, without the need for additional configuration. #### [#](https://rsbuild.rs/guide/basic/deployment#add-new-site-1) Add new site Vercel provides a detailed guide. You can follow [Vercel - Projects](https://vercel.com/docs/projects/overview) to create a project in your dashboard, configure the basic settings, and start the deployment. Only the following fields under "Build and Output Settings" need to be configured: * **Output directory**: fill in the project's output directory, which defaults to `dist`. Then click the **Deploy** button to start the deployment. #### [#](https://rsbuild.rs/guide/basic/deployment#configure-domains) Configure domains If you want to make your sites accessible at custom domain names, you can configure this in Vercel's "Domains" section. > Detailed guide: [Vercel - Domains](https://vercel.com/docs/projects/domains) > . ### [#](https://rsbuild.rs/guide/basic/deployment#zephyr-cloud) Zephyr Cloud [Zephyr Cloud](https://zephyr-cloud.io/) is a zero-config deployment platform that integrates directly into your build process and provides global edge distribution for federated applications. #### [#](https://rsbuild.rs/guide/basic/deployment#how-to-deploy) How to deploy Follow the steps in [zephyr-rsbuild-plugin](https://www.npmjs.com/package/zephyr-rsbuild-plugin) . During the build process, your application will be automatically deployed and you'll receive a deployment URL. Zephyr Cloud handles asset optimization, global CDN distribution, module federation setup, and provides automatic rollback capabilities. Start for free today at [zephyr-cloud.io](https://zephyr-cloud.io/) . --- # Svelte - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/framework/svelte.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/framework/svelte#svelte) Svelte ============================================================ Copy Markdown Learn how to build a Svelte application using Rsbuild. [#](https://rsbuild.rs/guide/framework/svelte#create-a-svelte-application) Create a Svelte application ------------------------------------------------------------------------------------------------------ Create a Svelte application with [create-rsbuild](https://rsbuild.rs/guide/start/quick-start#create-an-rsbuild-application) : npm yarn pnpm bun npm create rsbuild@latest yarn create rsbuild pnpm create rsbuild@latest bun create rsbuild@latest Then select `Svelte` when prompted to "Select framework". [#](https://rsbuild.rs/guide/framework/svelte#use-svelte-in-an-existing-project) Use Svelte in an existing project ------------------------------------------------------------------------------------------------------------------ To compile Svelte components (`.svelte` files), you need to register the Rsbuild [Svelte plugin](https://rsbuild.rs/plugins/list/plugin-svelte) . The plugin will automatically add the necessary configuration for Svelte builds. For example, register the plugin in Rsbuild config: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginSvelte } from '@rsbuild/plugin-svelte'; export default defineConfig({ plugins: [pluginSvelte()], }); --- # Code splitting - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/optimization/code-splitting.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/optimization/code-splitting#code-splitting) Code splitting ======================================================================================= Copy Markdown Code splitting is the process of breaking code into multiple chunks to enable on-demand loading and improve performance. With a well-designed splitting strategy, you can reduce the initial load size and speed up page rendering. Tip A chunk usually corresponds to a built output asset. The browser can request and cache these chunks separately instead of loading all code at once. > Reference: [Rspack - Code Splitting](https://rspack.rs/guide/optimization/code-splitting) > . [#](https://rsbuild.rs/guide/optimization/code-splitting#using-dynamic-import) Using dynamic import --------------------------------------------------------------------------------------------------- By using [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) , you can split code that is not required for the initial render into async chunks and load it only when needed. When Rsbuild encounters the `import()` syntax, it automatically splits the referenced module into a new chunk and loads it on demand at runtime. For large modules, whether local modules or third-party dependencies, dynamic import can be used to defer loading: // Local module import('./bigModule.ts').then((bigModule) => { console.log(bigModule); }); // Third-party dependency import('some-package').then((somePackage) => { console.log(somePackage); }); [#](https://rsbuild.rs/guide/optimization/code-splitting#chunk-splitting) Chunk splitting ----------------------------------------------------------------------------------------- Rsbuild provides the [splitChunks](https://rsbuild.rs/config/split-chunks) option to configure how chunks are split during the build process. This option is based on Rspack's `optimization.splitChunks` configuration and extends it with a set of ready-to-use presets. With `splitChunks`, you can customize chunk splitting rules. For example, you can control which modules are grouped into the same chunk and set conditions such as the minimum chunk size. This helps strike a better balance between load performance and the number of network requests. In the example below, axios is split into a separate chunk named `axios.js`: export default { splitChunks: { cacheGroups: { axios: { test: /[\\/]node_modules[\\/]axios[\\/]/, name: 'axios', chunks: 'all', }, }, }, }; For more options and usage details, see the [splitChunks documentation](https://rsbuild.rs/config/split-chunks) . --- # Path aliases - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/advanced/alias.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/advanced/alias#path-aliases) Path aliases ====================================================================== Copy Markdown Path aliases allow developers to define aliases for modules, making it easier to reference them in code. This can be useful when you want to use a short, easy-to-remember name for a module instead of a long, complex path. For example, if you frequently reference the `src/common/request.ts` module in your project, you can define an alias for it as `@request` and then use `import request from '@request'` in your code instead of writing the full relative path every time. This also allows you to move the module to a different location without needing to update all the import statements in your code. src/index.ts import request from '@request'; // resolve to `src/common/request.ts` In Rsbuild, there are several ways to set up path aliases: * Use the [`paths` field](https://rsbuild.rs/guide/advanced/alias#typescript-paths-field) in tsconfig.json or jsconfig.json. * Use the [`imports` field](https://rsbuild.rs/guide/advanced/alias#nodejs-imports-field) in package.json. * Use Rsbuild's [resolve.alias](https://rsbuild.rs/guide/advanced/alias#alias-configuration) configuration. [#](https://rsbuild.rs/guide/advanced/alias#typescript-paths-field) TypeScript `paths` field -------------------------------------------------------------------------------------------- You can configure aliases through the `paths` configuration in [tsconfig.json](https://typescriptlang.org/docs/handbook/tsconfig-json.html) , which is the recommended approach in TypeScript projects as it also resolves the TS type issues related to path aliases. For example: tsconfig.json { "compilerOptions": { "paths": { "@common/*": ["./src/common/*"] } } } After configuring, if you reference `@common/Foo.tsx` in your code, it will be mapped to the `/src/common/Foo.tsx` path. Tip You can refer to the [TypeScript - paths](https://typescriptlang.org/tsconfig#paths) documentation for more details. ### [#](https://rsbuild.rs/guide/advanced/alias#jsconfigjson) jsconfig.json In non-TypeScript projects, if you need to set path aliases through the `paths` field in [jsconfig.json](https://code.visualstudio.com/docs/languages/jsconfig) , you can use the [source.tsconfigPath](https://rsbuild.rs/config/source/tsconfig-path) option to set it. After adding the following configuration, Rsbuild will recognize the `paths` field in `jsconfig.json`. rsbuild.config.mjs export default { source: { tsconfigPath: './jsconfig.json', }, }; [#](https://rsbuild.rs/guide/advanced/alias#nodejs-imports-field) Node.js `imports` field ----------------------------------------------------------------------------------------- You can also use the Node.js [`imports` field](https://nodejs.org/api/packages.html#imports) to define aliases with the `#` prefix. This works out of the box and does not require additional Rsbuild configuration. package.json { "type": "module", "imports": { "#app/*": "./src/*" } } src/index.js import { message } from '#app/foo'; For TypeScript projects, enable [`resolvePackageJsonImports`](https://www.typescriptlang.org/tsconfig/#resolvePackageJsonImports) so the TypeScript language service and compiler can understand these aliases. [#](https://rsbuild.rs/guide/advanced/alias#alias-configuration) Alias configuration ------------------------------------------------------------------------------------ Rsbuild provides the [resolve.alias](https://rsbuild.rs/config/resolve/alias) configuration option, which corresponds to the webpack/Rspack native [resolve.alias](https://rspack.rs/config/resolve#resolvealias) configuration. You can configure this option using an object or a function. ### [#](https://rsbuild.rs/guide/advanced/alias#use-cases) Use cases Since the `paths` configuration in `tsconfig.json` is written in a static JSON file, it lacks dynamism. The `resolve.alias` configuration can address this limitation by allowing you to dynamically set the `resolve.alias` using JavaScript code, such as based on environment variables. ### [#](https://rsbuild.rs/guide/advanced/alias#object-usage) Object usage You can configure `resolve.alias` using an object, where the relative paths will be automatically resolved to absolute paths. For example: export default { resolve: { alias: { '@common': './src/common', }, }, }; After configuring, if you reference `@common/Foo.tsx` in your code, it will be mapped to the `/src/common/Foo.tsx` path. ### [#](https://rsbuild.rs/guide/advanced/alias#function-usage) Function usage You can also configure `resolve.alias` as a function, which receives the built-in `alias` object and allows you to modify it. For example: export default { resolve: { alias: (alias) => { alias['@common'] = './src/common'; return alias; }, }, }; ### [#](https://rsbuild.rs/guide/advanced/alias#priority) Priority The `paths` configuration in `tsconfig.json` takes precedence over the `resolve.alias` configuration. When a path matches the rules defined in both `paths` and `resolve.alias`, the value defined in `paths` will be used. You can adjust the priority of these two options using [resolve.aliasStrategy](https://rsbuild.rs/config/resolve/alias-strategy) . --- # Preact - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/framework/preact.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/framework/preact#preact) Preact ============================================================ Copy Markdown Learn how to build a Preact application using Rsbuild. [#](https://rsbuild.rs/guide/framework/preact#create-a-preact-application) Create a Preact application ------------------------------------------------------------------------------------------------------ Create a Preact application with [create-rsbuild](https://rsbuild.rs/guide/start/quick-start#create-an-rsbuild-application) : npm yarn pnpm bun npm create rsbuild@latest yarn create rsbuild pnpm create rsbuild@latest bun create rsbuild@latest Then select `Preact` when prompted to "Select framework". [#](https://rsbuild.rs/guide/framework/preact#use-preact-in-an-existing-project) Use Preact in an existing project ------------------------------------------------------------------------------------------------------------------ To compile Preact, you need to register the Rsbuild [Preact plugin](https://rsbuild.rs/plugins/list/plugin-preact) . The plugin will automatically add the necessary configuration for Preact builds. For example, register the plugin in Rsbuild config: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginPreact } from '@rsbuild/plugin-preact'; export default defineConfig({ plugins: [pluginPreact()], }); [#](https://rsbuild.rs/guide/framework/preact#preact-fast-refresh) Preact Fast Refresh -------------------------------------------------------------------------------------- Preact plugin uses [@preact/prefresh](https://github.com/preactjs/prefresh) and [@rspack/plugin-preact-refresh](https://github.com/rstackjs/rspack-plugin-preact-refresh) to hot reload Preact components. ### [#](https://rsbuild.rs/guide/framework/preact#component-recognition) Component recognition Prefresh needs to be able to recognize your components. This means that components should start with a capital letter and hooks should start with `use` followed by a capital letter. This allows the plugin to effectively recognize these. Do note that a component as seen below is not named: export default () => { return

Want to refresh

; }; Instead do: const MyComponent = () => { return

Want to refresh

; }; export default MyComponent; When you are working with HOC's be sure to lift up the `displayName` so the plugin can recognize it as a component. --- # Solid - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/framework/solid.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/framework/solid#solid) Solid ========================================================= Copy Markdown Learn how to build a Solid application using Rsbuild. [#](https://rsbuild.rs/guide/framework/solid#create-a-solid-application) Create a Solid application --------------------------------------------------------------------------------------------------- Create a Solid application with [create-rsbuild](https://rsbuild.rs/guide/start/quick-start#create-an-rsbuild-application) : npm yarn pnpm bun npm create rsbuild@latest yarn create rsbuild pnpm create rsbuild@latest bun create rsbuild@latest Then select `Solid` when prompted to "Select framework". [#](https://rsbuild.rs/guide/framework/solid#full-stack-frameworks) Full-stack frameworks ----------------------------------------------------------------------------------------- The following full-stack Solid frameworks are built on Rsbuild and reuse Rsbuild's plugin ecosystem. ### [#](https://rsbuild.rs/guide/framework/solid#tanstack-start) TanStack Start [TanStack Start](https://tanstack.com/start/latest) is a full-stack framework powered by TanStack Router. It provides full-document SSR, streaming, Server Functions, client/server builds, and more. * [Documentation](https://tanstack.com/start/latest) * [Example project](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/tanstack-start-solid) You can initialize the TanStack Start example project with: npx giget gh:rstackjs/rstack-examples/rsbuild/tanstack-start-solid tanstack-start cd tanstack-start pnpm i To migrate a TanStack Start project from Vite, see [TanStack Start migration](https://rsbuild.rs/guide/migration/tanstack-start) . [#](https://rsbuild.rs/guide/framework/solid#use-solid-in-an-existing-project) Use Solid in an existing project --------------------------------------------------------------------------------------------------------------- To compile Solid components, you need to register the Rsbuild [Solid plugin](https://rsbuild.rs/plugins/list/plugin-solid) . The plugin will automatically add the necessary configuration for Solid builds. For example, register the plugin in Rsbuild config: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginBabel } from '@rsbuild/plugin-babel'; import { pluginSolid } from '@rsbuild/plugin-solid'; export default defineConfig({ plugins: [\ pluginBabel({\ include: /\.(?:jsx|tsx)$/,\ }),\ pluginSolid(),\ ], }); --- # TypeScript - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/basic/typescript.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/basic/typescript#typescript) TypeScript ==================================================================== Copy Markdown Rsbuild supports TypeScript by default, allowing you to directly use `.ts` and `.tsx` files in your project. [#](https://rsbuild.rs/guide/basic/typescript#typescript-transformation) TypeScript transformation -------------------------------------------------------------------------------------------------- Rsbuild uses [SWC](https://rsbuild.rs/guide/configuration/swc) by default for transforming TypeScript code to JavaScript, and also supports switching to [Babel](https://rsbuild.rs/plugins/list/plugin-babel) for transformation. ### [#](https://rsbuild.rs/guide/basic/typescript#isolated-modules) Isolated modules Unlike the native TypeScript compiler, tools like SWC and Babel compile each file separately and cannot determine whether an imported name is a type or value. When using TypeScript in Rsbuild, enable the [verbatimModuleSyntax](https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax) option in `tsconfig.json`, which enables the [isolatedModules](https://typescriptlang.org/tsconfig/#isolatedModules) option by default: tsconfig.json { "compilerOptions": { "verbatimModuleSyntax": true } } The `isolatedModules` option prevents syntax that SWC and Babel cannot compile correctly, such as cross-file type references. It guides you toward correct usage: // Wrong export { SomeType } from './types'; // Correct export type { SomeType } from './types'; > See [SWC - Migrating from tsc](https://swc.rs/docs/migrating-from-tsc) > for more details about the differences between SWC and tsc. [#](https://rsbuild.rs/guide/basic/typescript#preset-types) Preset types ------------------------------------------------------------------------ `@rsbuild/core` provides preset type definitions, including CSS files, CSS Modules, static assets, `import.meta`, and other types. Add the preset types to `compilerOptions.types` in `tsconfig.json`: tsconfig.json { "compilerOptions": { "types": ["@rsbuild/core/types"] } } If your project already has `compilerOptions.types`, append `@rsbuild/core/types` to the existing list. > See [types.d.ts](https://github.com/web-infra-dev/rsbuild/blob/main/packages/core/types.d.ts) > for the complete preset type definitions that Rsbuild includes. [#](https://rsbuild.rs/guide/basic/typescript#type-checking) Type checking -------------------------------------------------------------------------- When transpiling TypeScript code using tools like SWC and Babel, type checking isn't performed. ### [#](https://rsbuild.rs/guide/basic/typescript#type-check-plugin) Type check plugin To enable type checking, you can use the [@rsbuild/plugin-type-check](https://github.com/rstackjs/rsbuild-plugin-type-check) plugin. This plugin runs TypeScript type checking in a separate process and internally integrates [ts-checker-rspack-plugin](https://github.com/rstackjs/ts-checker-rspack-plugin) . The plugin supports type checking in both dev and build modes, helping you catch type errors early in development. Refer to [@rsbuild/plugin-type-check](https://github.com/rstackjs/rsbuild-plugin-type-check) for usage instructions. ### [#](https://rsbuild.rs/guide/basic/typescript#using-tsc) Using tsc You can also use [tsc](https://www.typescriptlang.org/docs/handbook/compiler-options.html) directly for type checking by adding a `type-check` step to your `build` script. This approach only performs type checking after the build and doesn't run during dev mode. package.json { "scripts": { "build": "rsbuild build && npm run type-check", "type-check": "tsc --noEmit" }, "devDependencies": { "typescript": "^6.0.0" } } For Vue applications, use [vue-tsc](https://github.com/vuejs/language-tools/tree/master/packages/tsc) instead of `tsc`. It supports Vue SFCs in addition to TypeScript files. package.json { "scripts": { "build": "rsbuild build && npm run type-check", "type-check": "vue-tsc --noEmit" }, "devDependencies": { "typescript": "^6.0.0", "vue-tsc": "^3.0.0" } } [#](https://rsbuild.rs/guide/basic/typescript#tsconfigjson-path) tsconfig.json Path ----------------------------------------------------------------------------------- Rsbuild reads the `tsconfig.json` file from the root directory by default. Use [source.tsconfigPath](https://rsbuild.rs/config/source/tsconfig-path) to configure a custom tsconfig.json file path. export default { source: { tsconfigPath: './tsconfig.custom.json', }, }; [#](https://rsbuild.rs/guide/basic/typescript#path-extensions) Path extensions ------------------------------------------------------------------------------ When importing another module in a TypeScript module, TypeScript allows using the `.js` file extension: src/index.ts // The actual referenced module could be `./some-module.ts` or `./some-module.tsx` import { someFn } from './some-module.js'; Rsbuild supports this feature through Rspack's [extensionAlias](https://rspack.rs/config/resolve#resolveextensionalias) configuration. In TypeScript projects, Rsbuild adds the following configuration by default: const rspackConfig = { resolve: { extensionAlias: { '.js': ['.js', '.ts', '.tsx'], '.jsx': ['.jsx', '.tsx'], }, }, }; This means: * You can use the `.js` extension to import `.ts` or `.tsx` files. * You can use the `.jsx` extension to import `.tsx` files. [#](https://rsbuild.rs/guide/basic/typescript#decorators-version) Decorators version ------------------------------------------------------------------------------------ Rsbuild does not read the `experimentalDecorators` option in `tsconfig.json`. Instead, it provides the [decorators.version](https://rsbuild.rs/config/source/decorators#decoratorsversion) option to specify the decorator version. By default, Rsbuild uses the `2023-11` decorators version. You can set it to `legacy` or other versions when needed: rsbuild.config.ts export default { source: { decorators: { version: 'legacy', }, }, }; [#](https://rsbuild.rs/guide/basic/typescript#typescript-version-compatibility) TypeScript version compatibility ---------------------------------------------------------------------------------------------------------------- Rsbuild supports TypeScript 5.0 and later. Because Rsbuild uses SWC by default to transform TypeScript source code, it can still transform `.ts` and `.tsx` files in projects using earlier TypeScript versions. However, TypeScript versions earlier than 5.0 may fail to parse Rsbuild's type declarations, which can affect type checking and editor type hints. --- # Configure Rsbuild - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/configuration/rsbuild.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/configuration/rsbuild#configure-rsbuild) Configure Rsbuild ======================================================================================= Copy Markdown Rsbuild provides a wide range of configuration options with sensible defaults for most use cases. In most scenarios, you can use Rsbuild out of the box without any configuration. When you need to customize build behavior, use the options below. [#](https://rsbuild.rs/guide/configuration/rsbuild#configuration-structure) Configuration structure --------------------------------------------------------------------------------------------------- The Rsbuild configuration structure looks like this: rsbuild.config.mjs export default { plugins: [\ // configure Rsbuild plugins\ ], dev: { // options for local development }, html: { // options for HTML generation }, tools: { // options for the low-level tools }, output: { // options for build outputs }, resolve: { // options for module resolution }, source: { // options for input source code }, server: { // options for the Rsbuild server // mainly for local development and preview // some options (e.g. publicDir, base) also affect production builds }, security: { // options for Web security }, performance: { // options for build performance and runtime performance }, moduleFederation: { // options for module federation }, environments: { // define different Rsbuild configurations for each environment }, }; You can find detailed descriptions of every option on the [Config overview](https://rsbuild.rs/config/) page. [#](https://rsbuild.rs/guide/configuration/rsbuild#configuration-file) Configuration file ----------------------------------------------------------------------------------------- When you use the Rsbuild CLI, or call `loadConfig` without specifying `path`, Rsbuild looks for a configuration file in the project root in the following order: * rsbuild.config.ts * rsbuild.config.js * rsbuild.config.mts * rsbuild.config.mjs * rsbuild.config.cts * rsbuild.config.cjs If multiple config files exist at the same time, Rsbuild uses the first matching file in this list. We recommend using `rsbuild.config.ts` and importing the `defineConfig` utility from `@rsbuild/core`. It provides TypeScript hints and autocompletion to help you avoid configuration mistakes. For example, in `rsbuild.config.ts`, you can define the Rsbuild [resolve.alias](https://rsbuild.rs/config/resolve/alias) configuration: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; export default defineConfig({ resolve: { alias: { '@common': './src/common', }, }, }); Tip If Node.js shows the `[MODULE_TYPELESS_PACKAGE_JSON]` warning for `rsbuild.config.ts`, you can add `"type": "module"` to package.json or rename the file to `rsbuild.config.mts` to resolve the warning. If you are developing a non-TypeScript project, you can use the `.mjs` format for the configuration file: rsbuild.config.mjs import { defineConfig } from '@rsbuild/core'; export default defineConfig({ resolve: { alias: (opts) => { opts['@common'] = './src/common'; }, }, }); [#](https://rsbuild.rs/guide/configuration/rsbuild#specify-config-file) Specify config file ------------------------------------------------------------------------------------------- The Rsbuild CLI uses the `--config` option to specify the config file. It can be set to a relative or absolute path. For example, if you need to use the `rsbuild.prod.config.mjs` file when running `build`, add the following scripts to `package.json`: package.json { "scripts": { "build": "rsbuild build --config rsbuild.prod.config.mjs" } } You can also abbreviate the `--config` option to `-c`: rsbuild build -c rsbuild.prod.config.mjs [#](https://rsbuild.rs/guide/configuration/rsbuild#specify-config-loader) Specify config loader ----------------------------------------------------------------------------------------------- Rsbuild provides three ways to load configuration files: * `auto` (Default): Use Node.js's native loader to load configuration files first, falling back to jiti if it fails. * `jiti`: Use [jiti](https://github.com/unjs/jiti) to load the configuration file, providing interoperability between ESM and CommonJS. The module resolution behavior differs slightly from Node.js native behavior. * `native`: Use Node.js native loader to load the configuration file. This ensures that module resolution behavior is consistent with Node.js native behavior and has better performance. This requires your JavaScript runtime to natively support TypeScript. For example, Node.js v22.6.0+ natively supports TypeScript. You can use the following command with the Node.js native loader to load the configuration file: # Node.js >= v22.18.0 # No need to set --experimental-strip-types npx rsbuild build --config-loader native # Node.js v22.6.0 - v22.17.1 # Need to set --experimental-strip-types NODE_OPTIONS="--experimental-strip-types" npx rsbuild build --config-loader native ### [#](https://rsbuild.rs/guide/configuration/rsbuild#about-nodejs-native-loader) About Node.js native loader When using Node.js's native loader, note the following limitations: 1. When importing JSON files, you need to use import attributes: import pkgJson from './package.json' with { type: 'json' }; // ✅ Correct import pkgJson from './package.json'; // ❌ Incorrect 2. When importing TypeScript files, you need to include the `.ts` extension: import baseConfig from './rsbuild.base.config.ts'; // ✅ Correct import baseConfig from './rsbuild.base.config'; // ❌ Incorrect > See [Node.js - Running TypeScript Natively](https://nodejs.org/en/learn/typescript/run-natively#running-typescript-natively) > for more details. [#](https://rsbuild.rs/guide/configuration/rsbuild#using-environment-variables) Using environment variables ----------------------------------------------------------------------------------------------------------- In the configuration file, you can use Node.js environment variables such as `process.env.NODE_ENV` to dynamically set different configurations: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; export default defineConfig({ resolve: { alias: { '@request': process.env.NODE_ENV === 'development' ? './src/request.dev.js' : './src/request.prod.js', }, }, }); [#](https://rsbuild.rs/guide/configuration/rsbuild#export-function) Export function ----------------------------------------------------------------------------------- Rsbuild supports exporting a function in the config file, which allows you to dynamically compute the config and return it to Rsbuild. rsbuild.config.js import { defineConfig } from '@rsbuild/core'; export default defineConfig(({ env, command, envMode }) => ({ resolve: { alias: { '@foo': env === 'development' ? './src/foo.dev.ts' : './src/foo.prod.ts', }, }, })); Tip The exported config function must provide a return value. If you do not need to return any config, you can return an empty object. The function accepts the following parameters: ### [#](https://rsbuild.rs/guide/configuration/rsbuild#env) env * **Type:** `string` * **Default:** `process.env.NODE_ENV` The current runtime environment. * When running `rsbuild dev`, the default value of env is `development`. * When running `rsbuild build` or `rsbuild preview`, the default value of env is `production`. ### [#](https://rsbuild.rs/guide/configuration/rsbuild#envmode) envMode * **Type:** `string` * **Default:** `process.env.NODE_ENV` The current value of the CLI parameter `--env-mode`. For example, when running `rsbuild build --env-mode test`, the value of `envMode` is `test`. ### [#](https://rsbuild.rs/guide/configuration/rsbuild#command) command * **Type:** `string` The current CLI command, such as `dev`, `build`, `preview`. [#](https://rsbuild.rs/guide/configuration/rsbuild#export-async-function) Export async function ----------------------------------------------------------------------------------------------- Rsbuild also supports exporting an async function in the config file, which lets you perform async work: rsbuild.config.js import { defineConfig } from '@rsbuild/core'; export default defineConfig(async ({ env, command }) => { const result = await someAsyncFunction(); return { html: { title: result, }, }; }); [#](https://rsbuild.rs/guide/configuration/rsbuild#merge-configurations) Merge configurations --------------------------------------------------------------------------------------------- You can use the [mergeRsbuildConfig](https://rsbuild.rs/api/javascript-api/core#mergersbuildconfig) function exported by `@rsbuild/core` to merge multiple configurations. rsbuild.config.ts import { defineConfig, mergeRsbuildConfig } from '@rsbuild/core'; const config1 = defineConfig({ dev: { port: '3000' }, }); const config2 = defineConfig({ dev: { port: '3001' }, }); // { dev: { port: '3001' } export default mergeRsbuildConfig(config1, config2); [#](https://rsbuild.rs/guide/configuration/rsbuild#configuration-file-watching) Configuration file watching ----------------------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/guide/configuration/rsbuild#rsbuild-cli) Rsbuild CLI When using the Rsbuild CLI, `rsbuild dev` and `rsbuild build --watch` automatically watch the loaded configuration file and its imported dependencies. When one of these files changes, Rsbuild reloads the configuration and restarts the current dev server or watch build. ### [#](https://rsbuild.rs/guide/configuration/rsbuild#javascript-api) JavaScript API When using the JavaScript API, pass the complete result returned by [`loadConfig`](https://rsbuild.rs/api/javascript-api/core#loadconfig) to `createRsbuild`. This allows Rsbuild to track the configuration file and its imported dependencies. When calling `rsbuild.startDevServer()`, `rsbuild.createDevServer()`, or `rsbuild.build({ watch: true })`, Rsbuild installs a restart watcher and automatically watches these files. Regular builds and preview servers do not install a watcher. When a watched file changes, Rsbuild calls the [onRestart hook](https://rsbuild.rs/plugins/dev/hooks#onrestart) . By default, Rsbuild only calls this hook and does not automatically restart the current task. To run the restart process, pass the [`restart` option](https://rsbuild.rs/api/javascript-api/core#restart-handling) . [#](https://rsbuild.rs/guide/configuration/rsbuild#debug-the-config) Debug the config ------------------------------------------------------------------------------------- You can enable Rsbuild's debug mode by setting `DEBUG=rsbuild` when running a build. DEBUG=rsbuild pnpm dev In debug mode, Rsbuild writes the config to the dist directory, making it easier to inspect and debug. config inspection completed, open the following files to view the content: - Rsbuild config: /Project/demo/dist/.rsbuild/rsbuild.config.mjs - Rspack config (web): /Project/demo/dist/.rsbuild/rspack.config.web.mjs Open the generated `/dist/.rsbuild/rsbuild.config.mjs` file to see the complete content of the Rsbuild config. For a complete introduction to debug mode, see the [Debug mode](https://rsbuild.rs/guide/debug/debug-mode) chapter. --- # Introduction - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/start/index.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/start/#introduction) Introduction ============================================================== Copy Markdown Rsbuild is a modern build tool for web applications, powered by [Rspack](https://rspack.rs/) . It delivers fast builds and optimized production output, while keeping configuration simple, consistent, and extensible through plugins. [#](https://rsbuild.rs/guide/start/#performance) Performance ------------------------------------------------------------ Powered by Rspack's Rust-based architecture, Rsbuild delivers blazing-fast performance to speed up your development workflow. Time to build a large web application: Rsbuild 1.36s dev 3.35s build 160ms hmr Vite 6.50s dev 1.98s build 130ms hmr webpack 21.40s dev 28.10s build 2.78s hmr > 📊 Benchmark results from [build-tools-performance](https://github.com/rstackjs/build-tools-performance) > . [#](https://rsbuild.rs/guide/start/#comparisons) Comparisons ------------------------------------------------------------ Rsbuild is comparable to [Vite](https://vitejs.dev/) , [Create React App](https://github.com/facebook/create-react-app) , and [Vue CLI](https://github.com/vuejs/vue-cli) . Each of these tools includes a built-in dev server, command-line tools, and sensible defaults for an out-of-the-box experience. ![](https://assets.rspack.rs/rsbuild/assets/rsbuild-1-0-build-tools.png) ### [#](https://rsbuild.rs/guide/start/#cra--vue-cli) CRA / Vue CLI You can think of Rsbuild as a modernized version of Create React App or Vue CLI, with these key differences: * The underlying bundler has been switched from webpack to Rspack, delivering 5 to 10 times better build performance. * It's decoupled from frontend UI frameworks and supports all frameworks via [plugins](https://rsbuild.rs/plugins/list/) , including React, Vue, Svelte, Solid, and more. * It is more extensible. You can extend Rsbuild through [configurations](https://rsbuild.rs/config/) , the [Plugin API](https://rsbuild.rs/plugins/dev/) , and the [JavaScript API](https://rsbuild.rs/api/start/) . ### [#](https://rsbuild.rs/guide/start/#vite) Vite Rsbuild has many similarities to Vite, as both aim to improve the frontend development experience. The main differences are: * **Production consistency**: Rsbuild uses Rspack for bundling in both development and production builds, ensuring high consistency between development and production outputs. Vite uses ESM during development for faster startup, but this approach can introduce inconsistencies between development and production outputs. * **Ecosystem compatibility**: Rsbuild is compatible with most webpack plugins and all Rspack plugins, while Vite is compatible with Rollup plugins. If you're using many plugins and loaders from the webpack ecosystem, migration to Rsbuild is more straightforward. * **Module Federation**: The Rsbuild team works closely with the [Module Federation](https://rsbuild.rs/guide/advanced/module-federation) development team, providing first-class support for Module Federation to help you develop large web applications with micro-frontend architecture. [#](https://rsbuild.rs/guide/start/#features) Features ------------------------------------------------------ Rsbuild has the following features: * **Easy to configure**: One of Rsbuild's goals is to give Rspack users out-of-the-box build capabilities so they can start web projects with zero configuration. Rsbuild also provides a semantic build configuration API to reduce the Rspack learning curve. * **Performance-focused**: Rsbuild integrates high-performance Rust-based tools from the community, including [Rspack](https://rspack.rs/) , [SWC](https://swc.rs/) , and [Lightning CSS](https://lightningcss.dev/) , delivering first-class build speed and development experience. * **Plugin ecosystem**: Rsbuild has a lightweight plugin system and includes a range of high-quality official plugins. It is also compatible with most webpack plugins and all Rspack plugins, allowing you to use existing community or in-house plugins without rewriting code. * **Stable artifacts**: Rsbuild places a strong focus on build artifact stability. It ensures consistent artifacts in development and production builds, and automatically handles syntax downgrading and polyfill injection. Rsbuild also provides plugins for type checking and artifact syntax validation to prevent quality and compatibility issues from reaching production code. * **Framework agnostic**: Rsbuild is not coupled to any frontend UI framework. It supports frameworks like React, Vue, Svelte, Solid, and Preact through plugins, with plans to support more UI frameworks from the community in the future. [#](https://rsbuild.rs/guide/start/#rstack) Rstack -------------------------------------------------- Rsbuild is part of Rstack, the fast, unified JavaScript toolchain for developers and agents. ![Rstack](https://assets.rspack.rs/rstack/rstack-overview.png) Rstack includes the following tools: | Name | Description | Version | | --- | --- | --- | | [Rspack](https://github.com/web-infra-dev/rspack) | Bundler | [![npm version](https://img.shields.io/npm/v/@rspack/core?style=flat-square&colorA=564341&colorB=EDED91)](https://npmjs.com/package/@rspack/core) | | [Rsbuild](https://github.com/web-infra-dev/rsbuild) | Build tool | [![npm version](https://img.shields.io/npm/v/@rsbuild/core?style=flat-square&colorA=564341&colorB=EDED91)](https://npmjs.com/package/@rsbuild/core) | | [Rslib](https://github.com/web-infra-dev/rslib) | Library development tool | [![npm version](https://img.shields.io/npm/v/@rslib/core?style=flat-square&colorA=564341&colorB=EDED91)](https://npmjs.com/package/@rslib/core) | | [Rspress](https://github.com/web-infra-dev/rspress) | Static site generator | [![npm version](https://img.shields.io/npm/v/@rspress/core?style=flat-square&colorA=564341&colorB=EDED91)](https://npmjs.com/package/@rspress/core) | | [Rsdoctor](https://github.com/web-infra-dev/rsdoctor) | Build analyzer | [![npm version](https://img.shields.io/npm/v/@rsdoctor/core?style=flat-square&colorA=564341&colorB=EDED91)](https://npmjs.com/package/@rsdoctor/core) | | [Rstest](https://github.com/web-infra-dev/rstest) | Testing framework | [![npm version](https://img.shields.io/npm/v/@rstest/core?style=flat-square&colorA=564341&colorB=EDED91)](https://npmjs.com/package/@rstest/core) | | [Rslint](https://github.com/web-infra-dev/rslint) | Linter | [![npm version](https://img.shields.io/npm/v/@rslint/core?style=flat-square&colorA=564341&colorB=EDED91)](https://npmjs.com/package/@rslint/core) | [#](https://rsbuild.rs/guide/start/#links) Links ------------------------------------------------ * [awesome-rstack](https://github.com/rstackjs/awesome-rstack) : A curated list of awesome things related to Rstack. * [agent-skills](https://github.com/rstackjs/agent-skills) : A collection of Agent Skills for Rstack. * [rstack-examples](https://github.com/rstackjs/rstack-examples) : Examples showcasing Rstack tools. * [storybook-rsbuild](https://github.com/rstackjs/storybook-rsbuild) : Storybook builder powered by Rsbuild. * [rsbuild-plugin-template](https://github.com/rstackjs/rsbuild-plugin-template) : Use this template to create your own Rsbuild plugin. * [rstack-design-resources](https://github.com/rstackjs/rstack-design-resources) : Design resources for Rstack. [#](https://rsbuild.rs/guide/start/#community) Community -------------------------------------------------------- Come and chat with us on [Discord](https://discord.gg/XsaKEEk4mW) ! The Rstack team and users are active there, and we're always looking for contributions. [#](https://rsbuild.rs/guide/start/#online-example) Online example ------------------------------------------------------------------ Try Rsbuild online with the [StackBlitz example](https://stackblitz.com/~/github.com/rstackjs/rsbuild-stackblitz-example) . [#](https://rsbuild.rs/guide/start/#next-step) Next step -------------------------------------------------------- Next, you may want to: [Quick start\ \ Learn how to use Rsbuild](https://rsbuild.rs/guide/start/quick-start) [All features\ \ Learn all features of Rsbuild](https://rsbuild.rs/guide/start/features) [Support Rsbuild\ \ Support us with a star ⭐️](https://github.com/web-infra-dev/rsbuild) --- # dev.assetPrefix - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /config/dev/asset-prefix.md. MenuON THIS PAGE [#](https://rsbuild.rs/config/dev/asset-prefix#devassetprefix) dev.assetPrefix ============================================================================== Copy Markdown * **Type:** `boolean | string | 'auto'` * **Default:** [server.base](https://rsbuild.rs/config/server/base) Set the URL prefix of static assets in [development mode](https://rsbuild.rs/config/mode) . `assetPrefix` affects most static asset URLs, including JavaScript files, CSS files, images, videos, etc. If it is set incorrectly, these resources may return 404 errors. This config is only used in `development` mode. In `production` mode or `none` mode, use [output.assetPrefix](https://rsbuild.rs/config/output/asset-prefix) to configure the URL prefix. [#](https://rsbuild.rs/config/dev/asset-prefix#default-value) Default value --------------------------------------------------------------------------- The default value of `dev.assetPrefix` is the same as [server.base](https://rsbuild.rs/config/server/base) . When `server.base` is `/foo`, `index.html` and other static assets can be accessed through `http://localhost:3000/foo/`. When you customize `dev.assetPrefix`, keep its URL prefix consistent with `server.base` so assets stay accessible through the Rsbuild dev server. For example: rsbuild.config.ts export default { dev: { assetPrefix: '/foo/bar/', }, server: { base: '/foo', }, }; [#](https://rsbuild.rs/config/dev/asset-prefix#boolean-type) Boolean type ------------------------------------------------------------------------- If `assetPrefix` is set to `true`, the URL prefix will be `http://localhost:/`: rsbuild.config.ts export default { dev: { assetPrefix: true, }, }; The resource URL loaded in the browser is as follows: If `assetPrefix` is set to `false` or not set, `/` is used as the default value. [#](https://rsbuild.rs/config/dev/asset-prefix#string-type) String type ----------------------------------------------------------------------- When the value of `assetPrefix` is a `string` type, the string will be used as a prefix and automatically appended to the static resource URL. * For example, set to a path relative to the root directory: rsbuild.config.ts export default { dev: { assetPrefix: '/example/', }, }; The resource URL loaded in the browser is as follows: * For example, set to a complete URL: rsbuild.config.ts export default { dev: { assetPrefix: 'https://example.com/assets/', }, }; The resource URL loaded in the browser is as follows: ### [#](https://rsbuild.rs/config/dev/asset-prefix#port-placeholder) Port placeholder The port number that Rsbuild server listens on may change. For example, if the port is in use, Rsbuild will automatically increment the port number until it finds an available port. To avoid `dev.assetPrefix` becoming invalid due to port changes, you can use one of the following methods: * Enable [server.strictPort](https://rsbuild.rs/config/server/strict-port) . * Use the `` placeholder to refer to the current port number. Rsbuild will replace the placeholder with the actual port number it is listening on. rsbuild.config.ts export default { dev: { assetPrefix: 'http://localhost:/', }, }; [#](https://rsbuild.rs/config/dev/asset-prefix#path-types) Path types --------------------------------------------------------------------- The `assetPrefix` option accepts the following path types: * **absolute path**: The most common choice, including specific server paths like `/assets/`. * **'auto'**: Rspack will automatically calculate the path and generate relative paths based on file location. Tip It's not recommended to set assetPrefix as a relative path, such as `'./assets/'`. This is because when assets are at different path depths, using relative paths may cause assets to load incorrectly. [#](https://rsbuild.rs/config/dev/asset-prefix#compare-with-publicpath) Compare with `publicPath` ------------------------------------------------------------------------------------------------- The functionality of `dev.assetPrefix` is basically the same as the [output.publicPath](https://rspack.rs/config/output#outputpublicpath) config in Rspack. The differences from the native configuration are as follows: * `dev.assetPrefix` only takes effect in development mode. * `dev.assetPrefix` default value is the same as [server.base](https://rsbuild.rs/config/server/base) . * `dev.assetPrefix` automatically appends a trailing `/` by default. * The value of `dev.assetPrefix` is written to the [process.env.ASSET\_PREFIX](https://rsbuild.rs/guide/advanced/env-vars#processenvasset_prefix) environment variable (can only be accessed in client code). [#](https://rsbuild.rs/config/dev/asset-prefix#dynamic-asset-prefix) Dynamic asset prefix ----------------------------------------------------------------------------------------- Use the `import.meta.rspackPublicPath` variable provided by Rspack to dynamically set the URL prefix of static assets in JavaScript code. See [Rspack - Dynamically set publicPath](https://rspack.rs/guide/features/asset-base-path#dynamically-set-publicpath) . --- # Vue - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/framework/vue.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/framework/vue#vue) Vue =================================================== Copy Markdown This document explains how to build Vue applications with Rsbuild, including Vue 2 support. [#](https://rsbuild.rs/guide/framework/vue#create-a-vue-application) Create a Vue application --------------------------------------------------------------------------------------------- Create a Vue application with Rsbuild using [create-rsbuild](https://rsbuild.rs/guide/start/quick-start#create-an-rsbuild-application) . Run this command: npm yarn pnpm bun npm create rsbuild@latest yarn create rsbuild pnpm create rsbuild@latest bun create rsbuild@latest Then select `Vue` when prompted to "Select framework". [#](https://rsbuild.rs/guide/framework/vue#vue-3) Vue 3 ------------------------------------------------------- ### [#](https://rsbuild.rs/guide/framework/vue#use-vue-in-an-existing-project) Use Vue in an existing project To compile Vue SFC (Single File Components), register the Rsbuild [Vue plugin](https://rsbuild.rs/plugins/list/plugin-vue) . The plugin automatically adds the necessary configuration for Vue builds. For example, register in `rsbuild.config.ts`: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginVue } from '@rsbuild/plugin-vue'; export default defineConfig({ plugins: [pluginVue()], }); Tip For projects using Vue CLI, you can refer to the [Vue CLI Migration Guide](https://rsbuild.rs/guide/migration/vue-cli) . ### [#](https://rsbuild.rs/guide/framework/vue#use-the-jsx-syntax-of-vue) Use the JSX syntax of Vue To use the JSX syntax of Vue, you also need to register the [@rsbuild/plugin-vue-jsx](https://github.com/rstackjs/rsbuild-plugin-vue-jsx) . ### [#](https://rsbuild.rs/guide/framework/vue#typescript-support) TypeScript support Rsbuild supports compiling TypeScript by default. Please refer to the [TypeScript - IDE Support](https://vuejs.org/guide/typescript/overview.html#ide-support) section of the Vue documentation to learn how to set up Vue TypeScript support in your IDE. [#](https://rsbuild.rs/guide/framework/vue#vue-2) Vue 2 ------------------------------------------------------- ### [#](https://rsbuild.rs/guide/framework/vue#use-vue-2-in-an-existing-project) Use Vue 2 in an existing project To compile Vue SFC (Single File Components), you need to register the Rsbuild [Vue 2 plugin](https://github.com/rstackjs/rsbuild-plugin-vue2) . The plugin will automatically add the necessary configuration for Vue builds. For example, register in `rsbuild.config.ts`: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginVue2 } from '@rsbuild/plugin-vue2'; export default defineConfig({ plugins: [pluginVue2()], }); Tip * The Vue 2 plugin only supports Vue >= 2.7.0. * For projects using Vue CLI, you can refer to the [Vue CLI Migration Guide](https://rsbuild.rs/guide/migration/vue-cli) . ### [#](https://rsbuild.rs/guide/framework/vue#use-the-jsx-syntax-of-vue-1) Use the JSX syntax of Vue To use the JSX syntax of Vue, you also need to register the [@rsbuild/plugin-vue2-jsx](https://github.com/rstackjs/rsbuild-plugin-vue2-jsx) . ### [#](https://rsbuild.rs/guide/framework/vue#type-declarations) Type declarations In a TypeScript project, you need to add type definitions for `*.vue` files so that TypeScript can recognize them correctly. Create `env.d.ts` in the `src` directory and add the following content: src/env.d.ts declare module '*.vue' { import Vue from 'vue'; export default Vue; } [#](https://rsbuild.rs/guide/framework/vue#vue-devtools) Vue DevTools --------------------------------------------------------------------- Vue DevTools is designed to enhance the Vue developer experience; it can significantly improve your productivity and debugging capabilities when working with Vue applications. For Vue applications built with Rsbuild, use [vue-devtools-rstack](https://github.com/OskarLebuda/vue-devtools-rstack) to integrate Vue DevTools. --- # Bundle size optimization - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/optimization/optimize-bundle.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/optimization/optimize-bundle#bundle-size-optimization) Bundle size optimization ============================================================================================================ Copy Markdown Bundle size optimization is critical for production builds because it directly affects user experience. This document covers common bundle size optimization methods in Rsbuild. [#](https://rsbuild.rs/guide/optimization/optimize-bundle#reduce-duplicate-dependencies) Reduce duplicate dependencies ---------------------------------------------------------------------------------------------------------------------- Web applications commonly bundle multiple versions of third-party dependencies. Duplicate dependencies increase bundle size and slow down builds. ### [#](https://rsbuild.rs/guide/optimization/optimize-bundle#detect-duplicate-dependencies) Detect duplicate dependencies You can use [Rsdoctor](https://rsdoctor.rs/) to detect duplicate dependencies in your project. Rsdoctor analyzes the build, identifies duplicate bundled dependencies, and displays them visually: ![](https://assets.rspack.rs/rsbuild/assets/rsdoctor-duplicated-packages.png) For more details, see [Rsdoctor - Duplicate Dependency Problem](https://rsdoctor.rs/blog/topic/duplicate-pkg-problem) . ### [#](https://rsbuild.rs/guide/optimization/optimize-bundle#eliminate-duplicate-dependencies) Eliminate duplicate dependencies You can eliminate duplicate dependencies using your package manager. * Rsbuild provides the [resolve.dedupe](https://rsbuild.rs/config/resolve/dedupe) config, which forces specified packages to resolve from the project root directory, removing duplicate packages. * If you are using `pnpm >= 7.26.0`, you can use the [pnpm dedupe](https://pnpm.io/cli/dedupe) command to upgrade and eliminate duplicate dependencies. pnpm dedupe * If you are using `pnpm < 7.26.0`, you can use [pnpm-deduplicate](https://github.com/ocavue/pnpm-deduplicate) to analyze duplicate dependencies, then update dependencies or declare [pnpm overrides](https://pnpm.io/settings#overrides) to merge them. npx pnpm-deduplicate --list * If you are using `yarn`, you can use [yarn-deduplicate](https://github.com/scinos/yarn-deduplicate) to automatically merge duplicate dependencies: npx yarn-deduplicate && yarn [#](https://rsbuild.rs/guide/optimization/optimize-bundle#use-lightweight-libraries) Use lightweight libraries -------------------------------------------------------------------------------------------------------------- We recommend using lightweight libraries in your project, such as replacing [moment](https://momentjs.com/) with [day.js](https://day.js.org/) . To identify the largest third-party libraries in your project, analyze bundle size with Rsdoctor. For more details, see [Use Rsdoctor](https://rsbuild.rs/guide/debug/rsdoctor) . [#](https://rsbuild.rs/guide/optimization/optimize-bundle#adjust-browserslist) Adjust browserslist -------------------------------------------------------------------------------------------------- Rsbuild compiles code based on your project's browserslist config and injects polyfills. If your project doesn't need to support legacy browsers, adjust the browserslist to drop older targets, reducing compilation overhead for syntax transforms and polyfills. Rsbuild's default Browserslist config is: ['chrome >= 107', 'edge >= 107', 'firefox >= 104', 'safari >= 16']; For example, if you only need to be compatible with the latest version of Chrome, you can change it to: ['last 1 chrome version']; Tip For more details on configuring Browserslist, see [Browserslist](https://rsbuild.rs/guide/advanced/browserslist) . [#](https://rsbuild.rs/guide/optimization/optimize-bundle#use-polyfill-on-demand) Use polyfill on demand -------------------------------------------------------------------------------------------------------- If your project's [output.polyfill](https://rsbuild.rs/config/output/polyfill) is set to `'entry'` and you're certain that third-party dependencies don't require additional polyfills, switch it to `usage`. In `usage` mode, Rsbuild analyzes your source code and injects only the required polyfills, reducing polyfill size. export default { output: { polyfill: 'usage', }, }; Tip For more details on polyfill usage, see [Browser compatibility](https://rsbuild.rs/guide/advanced/browser-compatibility) . [#](https://rsbuild.rs/guide/optimization/optimize-bundle#image-compression) Image compression ---------------------------------------------------------------------------------------------- In typical front-end projects, images often account for a large portion of the total bundle size. Reducing image size can meaningfully lower the overall bundle size. Enable image compression by registering a plugin in Rsbuild: rsbuild.config.ts import { pluginImageCompress } from '@rsbuild/plugin-image-compress'; export default { plugins: [pluginImageCompress()], }; See details in [@rsbuild/plugin-image-compress](https://github.com/rstackjs/rsbuild-plugin-image-compress) . [#](https://rsbuild.rs/guide/optimization/optimize-bundle#code-splitting) Code splitting ---------------------------------------------------------------------------------------- A well-designed code splitting strategy improves application load performance. By breaking code into appropriately sized chunks, you can leverage browser caching more effectively and reduce unnecessary network requests, leading to faster page loads. See [Code splitting](https://rsbuild.rs/guide/optimization/code-splitting) for details on how to apply code splitting. --- # Features FAQ - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/faq/features.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/faq/features#features-faq) Features FAQ ==================================================================== Copy Markdown ### [#](https://rsbuild.rs/guide/faq/features#how-to-import-a-ui-component-library-on-demand) How to import a UI component library on demand? To enable on-demand imports for a component library, configure [source.transformImport](https://rsbuild.rs/config/source/transform-import) . This works the same way as [babel-plugin-import](https://npmjs.com/package/babel-plugin-import) . export default { source: { transformImport: [\ {\ libraryName: 'my-components',\ libraryDirectory: 'es',\ style: true,\ },\ ], }, }; * * * ### [#](https://rsbuild.rs/guide/faq/features#how-to-run-eslint-during-compilation) How to run ESLint during compilation? To protect compilation performance, Rsbuild doesn't run ESLint checks during builds by default. If you need ESLint in the pipeline, use the [ESLint plugin](https://github.com/rstackjs/rsbuild-plugin-eslint) . * * * ### [#](https://rsbuild.rs/guide/faq/features#how-to-configure-cdn-path-for-static-assets) How to configure CDN path for static assets? To serve static assets like JS and CSS from a CDN, set the asset URL prefix with [output.assetPrefix](https://rsbuild.rs/config/output/asset-prefix) . export default { output: { assetPrefix: 'https://cdn.example.com/assets/', }, }; * * * ### [#](https://rsbuild.rs/guide/faq/features#how-to-remove-console-after-production-build) How to remove console after production build? In production builds, you can strip `console` calls to avoid shipping development logs. Rsbuild provides a built-in option for removing console statements. See [performance.removeConsole](https://rsbuild.rs/config/performance/remove-console) . * * * ### [#](https://rsbuild.rs/guide/faq/features#how-to-view-the-final-generated-rspack-configuration) How to view the final generated Rspack configuration? Use Rsbuild's debug mode to view the Rspack configuration that Rsbuild generates. Enable debug mode by setting the `DEBUG=rsbuild` environment variable when running a build. In this mode, the generated Rspack configuration is written to the `dist` directory. ➜ DEBUG=rsbuild pnpm dev ... rsbuild 10:00:00 configuration loaded from: /path/to/... rsbuild 10:00:00 registering default plugins rsbuild 10:00:00 default plugins registered ... config inspection completed, generated files: - Rsbuild config: /root/my-project/dist/.rsbuild/rsbuild.config.mjs - Rspack config (web): /root/my-project/dist/.rsbuild/rspack.config.web.mjs * * * ### [#](https://rsbuild.rs/guide/faq/features#how-to-ignore-specific-warnings) How to ignore specific warnings? By default, Rsbuild prints all errors and warnings from the build. If a noisy third-party package produces many warnings, you can silence specific messages with Rspack's `ignoreWarnings` configuration. export default { tools: { rspack: { ignoreWarnings: [/Using \/ for division outside of calc()/], }, }, }; For details, please refer to: [ignoreWarnings](https://rspack.rs/config/other-options#ignorewarnings) . --- # CSS-in-JS - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/styling/css-in-js.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/styling/css-in-js#css-in-js) CSS-in-JS =================================================================== Copy Markdown This document outlines how to use common CSS-in-JS libraries in Rsbuild. Although the examples are based on React, some CSS-in-JS libraries (such as [vanilla-extract](https://rsbuild.rs/guide/styling/css-in-js#use-vanilla-extract) ) also support other frameworks. ### [#](https://rsbuild.rs/guide/styling/css-in-js#use-emotion) Use Emotion Rsbuild supports compiling [Emotion](https://github.com/emotion-js/emotion) . Add the following configuration to enable it: * [swcReactOptions.importSource](https://rsbuild.rs/plugins/list/plugin-react#swcreactoptions) * [@swc/plugin-emotion](https://npmjs.com/package/@swc/plugin-emotion) rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; export default defineConfig({ plugins: [\ pluginReact({\ swcReactOptions: {\ importSource: '@emotion/react',\ },\ }),\ ], tools: { swc: { jsc: { experimental: { plugins: [['@swc/plugin-emotion', {}]], }, }, }, }, }); > Refer to this example: [emotion](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/emotion) > . ### [#](https://rsbuild.rs/guide/styling/css-in-js#use-styled-jsx) Use styled-jsx You can use [styled-jsx](https://github.com/vercel/styled-jsx) through [@swc/plugin-styled-jsx](https://npmjs.com/package/@swc/plugin-styled-jsx) : rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; export default defineConfig({ plugins: [pluginReact()], tools: { swc: { jsc: { experimental: { plugins: [['@swc/plugin-styled-jsx', {}]], }, }, }, }, }); Make sure to choose the SWC plugin version that matches your current `@swc/core` version so SWC can run correctly. See [tools.swc](https://rsbuild.rs/config/tools/swc) . > Refer to this example: [styled-jsx](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/styled-jsx) > . ### [#](https://rsbuild.rs/guide/styling/css-in-js#use-vanilla-extract) Use vanilla-extract Rsbuild supports [@vanilla-extract/webpack-plugin](https://npmjs.com/package/@vanilla-extract/webpack-plugin) . Add the following config to use [vanilla-extract](https://github.com/vanilla-extract-css/vanilla-extract) : Currently, Rspack has an [HMR issue](https://github.com/web-infra-dev/rsbuild/issues/6049) when `splitChunks` is used with `@vanilla-extract/webpack-plugin`. In development mode, you can use a dedicated `splitChunks` configuration to avoid the issue. rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; import { VanillaExtractPlugin } from '@vanilla-extract/webpack-plugin'; export default defineConfig({ plugins: [\ pluginReact({\ reactRefreshOptions: {\ exclude: [/\.css\.ts$/],\ },\ }),\ ], splitChunks: { cacheGroups: { vanilla: { test: /@vanilla-extract\/webpack-plugin/, // make sure that chunks containing modules created by @vanilla-extract/webpack-plugin have stable IDs // in development mode to avoid HMR issues name: process.env.NODE_ENV === 'development' && 'vanilla', chunks: 'all', }, }, }, tools: { rspack: { plugins: [new VanillaExtractPlugin()], }, }, }); > Refer to this example: [vanilla-extract](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/vanilla-extract) > . #### [#](https://rsbuild.rs/guide/styling/css-in-js#static-assets) Static assets When importing static assets, use import syntax: src/App.css.ts import { style } from '@vanilla-extract/css'; import logoUrl from './logo.png'; export const containerStyle = style({ backgroundImage: `url(${logoUrl})`, }); Since `logoUrl` already resolves to the dist directory, `css-loader` doesn't need to process it again. Disable CSS URL processing via [tools.cssLoader.url](https://rsbuild.rs/config/tools/css-loader) to avoid module resolution errors: rsbuild.config.ts export default defineConfig({ // ... other config tools: { cssLoader: { url: false, }, }, }); > Reference: [#6215](https://github.com/web-infra-dev/rsbuild/issues/6215) > . ### [#](https://rsbuild.rs/guide/styling/css-in-js#use-stylex) Use StyleX You can use [StyleX](https://github.com/facebook/stylex) via [unplugin-stylex](https://github.com/eryue0220/unplugin-stylex) : rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; import stylexPlugin from 'unplugin-stylex/rspack'; export default defineConfig({ plugins: [pluginReact()], tools: { rspack: { plugins: [stylexPlugin()], }, }, }); > Refer to this example: [stylex](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/stylex) > . ### [#](https://rsbuild.rs/guide/styling/css-in-js#use-styled-components) Use styled-components [styled-components](https://github.com/styled-components/styled-components) is a runtime library, so you can use it directly without additional configuration. Rsbuild supports compiling styled-components, improving the debugging experience and adding SSR support to styled-components. To use styled-components, we recommend using the [@rsbuild/plugin-styled-components](https://github.com/rsbuild-contrib/rsbuild-plugin-styled-components) . rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginStyledComponents } from '@rsbuild/plugin-styled-components'; export default defineConfig({ plugins: [pluginStyledComponents()], }); > Refer to this example: [styled-components](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/styled-components) > . Tip styled-components is no longer recommended for new projects as it is in [maintenance mode](https://opencollective.com/styled-components/updates/thank-you) . --- # UnoCSS - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/styling/unocss.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/styling/unocss#unocss) UnoCSS ========================================================== Copy Markdown [UnoCSS](https://unocss.dev/) is the instant atomic CSS engine, which is designed to be flexible and extensible. The core is un-opinionated, and all the CSS utilities are provided via presets. You can integrate UnoCSS in Rsbuild via PostCSS plugins. [#](https://rsbuild.rs/guide/styling/unocss#installing-unocss) Installing UnoCSS -------------------------------------------------------------------------------- You need to install `unocss` and `@unocss/postcss` first. npm yarn pnpm bun deno npm add unocss @unocss/postcss -D yarn add unocss @unocss/postcss -D pnpm add unocss @unocss/postcss -D bun add unocss @unocss/postcss -D deno add npm:unocss npm:@unocss/postcss -D [#](https://rsbuild.rs/guide/styling/unocss#configuring-postcss) Configuring PostCSS ------------------------------------------------------------------------------------ You can register the `unocss` PostCSS plugin through [postcss.config.mjs](https://github.com/webpack/postcss-loader#config) or [tools.postcss](https://rsbuild.rs/config/tools/postcss) . postcss.config.mjs import UnoCSS from '@unocss/postcss'; export default { plugins: [UnoCSS()], }; Rsbuild uses [Lightning CSS](https://rsbuild.rs/guide/styling/css-usage#lightning-css) to add vendor prefixes by default, so you only need to register the `UnoCSS` plugin. [#](https://rsbuild.rs/guide/styling/unocss#configuring-unocss) Configuring UnoCSS ---------------------------------------------------------------------------------- Create a `uno.config.ts` file in the root directory of your project and add the following content: uno.config.ts import { defineConfig, presetUno } from 'unocss'; export default defineConfig({ content: { filesystem: ['./src/**/*.{html,js,ts,jsx,tsx}'], }, presets: [presetUno()], }); Tip The above configuration is for reference only and can be modified to suit the needs of your project. [#](https://rsbuild.rs/guide/styling/unocss#importing-css) Importing CSS ------------------------------------------------------------------------ Add the `@unocss` directives in your CSS entry file: main.css @unocss preflights; @unocss default; Depending on your needs, you can selectively import the CSS styles provided by UnoCSS. Please refer to the [unocss documentation](https://unocss.dev/integrations/postcss#usage) for detailed usage of the UnoCSS. [#](https://rsbuild.rs/guide/styling/unocss#done) Done ------------------------------------------------------ You have now completed all the steps to integrate UnoCSS in Rsbuild! You can use UnoCSS's utility classes in any component or HTML, such as:

Hello world!

For more usage details, refer to the [UnoCSS documentation](https://unocss.dev/) . [#](https://rsbuild.rs/guide/styling/unocss#vs-code-extension) VS Code extension -------------------------------------------------------------------------------- UnoCSS provides a [VS Code Extension](https://unocss.dev/integrations/vscode) plugin for VS Code to decoration and tooltip for matched utilities. You can install this plugin in VS Code to enable more intelligent features. --- # Configure SWC - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/configuration/swc.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/configuration/swc#configure-swc) Configure SWC =========================================================================== Copy Markdown [SWC](https://github.com/swc-project/swc) (Speedy Web Compiler) is a transformer and minimizer for JavaScript and TypeScript based on Rust. SWC provides similar functionality to Babel and Terser, and it is 20x faster than Babel on a single thread and 70x faster on four cores. Rsbuild enables the following SWC features by default: * Transform JavaScript and TypeScript code using Rspack's [builtin:swc-loader](https://rspack.rs/guide/features/builtin-swc-loader) , which is the Rust version of [swc-loader](https://github.com/swc-project/pkgs/tree/main/packages/swc-loader) . * Minify JavaScript code using Rspack's [SwcJsMinimizerRspackPlugin](https://rspack.rs/plugins/rspack/swc-js-minimizer-rspack-plugin) . [#](https://rsbuild.rs/guide/configuration/swc#loader-options) Loader options ----------------------------------------------------------------------------- The options for `builtin:swc-loader` are the same as those for the JS version of `swc-loader`. Rsbuild exposes some options to configure `builtin:swc-loader`: * [tools.swc](https://rsbuild.rs/config/tools/swc) :to configure the options for `builtin:swc-loader`. * [source.include](https://rsbuild.rs/config/source/include) :to specify files that need to be compiled by SWC. * [source.exclude](https://rsbuild.rs/config/source/exclude) :to exclude files that do not need to be compiled by SWC. Here are some examples: ### [#](https://rsbuild.rs/guide/configuration/swc#register-swc-plugin) Register SWC plugin `tools.swc` can be used to register SWC's Wasm plugins, for example, registering [@swc/plugin-styled-components](https://npmjs.com/package/@swc/plugin-styled-components) : export default { tools: { swc: { jsc: { experimental: { plugins: [['@swc/plugin-styled-components', {}]], }, }, }, }, }; > You can check out the [awesome-swc](https://github.com/swc-contrib/awesome-swc) > repository to see the SWC plugins available in the community. ### [#](https://rsbuild.rs/guide/configuration/swc#swc-plugin-version) SWC plugin version Please note that the SWC plugin is still an experimental feature, and the SWC Wasm plugin is currently not backward compatible. The version of the SWC plugin is closely tied to the version of `swc_core` that Rspack depends on. This means that you must choose an SWC plugin that matches the current version of `swc_core` to ensure that it works properly. If the version of the SWC plugin you are using does not match the version of `swc_core` that Rspack depends on, Rspack will throw an error during the build process. Please refer to [Rspack FAQ - SWC Plugin Version Unmatched](https://rspack.rs/errors/swc-plugin-version) for more information. ### [#](https://rsbuild.rs/guide/configuration/swc#enable-emotion-support) Enable Emotion support Example of enabling the Emotion support using the `builtin:swc-loader`: export default { tools: { swc: { jsc: { experimental: { plugins: [['@swc/plugin-emotion', {}]], }, }, }, }, }; For more options, please refer to [@swc/plugin-emotion](https://npmjs.com/package/@swc/plugin-emotion) . ### [#](https://rsbuild.rs/guide/configuration/swc#enable-relay-support) Enable Relay support Example of enabling the Relay support using the `builtin:swc-loader`: export default { tools: { swc: { jsc: { experimental: { plugins: [['@swc/plugin-relay', {}]], }, }, }, }, }; For more options, please refer to [@swc/plugin-relay](https://npmjs.com/package/@swc/plugin-relay) . [#](https://rsbuild.rs/guide/configuration/swc#minimizer-options) Minimizer options ----------------------------------------------------------------------------------- Rsbuild provides the [output.minify.js](https://rsbuild.rs/config/output/minify) option to configure the SwcJsMinimizerRspackPlugin. Here are some examples: ### [#](https://rsbuild.rs/guide/configuration/swc#exclude-files) Exclude files You can exclude certain files from being minified using the `exclude` option: export default { output: { minify: { jsOptions: { exclude: /foo\/bar/, }, }, }, }; [#](https://rsbuild.rs/guide/configuration/swc#switching-minifier) Switching minifier ------------------------------------------------------------------------------------- See [output.minify - Switching minifier](https://rsbuild.rs/config/output/minify#switching-minifier) to learn how to switch to other JavaScript minifier. --- # Browser compatibility - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/advanced/browser-compatibility.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/advanced/browser-compatibility#browser-compatibility) Browser compatibility ======================================================================================================== Copy Markdown Rsbuild supports [modern browsers](https://rsbuild.rs/guide/advanced/browserslist#default-values) by default and provides syntax and API downgrade capabilities to ensure compatibility with legacy browsers that support ES5 (such as IE11). This chapter explains how to use Rsbuild's features to handle browser compatibility issues. [#](https://rsbuild.rs/guide/advanced/browser-compatibility#set-browserslist) Set browserslist ---------------------------------------------------------------------------------------------- Before addressing compatibility issues, decide which browsers your project needs to support and add the corresponding browserslist config. * If you haven't set browserslist yet, please read the [Browserslist](https://rsbuild.rs/guide/advanced/browserslist) chapter first. * If you have set a browserslist, Rsbuild automatically compiles code to match that scope, downgrades JavaScript and CSS syntax, and injects required polyfills. In most cases, you can safely use modern ECMAScript features without worrying about compatibility. After setting the browserslist, if you still encounter compatibility issues, continue reading to find solutions. What is polyfill A polyfill is code that provides newer features to older browsers that don't support them natively. It fills gaps in older implementations of web standards, letting developers use modern features without worrying about whether they'll work in legacy browsers. For example, if a browser doesn't support the `Array.prototype.flat()` method, a polyfill can add that functionality so code using `Array.prototype.flat()` still runs. Polyfills are commonly used to keep web applications working across a wide range of browsers, including older ones. [#](https://rsbuild.rs/guide/advanced/browser-compatibility#background-knowledge) Background knowledge ------------------------------------------------------------------------------------------------------ Before you tackle compatibility issues, review the following background so you can address them effectively. ### [#](https://rsbuild.rs/guide/advanced/browser-compatibility#syntax-downgrade-and-api-downgrade) Syntax downgrade and API downgrade When you use higher-version syntax and APIs in your project, you need to downgrade two parts to make the compiled code run reliably in older browsers: syntax and APIs. **Rsbuild downgrades syntax through transpilation and downgrades APIs through polyfill injection.** > Syntax and APIs are not tightly coupled. Browser vendors ship syntax or APIs at different times based on specifications and their own priorities, so browsers released in the same period may not support the same syntax or APIs. In practice, syntax and APIs are handled separately. ### [#](https://rsbuild.rs/guide/advanced/browser-compatibility#syntax-transpilation) Syntax transpilation **Syntax is a set of rules for how a programming language organizes code**. Code that doesn't follow these rules cannot be correctly recognized by the programming language's engine and therefore cannot run. In JavaScript, the following are examples of syntax rules: * In `const foo = 1`, `const` means to declare an immutable constant. * In `foo?.bar?.baz`, `?.` indicates optional chaining of access properties. * In `async function () {}`, `async` means to declare an asynchronous function. Because different browser parsers support different syntax, and older engines support even less, certain syntax can trigger errors when older browsers try to parse the AST. For example, the following code will cause an error in IE or an older version of Node.js: const foo = {}; foo?.bar(); When this code runs in an older version of Node.js, the following error message appears: SyntaxError: Unexpected token. at Object.exports.runInThisContext (vm.js:73:16) at Object. ([eval]-wrapper:6:22) at Module._compile (module.js:460:26) at evalScript (node.js:431:25) at startup (node.js:90:7) at node.js:814:3 The error makes it clear that this is a syntax issue, meaning older versions of the engine do not support this syntax. **Syntax cannot be supported by polyfills or shims**. To run syntax that's not originally supported in an older browser, you need to transpile the code into syntax the older engine can support. Transpile the above code into the following to run in older engines: var foo = {}; foo === null || foo === void 0 ? void 0 : foo.bar(); After transpilation, the syntax of the code has changed, and syntax the older engine cannot understand has been replaced with syntax it can understand, **but the meaning of the code itself hasn't changed**. If the engine encounters unrecognized syntax when converting to AST, it will report a syntax error and abort execution. In this case, if your project doesn't use capabilities like SSR or SSG, the page will be blank and unusable. If the code is successfully converted to AST, the engine will convert it into executable code and run it normally. ### [#](https://rsbuild.rs/guide/advanced/browser-compatibility#api-polyfill) API polyfill JavaScript is an interpreted scripting language, unlike compiled languages like Rust. Rust checks function calls during compilation, but JavaScript doesn't know whether a function exists until it runs that line of code, so some errors only appear at runtime. For example: var str = 'Hello world!'; console.log(str.notExistedMethod()); The above code uses valid syntax and can be converted to an AST during the first stage of engine runtime, but when it actually runs, the method `notExistedMethod` does not exist on `String.prototype`, so an error is reported: Uncaught TypeError: str.notExistedMethod is not a function at :2:17 With ECMAScript iterations, new methods are added to built-in objects. For example, `String.prototype.replaceAll` was introduced in ES2021. The `replaceAll` method doesn't exist in `String.prototype` of most browser engines before 2021, so the following code works in the latest Chrome but not in earlier versions: 'abc'.replaceAll('abc', 'xyz'); To address the lack of `replaceAll` in older browsers, we can extend the `String.prototype` object and add the `replaceAll` method to it. For example: // The implementation of this polyfill does not necessarily conform to the standard, it is only used as an example. if (!String.prototype.replaceAll) { String.prototype.replaceAll = function (str, newStr) { // If a regex pattern if ( Object.prototype.toString.call(str).toLowerCase() === '[object regexp]' ) { return this.replace(str, newStr); } // If a string return this.replace(new RegExp(str, 'g'), newStr); }; } > This technique of providing implementations for legacy environments to align new APIs is called polyfill. [#](https://rsbuild.rs/guide/advanced/browser-compatibility#compilation-scope) Compilation scope ------------------------------------------------------------------------------------------------ By default, Rsbuild uses [SWC](https://rsbuild.rs/guide/configuration/swc) to compile all JavaScript and TypeScript modules, excluding JavaScript modules in the `node_modules` directory. This approach is designed to avoid impacting build performance when downgrading all third-party dependencies while also preventing potential issues from redundantly downgrading pre-compiled third-party dependencies. ### [#](https://rsbuild.rs/guide/advanced/browser-compatibility#source-code) Source code The source code of the current project will be downgraded by default, so you don't need to add additional config, just make sure that the browserslist config is set correctly. ### [#](https://rsbuild.rs/guide/advanced/browser-compatibility#third-party-dependencies) Third-party dependencies When you find that a third-party dependency causes compatibility issues, you can add this dependency to Rsbuild's [source.include](https://rsbuild.rs/config/source/include) config. This makes Rsbuild perform extra compilation for that dependency. Taking the npm package `query-string` as an example, you can add the following config: rsbuild.config.ts import path from 'node:path'; export default { source: { include: [/node_modules[\\/]query-string[\\/]/], }, }; See [source.include](https://rsbuild.rs/config/source/include) for detailed usage. [#](https://rsbuild.rs/guide/advanced/browser-compatibility#polyfills) Polyfills -------------------------------------------------------------------------------- Rsbuild compiles JavaScript code using SWC and supports injecting polyfills such as [core-js](https://github.com/zloirock/core-js) and [@swc/helpers](https://npmjs.com/package/@swc/helpers) . In different usage scenarios, you may need different polyfill solutions. Rsbuild provides [output.polyfill](https://rsbuild.rs/config/output/polyfill) config to switch between different polyfill modes. ### [#](https://rsbuild.rs/guide/advanced/browser-compatibility#default-behavior) Default behavior Rsbuild does not inject any polyfills by default: export default { output: { polyfill: 'off', }, }; ### [#](https://rsbuild.rs/guide/advanced/browser-compatibility#usage-mode) Usage mode When you enable usage mode, Rsbuild will analyze the source code in the project and determine which polyfills need to be injected. For example, the code uses the `Map` object: var b = new Map(); After compilation, only the polyfills for `Map` will be injected into this file: import 'core-js/modules/es.map'; var b = new Map(); The advantage of this method is smaller injected polyfill size, which is suitable for projects with higher requirements on bundle size. The disadvantage is that polyfills may not be fully injected because third-party dependencies won't be compiled and downgraded by default, so the polyfills required by third-party dependencies won't be analyzed. If you need to analyze a third-party dependency, you also need to add it to [source.include](https://rsbuild.rs/config/source/include) config. The config of usage mode is: export default { output: { polyfill: 'usage', }, }; ### [#](https://rsbuild.rs/guide/advanced/browser-compatibility#entry-mode) Entry mode When using entry mode, Rsbuild will analyze which `core-js` methods need to be injected according to the browserslist set for the current project and inject them into the entry file of each page. Polyfills injected this way are more comprehensive, eliminating concerns about polyfill issues in project source code and third-party dependencies. However, because some unused polyfill code is included, the bundle size may increase. The config of entry mode is: export default { output: { polyfill: 'entry', }, }; ### [#](https://rsbuild.rs/guide/advanced/browser-compatibility#ua-polyfill) UA polyfill Cloudflare provides a [polyfill service](https://cdnjs.cloudflare.com/polyfill/) that automatically generates polyfill bundles based on the user's browser User-Agent. You can use the [html.tags](https://rsbuild.rs/config/html/tags) config of Rsbuild to inject scripts. For example, to inject a ``) .join('\n'); const styleTags = css .map((file) => ``) .join('\n'); return ` ${scriptTags} ${styleTags}
`; } [#](https://rsbuild.rs/guide/advanced/ssr#examples) Examples ------------------------------------------------------------ * [SSR + Express Example](https://github.com/rstackjs/rstack-examples/blob/main/rsbuild/ssr-express) * [SSR + Express + Manifest Example](https://github.com/rstackjs/rstack-examples/blob/main/rsbuild/ssr-express-with-manifest) [#](https://rsbuild.rs/guide/advanced/ssr#ssr-specific-plugins) SSR-specific plugins ------------------------------------------------------------------------------------ When developing Rsbuild plugins, if you need to add specific logic for SSR, you can distinguish it by `target`. * Modify Rsbuild configuration for SSR via [modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) : export const myPlugin = () => ({ name: 'my-plugin', setup(api) { api.modifyEnvironmentConfig((config) => { if (config.target === 'node') { // SSR-specific Rsbuild config } }); }, }); * Modify Rspack configuration for SSR via [modifyRspackConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrspackconfig) : export const myPlugin = () => ({ name: 'my-plugin', setup(api) { api.modifyRspackConfig((config, { target }) => { if (target === 'node') { // SSR-specific Rspack config } }); }, }); * Transform code for SSR and client separately via [transform](https://rsbuild.rs/plugins/dev/core#apitransform) : export const myPlugin = () => ({ name: 'my-plugin', setup(api) { api.transform({ test: /foo\.js$/, targets: ['web'] }, ({ code }) => { // transform client code }); api.transform({ test: /foo\.js$/, targets: ['node'] }, ({ code }) => { // transform server code }); }, }); [#](https://rsbuild.rs/guide/advanced/ssr#keep-asset-urls-consistent) Keep asset URLs consistent ------------------------------------------------------------------------------------------------ In multi-environment SSR, keep [output.assetPrefix](https://rsbuild.rs/config/output/asset-prefix) and public asset [output.distPath](https://rsbuild.rs/config/output/dist-path) values consistent between server and client builds. This helps ensure that the server gets the same asset path as the client when using queries such as `?url`. rsbuild.config.ts const assetPaths = { css: 'assets/css', image: 'assets/image', }; export default { output: { assetPrefix: '/', }, environments: { web: { output: { target: 'web', distPath: { root: 'dist/client', ...assetPaths, }, }, }, node: { output: { target: 'node', distPath: { root: 'dist/server', ...assetPaths, }, }, }, }, }; --- # Multi-environment builds - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/advanced/environments.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/advanced/environments#multi-environment-builds) Multi-environment builds ===================================================================================================== Copy Markdown Rsbuild can build outputs for multiple environments in a single run. Use [environments](https://rsbuild.rs/config/environments) to build them in parallel and set a separate Rsbuild config for each one. [#](https://rsbuild.rs/guide/advanced/environments#what-is-an-environment) What is an environment ------------------------------------------------------------------------------------------------- The `environment` refers to the runtime environment for build output. Common environments include browsers, Node.js, and Workers. Rsbuild allows you to define custom environment names and set build options for each environment individually. A typical scenario is server-side rendering (SSR). You can define two environments, `web` and `node`, where the build targets ([output.target](https://rsbuild.rs/config/output/target) ) are `web` and `node`. These are used for client-side rendering (CSR) and server-side rendering (SSR) scenarios. You can also define different environments for the same build target, for example: * Define `rsc` and `ssr` environments, both targeting `node`, used separately for React Server Components and SSR. * Define `desktop` and `mobile` environments, both targeting `web`, used separately for desktop and mobile browsers. Without the `environments` configuration, you would need to define multiple configurations for these scenarios and run multiple independent Rsbuild builds. With `environments`, you can build every output in a single Rsbuild run (Rsbuild achieves this using Rspack's [MultiCompiler](https://rspack.rs/api/javascript-api/compiler#multicompiler) ). In Rsbuild, each `environment` is associated with an Rsbuild configuration, an Rspack configuration, and a set of build outputs. Plugin authors can tailor the build for a specific environment—modifying configs, registering or removing plugins, adjusting Rspack rules, or inspecting asset information—based on the environment name. [#](https://rsbuild.rs/guide/advanced/environments#environment-configs) Environment configs ------------------------------------------------------------------------------------------- Rsbuild supports defining different Rsbuild configurations for each environment through [environments](https://rsbuild.rs/config/environments) . For example, if your project needs SSR support, you need to define different configurations for the client and server. You can define web and node environments. rsbuild.config.ts export default { environments: { // Configure the web environment for browsers web: { source: { entry: { index: './src/index.client.js', }, }, output: { // Use 'web' target for the browser outputs target: 'web', }, resolve: { alias: { '@common': './src/client/common', }, }, }, // Configure the node environment for SSR node: { source: { entry: { index: './src/index.server.js', }, }, output: { // Use 'node' target for the Node.js outputs target: 'node', distPath: { root: 'dist/server', }, }, resolve: { alias: { '@common': './src/server/common', }, }, }, }, }; ### [#](https://rsbuild.rs/guide/advanced/environments#config-merging) Config merging If you configure `environments`, Rsbuild will merge the config in `environments` with the outer base config. When merging, the config in `environments` has higher priority. In the example above, after merging the configs, Rsbuild generates two standalone environment configs for building web and node environments. * **web environments config**: Generated by merging base config with `environments.web` * **node environments config**: Generated by merging base config with `environments.node` Then, Rsbuild will use these environment configurations to internally generate two Rspack configs and execute a single build using Rspack’s MultiCompiler. ### [#](https://rsbuild.rs/guide/advanced/environments#debug-config) Debug config When you execute the command `npx rsbuild inspect` in the project root directory, you will see the following output: * `rsbuild.config.[name].mjs`: The Rsbuild config used for a certain environment during build. * `rspack.config.[name].mjs`: The Rspack config corresponding to a certain environment when building. ➜ npx rsbuild inspect config inspection completed, generated files: - Rsbuild config (web): /project/dist/.rsbuild/rsbuild.config.web.mjs - Rsbuild config (node): /project/dist/.rsbuild/rsbuild.config.node.mjs - Rspack config (web): /project/dist/.rsbuild/rspack.config.web.mjs - Rspack config (node): /project/dist/.rsbuild/rspack.config.node.mjs [#](https://rsbuild.rs/guide/advanced/environments#default-environment) Default environment ------------------------------------------------------------------------------------------- When `environments` is not specified, Rsbuild creates an environment by default with the same name as the current target type (the value of [output.target](https://rsbuild.rs/config/output/target) ). rsbuild.config.ts export default { output: { target: 'web', }, }; The above config is equivalent to a simplification of the following config: rsbuild.config.ts export default { environments: { web: { output: { target: 'web', }, }, }, }; [#](https://rsbuild.rs/guide/advanced/environments#build-a-specific-environment) Build a specific environment ------------------------------------------------------------------------------------------------------------- By default, Rsbuild will build all environments in the Rsbuild configuration when you execute `rsbuild dev` or `rsbuild build`. You can build only the specified environments with `--environment `. # Build for all environments by default rsbuild # Build for the web environment rsbuild --environment web # Build for the web and ssr environments rsbuild --environment web --environment node # Building multiple environments can be shortened to: rsbuild --environment web,node [#](https://rsbuild.rs/guide/advanced/environments#plugins-specified-environment) Add plugins for specified environment ----------------------------------------------------------------------------------------------------------------------- Plugins configured through the [plugins](https://rsbuild.rs/config/plugins) field support running in all environments. If you want a plugin to run only in a specified environment, you can configure the plugin in the specified `environment`. For example, enable the React plugin only in the web environment: rsbuild.config.ts import { pluginReact } from '@rsbuild/plugin-react'; export default { environments: { web: { output: { target: 'web', }, plugins: [pluginReact()], }, node: { output: { target: 'node', distPath: { root: 'dist/server', }, }, }, }, }; If you are a plugin developer, you can view [Developing environment plugins](https://rsbuild.rs/plugins/dev/#environment-plugin) for details. [#](https://rsbuild.rs/guide/advanced/environments#configuring-output-directories) Configuring output directories ----------------------------------------------------------------------------------------------------------------- When building for multiple environments, it's recommended to configure different output directories for each environment to prevent dist files with the same name from overwriting each other. You can use [output.distPath.root](https://rsbuild.rs/config/output/dist-path) to set independent output root directories for each environment. For example, output the web bundles to the default `dist` directory, and the node bundles to `dist/server`: rsbuild.config.ts export default { environments: { web: { source: { entry: { index: './src/index.client.js', }, }, }, node: { source: { entry: { index: './src/index.server.js', }, }, output: { target: 'node', distPath: { root: 'dist/server', }, }, }, }, }; [#](https://rsbuild.rs/guide/advanced/environments#plugin-api) Plugin API ------------------------------------------------------------------------- ### [#](https://rsbuild.rs/guide/advanced/environments#update-environment-config) Update environment config Rsbuild supports modifying or adding environment config through the [modifyRsbuildConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrsbuildconfig) hook. const myPlugin = () => ({ setup(api) { api.modifyRsbuildConfig((config, { mergeRsbuildConfig }) => { return mergeRsbuildConfig(config, { environments: { web1: { source: { entry: { index: './src/web1/index', }, }, }, }, }); }); }, }); ### [#](https://rsbuild.rs/guide/advanced/environments#configuring-a-specific-environment) Configuring a specific environment Rsbuild supports modifying the Rsbuild config of a specific environment through the [modifyEnvironmentConfig](https://rsbuild.rs/plugins/dev/hooks#modifyenvironmentconfig) hook. const myPlugin = () => ({ setup(api) { api.modifyEnvironmentConfig((config, { name }) => { if (name !== 'web') { return config; } config.html.title = 'My Default Title'; }); }, }); [#](https://rsbuild.rs/guide/advanced/environments#environment-context) Environment context ------------------------------------------------------------------------------------------- [Environment context](https://rsbuild.rs/api/javascript-api/environment-api#environment-context) is a read-only object that provides some context infos about the current environment. Rsbuild supports obtaining environment context information in plugin hooks. For some plugin hooks related to the build environment (such as [modifyRspackConfig](https://rsbuild.rs/plugins/dev/hooks#modifyrspackconfig) and [modifyBundlerChain](https://rsbuild.rs/plugins/dev/hooks#modifybundlerchain) ), Rsbuild supports obtaining the current environment context through the `environment` parameter. const myPlugin = () => ({ setup(api) { api.modifyRspackConfig((rspackConfig, { environment }) => { if (environment.name === 'node') { // do some thing } }); }, }); For some global plugin hooks (such as [onAfterDevCompile](https://rsbuild.rs/plugins/dev/hooks#onafterdevcompile) , [onBeforeStartDevServer](https://rsbuild.rs/plugins/dev/hooks#onbeforestartdevserver) , etc.), Rsbuild supports obtaining the context of all environments through the `environments` parameter. const myPlugin = () => ({ setup(api) { api.onAfterDevCompile(({ environments }) => { for (const name in environments) { console.log(name, environments[name]); } }); }, }); [#](https://rsbuild.rs/guide/advanced/environments#environment-api) Environment API ----------------------------------------------------------------------------------- Rsbuild server provides a series of APIs related to the build environment. Users can operate the build artifacts in a specific environment on the server side through the Rsbuild [environment API](https://rsbuild.rs/api/javascript-api/environment-api#environment-api) . You can use the environment API in [server.setup](https://rsbuild.rs/config/server/setup) or [Custom Server](https://rsbuild.rs/api/javascript-api/instance#rsbuildcreatedevserver) . For example, you can quickly implement an SSR function through the Rsbuild environment API in development mode: import express from 'express'; import { createRsbuild, loadConfig } from '@rsbuild/core'; const serverRender = ({ environments }) => async (_req, res) => { const bundle = await environments.node.loadBundle('index'); const rendered = bundle.render(); const template = await environments.web.getTransformedHtml('index'); const html = template.replace('', rendered); res.writeHead(200, { 'Content-Type': 'text/html', }); res.end(html); }; export async function startDevServer() { const { content } = await loadConfig(); // Init Rsbuild const rsbuild = await createRsbuild({ config: content, }); const app = express(); // Create Rsbuild dev server instance const rsbuildServer = await rsbuild.createDevServer(); const serverRenderMiddleware = serverRender(rsbuildServer); app.get('/', async (req, res, next) => { try { await serverRenderMiddleware(req, res, next); } catch (err) { logger.error('SSR render error, downgrade to CSR...'); logger.error(err); next(); } }); // Apply Rsbuild’s built-in middleware app.use(rsbuildServer.middlewares); // ... } For detailed usage, please refer to: [SSR + Express Example](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/ssr-express) . [#](https://rsbuild.rs/guide/advanced/environments#build-order) Build order --------------------------------------------------------------------------- By default, Rsbuild builds all environments in parallel. To control the build order between different environments, you can set build dependencies through Rspack's [dependencies](https://rspack.rs/config/other-options#dependencies) configuration. For example, if you need to build the `web` environment first, then build the `node` environment, you can add the following configuration: rsbuild.config.ts export default { environments: { web: { tools: { rspack: { name: 'foo', }, }, }, node: { tools: { rspack: { dependencies: ['foo'], }, }, }, }, }; We can use a simple plugin to test the build order of multiple environments: const testPlugin: RsbuildPlugin = { name: 'test-plugin', setup(api) { api.onBeforeEnvironmentCompile(({ environment }) => { console.log('build start:', environment.name); }); api.onAfterEnvironmentCompile(({ stats, environment }) => { console.log('build done:', environment.name); console.log('stats', stats); }); }, }; // The plugin will output: // - build start: web // - build done: web // - stats: { ... } // - build start: node // - build done: node // - stats: { ... } --- # 构建性能分析 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/debug/build-profiling.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/debug/build-profiling#%E6%9E%84%E5%BB%BA%E6%80%A7%E8%83%BD%E5%88%86%E6%9E%90) 构建性能分析 ==================================================================================================================== 复制 Markdown 进行构建性能分析可以帮助你确定项目中的性能瓶颈,从而采取针对性的优化。 [#](https://rsbuild.rs/zh/guide/debug/build-profiling#%E4%BD%BF%E7%94%A8-rsdoctor) 使用 Rsdoctor ---------------------------------------------------------------------------------------------- Rsdoctor 是一个构建分析工具,能够可视化地展示各个 loaders 和 plugins 的编译耗时。 请参考 [使用 Rsdoctor](https://rsbuild.rs/zh/guide/debug/rsdoctor) 了解更多。 [#](https://rsbuild.rs/zh/guide/debug/build-profiling#nodejs-profiling) Node.js profiling ----------------------------------------------------------------------------------------- 当 Rsbuild 执行一次构建时,会包含 JavaScript 和 Rust 两侧的代码运行开销,以及 JavaScript 和 Rust 之间的数据通信开销。 通常而言,JavaScript 侧的性能开销会大于 Rust 侧,你可以使用 Node.js 的 profiling 来分析 JS 侧的开销,这有助于发现 JS 侧的性能瓶颈。 例如,进行 [CPU profiling](https://nodejs.org/docs/v20.17.0/api/cli.html#--cpu-prof) 分析,在项目根目录执行以下命令: # dev node --cpu-prof ./node_modules/@rsbuild/core/bin/rsbuild.js dev # build node --cpu-prof ./node_modules/@rsbuild/core/bin/rsbuild.js build # 设置更高精度的采样间隔 node --cpu-prof --cpu-prof-interval=100 ./node_modules/@rsbuild/core/bin/rsbuild.js build 以上命令执行后会生成一个 `*.cpuprofile` 文件,我们可以使用 [speedscope](https://github.com/jlfwong/speedscope) 来可视化查看该文件: # 安装 speedscope npm install -g speedscope # 查看 cpuprofile 内容 # 请将文件名替换为本地文件的名称 speedscope CPU.date.000000.00000.0.001.cpuprofile [#](https://rsbuild.rs/zh/guide/debug/build-profiling#rspack-profiling) Rspack profiling ---------------------------------------------------------------------------------------- Rsbuild 支持使用 `RSPACK_PROFILE` 环境变量来对 Rspack 进行构建性能分析。 package.json { "scripts": { "dev:profile": "RSPACK_PROFILE=OVERVIEW rsbuild", "build:profile": "RSPACK_PROFILE=OVERVIEW rsbuild build" } } 由于 Windows 不支持上述用法,你也可以使用 [cross-env](https://npmjs.com/package/cross-env) 来设置环境变量,这可以确保在不同的操作系统中都能正常使用: package.json { "scripts": { "dev:profile": "cross-env RSPACK_PROFILE=OVERVIEW rsbuild", "build:profile": "cross-env RSPACK_PROFILE=OVERVIEW rsbuild build" }, "devDependencies": { "cross-env": "^7.0.0" } } 默认情况下,Rspack 会使用 `logger` trace layer,并将 profile 输出到项目根目录下的 `.rspack-profile-${timestamp}-${pid}/rspack.log`。当 `RSPACK_TRACE_OUTPUT` 是相对文件路径时,它会解析到生成的 `.rspack-profile-${timestamp}-${pid}` 目录下;绝对路径会按原样使用。如果需要输出到终端,请显式设置 `RSPACK_TRACE_OUTPUT=stdout` 或 `RSPACK_TRACE_OUTPUT=stderr`。 Tip * 在关闭 dev server 时,优先使用 `CTRL + D` 关闭,而不是 `CTRL + C`,这可以确保 Rspack 能够完整地记录性能数据。 * 关于 Rspack 性能分析的更多用法,可参考 [Rspack - Tracing](https://rspack.rs/zh/contribute/development/tracing) 。 --- # 开启调试模式 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/debug/debug-mode.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/debug/debug-mode#%E5%BC%80%E5%90%AF%E8%B0%83%E8%AF%95%E6%A8%A1%E5%BC%8F) 开启调试模式 =============================================================================================================== 复制 Markdown 为了便于排查问题,Rsbuild 提供了调试模式,你可以在执行构建时添加 `DEBUG=rsbuild` 环境变量来开启 Rsbuild 的调试模式。 # 调试开发模式 DEBUG=rsbuild pnpm dev # 调试生产模式 DEBUG=rsbuild pnpm build 在调试模式下,Rsbuild 会输出一些额外的日志信息,并将内部最终生成的 Rsbuild 配置和 Rspack 配置写入到产物目录下,便于开发者查看和调试。 [#](https://rsbuild.rs/zh/guide/debug/debug-mode#%E6%97%A5%E5%BF%97%E4%BF%A1%E6%81%AF) 日志信息 ------------------------------------------------------------------------------------------- 在调试模式下,你会看到 terminal 中输出了一些以 `rsbuild` 开头的日志,包括 Rsbuild 内部执行的操作、当前使用的 Rspack 版本等。 $ DEBUG=rsbuild pnpm dev ... rsbuild 10:00:00 configuration loaded from: /path/to/... rsbuild 10:00:00 registering default plugins rsbuild 10:00:00 default plugins registered ... 此外,terminal 中还会输出以下日志,表示 Rsbuild 将内部生成的构建配置写入到磁盘中,此时你可以打开这些配置文件来查看相应的内容。 config inspection completed, generated files: - Rsbuild config: /Project/demo/dist/.rsbuild/rsbuild.config.mjs - Rspack config (web): /Project/demo/dist/.rsbuild/rspack.config.web.mjs [#](https://rsbuild.rs/zh/guide/debug/debug-mode#rsbuild-%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6) Rsbuild 配置文件 ----------------------------------------------------------------------------------------------------------- 在调试模式下,Rsbuild 会自动生成 `dist/.rsbuild/rsbuild.config.mjs` 文件,这里面包含了最终生成的 Rsbuild 配置。在这个文件里,你可以了解到你传入的 Rsbuild 配置在经过框架层和 Rsbuild 处理后的最终结果。 该文件的大致结构如下: rsbuild.config.mjs export default { dev: { // some configs... }, source: { // some configs... }, // other configs... }; 关于 Rsbuild 配置项的完整介绍,请查看 [配置 Rsbuild](https://rsbuild.rs/zh/guide/configuration/rsbuild) 章节。 [#](https://rsbuild.rs/zh/guide/debug/debug-mode#rspack-%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6) Rspack 配置文件 --------------------------------------------------------------------------------------------------------- 在调试模式下,Rsbuild 还会自动生成 `dist/.rsbuild/rspack.config.web.mjs` 文件,这里面包含了最终生成的 Rspack 配置。在这个文件里,你可以了解到 Rsbuild 最终传递给 Rspack 的配置里包含了哪些内容。 该文件的大致结构如下: rspack.config.web.mjs export default { resolve: { // some resolve configs... }, module: { // some Rspack loaders... }, plugins: [\ // some Rspack plugins...\ ], // other configs... }; 关于 Rspack 配置项的完整介绍,请查看 [Rspack 官方文档](https://rspack.rs/zh/config) 。 --- # TanStack Start - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/migration/tanstack-start.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/migration/tanstack-start#tanstack-start) TanStack Start ==================================================================================== Copy Markdown TanStack Start supports Rsbuild for React and Solid applications. This guide replaces the Vite integration while preserving TanStack Start's managed client and server entries. Do not apply the generic [build entry](https://rsbuild.rs/guide/migration/vite#build-entry) migration steps to a TanStack Start application. [#](https://rsbuild.rs/guide/migration/tanstack-start#before-you-start) Before you start ---------------------------------------------------------------------------------------- Keep your existing `tanstackStart` options, routes, server functions, and application code. This migration changes the build tool; it does not change the TanStack Start application model. Review your Vite configuration and deployment integration before editing dependencies. Vite plugins cannot run in `rsbuild.config.ts`; migrate each one to an Rsbuild or Rspack equivalent, or remove it only after confirming that it is no longer needed. [#](https://rsbuild.rs/guide/migration/tanstack-start#replace-the-vite-configuration) Replace the Vite configuration -------------------------------------------------------------------------------------------------------------------- ### [#](https://rsbuild.rs/guide/migration/tanstack-start#react) React Remove Vite and its React plugin, then install the Rsbuild equivalents: npm yarn pnpm bun deno npm remove vite @vitejs/plugin-react yarn remove vite @vitejs/plugin-react pnpm remove vite @vitejs/plugin-react bun remove vite @vitejs/plugin-react deno remove npm:vite npm:@vitejs/plugin-react npm yarn pnpm bun deno npm add @rsbuild/core @rsbuild/plugin-react -D yarn add @rsbuild/core @rsbuild/plugin-react -D pnpm add @rsbuild/core @rsbuild/plugin-react -D bun add @rsbuild/core @rsbuild/plugin-react -D deno add npm:@rsbuild/core npm:@rsbuild/plugin-react -D If you use `@vitejs/plugin-react-swc`, remove that package instead. Keep `@tanstack/react-start` and `@tanstack/react-router` installed. Replace `vite.config.ts` with `rsbuild.config.ts`: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'; export default defineConfig({ plugins: [pluginReact(), tanstackStart()], }); This is the minimal configuration used by the [Rsbuild React example](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/tanstack-start) , excluding its optional Tailwind CSS plugin. ### [#](https://rsbuild.rs/guide/migration/tanstack-start#solid) Solid Remove Vite and its Solid plugin, then install the Rsbuild equivalents: npm yarn pnpm bun deno npm remove vite vite-plugin-solid yarn remove vite vite-plugin-solid pnpm remove vite vite-plugin-solid bun remove vite vite-plugin-solid deno remove npm:vite npm:vite-plugin-solid npm yarn pnpm bun deno npm add @rsbuild/core @rsbuild/plugin-babel @rsbuild/plugin-solid -D yarn add @rsbuild/core @rsbuild/plugin-babel @rsbuild/plugin-solid -D pnpm add @rsbuild/core @rsbuild/plugin-babel @rsbuild/plugin-solid -D bun add @rsbuild/core @rsbuild/plugin-babel @rsbuild/plugin-solid -D deno add npm:@rsbuild/core npm:@rsbuild/plugin-babel npm:@rsbuild/plugin-solid -D Keep `@tanstack/solid-start` and `@tanstack/solid-router` installed. Replace `vite.config.ts` with `rsbuild.config.ts`: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginBabel } from '@rsbuild/plugin-babel'; import { pluginSolid } from '@rsbuild/plugin-solid'; import { tanstackStart } from '@tanstack/solid-start/plugin/rsbuild'; export default defineConfig({ plugins: [\ pluginBabel({\ include: /\.(?:jsx|tsx)$/,\ }),\ pluginSolid(),\ tanstackStart(),\ ], }); This is the minimal configuration used by the [Rsbuild Solid example](https://github.com/rstackjs/rstack-examples/tree/main/rsbuild/tanstack-start-solid) , excluding its optional Tailwind CSS plugin. [#](https://rsbuild.rs/guide/migration/tanstack-start#update-scripts) Update scripts ------------------------------------------------------------------------------------ Retain `"type": "module"` in `package.json`, then replace the Vite scripts: package.json { "type": "module", "scripts": { "dev": "vite dev", "build": "vite build", "preview": "vite preview", "dev": "rsbuild", "build": "rsbuild build", "preview": "rsbuild preview" } } `rsbuild` without a subcommand starts the dev server. `rsbuild dev` is equivalent. ### [#](https://rsbuild.rs/guide/migration/tanstack-start#route-generation) Route generation If the project has a `generate-routes` script that runs `tsr generate`, replace it with `rsbuild build`: package.json { "scripts": { "generate-routes": "tsr generate", "generate-routes": "rsbuild build" } } The TanStack Start Rsbuild plugin generates the route tree during the build and adds its required registration to `routeTree.gen.ts`. Running `tsr generate` directly can overwrite that registration. [#](https://rsbuild.rs/guide/migration/tanstack-start#migrate-project-specific-settings) Migrate project-specific settings -------------------------------------------------------------------------------------------------------------------------- The configuration above replaces only the TanStack Start and Vite integration. Migrate all other Vite configuration deliberately: * Use the [Vite config migration reference](https://rsbuild.rs/guide/migration/vite#config-migration) for aliases, CSS, dev server settings, static assets, and other Vite options. * Replace each Vite plugin with an Rsbuild or Rspack equivalent. Integrations that expose only a Vite plugin need a separately supported replacement. * Delete `vite.config.ts` after its settings have been migrated. ### [#](https://rsbuild.rs/guide/migration/tanstack-start#react-compiler) React Compiler For React applications that use React Compiler through a Babel plugin, configure the built-in Rspack implementation instead: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginReact } from '@rsbuild/plugin-react'; export default defineConfig({ plugins: [\ pluginReact({\ reactCompiler: true,\ }),\ ], }); If a Babel or Rolldown Babel plugin was used only for React Compiler, remove that plugin and `babel-plugin-react-compiler`. For React 17 or 18 applications, install `react-compiler-runtime` and set the compiler target as described in the [React plugin documentation](https://rsbuild.rs/plugins/list/plugin-react#reactcompiler) . ### [#](https://rsbuild.rs/guide/migration/tanstack-start#typescript) TypeScript Replace Vite's preset types in `tsconfig.json` with Rsbuild's preset types. If your project already defines a `types` array, replace only the Vite entries and retain the other required types: tsconfig.json { "compilerOptions": { "types": ["vite/client", "vite-plugin-svgr/client"], "types": ["@rsbuild/core/types"] } } `@rsbuild/plugin-svgr` does not provide a TypeScript declaration for `*.svg?react` imports. If your application uses that query, add a declaration file such as `src/types/svg.d.ts`: src/types/svg.d.ts declare module '*.svg?react' { import type React from 'react'; const ReactComponent: React.FunctionComponent>; export default ReactComponent; } ### [#](https://rsbuild.rs/guide/migration/tanstack-start#environment-variables) Environment variables Rsbuild exposes client environment variables with the `PUBLIC_` prefix. Rename every client variable from `VITE_*` to `PUBLIC_*`, including its definition in `.env` files, CI variables, Docker build arguments, and application code: - VITE_API_URL + PUBLIC_API_URL Update application code to use direct property access, such as `import.meta.env.PUBLIC_API_URL`. If an environment validator receives the entire `import.meta.env` object, pass it an explicit object containing the required `PUBLIC_` properties. ### [#](https://rsbuild.rs/guide/migration/tanstack-start#static-prerendering-and-cdn-urls) Static prerendering and CDN URLs Keep options passed to `tanstackStart`. For example, static prerendering remains configured through the plugin: tanstackStart({ prerender: { enabled: true, crawlLinks: true, }, }); See the [React](https://tanstack.com/start/latest/docs/framework/react/guide/static-prerendering) and [Solid](https://tanstack.com/start/latest/docs/framework/solid/guide/static-prerendering) static prerendering guides for all available options. For React applications that use CDN asset URLs, configure `transformAssets` in the TanStack Start server entry. This is different from setting an Rsbuild `assetPrefix`: const handler = createStartHandler({ handler: defaultStreamHandler, transformAssets: process.env.CDN_ORIGIN || '', }); Use the React server APIs when creating the handler. See [CDN asset URLs](https://tanstack.com/start/latest/docs/framework/react/guide/cdn-asset-urls) for a complete example. ### [#](https://rsbuild.rs/guide/migration/tanstack-start#paraglide) Paraglide If you use Paraglide, replace `paraglideVitePlugin` with `paraglideRspackPlugin` and register it in `tools.rspack.plugins`. Keep the existing plugin options and generated output directory. ### [#](https://rsbuild.rs/guide/migration/tanstack-start#sentry) Sentry Replace the Vite adapter's build-time integration with [`@sentry/webpack-plugin`](https://www.npmjs.com/package/@sentry/webpack-plugin) . Register it in `tools.rspack.plugins`, enable `hidden-source-map` when uploading source maps, and set `SENTRY_AUTH_TOKEN` and `SENTRY_RELEASE` in CI. If you use a Sentry tunnel, define a TanStack Start route and limit it to your public DSN: src/routes/monitoring.ts import * as Sentry from '@sentry/tanstackstart-react'; import { createFileRoute } from '@tanstack/react-router'; const sentryDsn = import.meta.env.PUBLIC_SENTRY_DSN; export const Route = createFileRoute('/monitoring')({ server: Sentry.createSentryTunnelRoute({ allowedDsns: sentryDsn ? [sentryDsn] : [], }), }); Configure the same path with the client SDK's `tunnel` option. [#](https://rsbuild.rs/guide/migration/tanstack-start#migrate-tests-from-vitest-to-rstest) Migrate tests from Vitest to Rstest ------------------------------------------------------------------------------------------------------------------------------ Vitest runs tests through Vite. If you want to remove Vite from the test toolchain, migrate the Vitest configuration and test imports to Rstest before removing `vitest`, `@vitest/coverage-v8`, and Vite-only test plugins. Install Rstest and its Rsbuild adapter. Add the V8 coverage package when the Vitest configuration uses V8 coverage: npm yarn pnpm bun deno npm add @rstest/core @rstest/adapter-rsbuild @rstest/coverage-v8 jsdom -D yarn add @rstest/core @rstest/adapter-rsbuild @rstest/coverage-v8 jsdom -D pnpm add @rstest/core @rstest/adapter-rsbuild @rstest/coverage-v8 jsdom -D bun add @rstest/core @rstest/adapter-rsbuild @rstest/coverage-v8 jsdom -D deno add npm:@rstest/core npm:@rstest/adapter-rsbuild npm:@rstest/coverage-v8 npm:jsdom -D Create `rstest.config.ts` and reuse the application configuration: rstest.config.ts import { withRsbuildConfig } from '@rstest/adapter-rsbuild'; import { defineConfig } from '@rstest/core'; export default defineConfig({ extends: withRsbuildConfig(), testEnvironment: 'jsdom', setupFiles: ['./src/test/setup.ts'], coverage: { provider: 'v8', reporters: ['text', 'html', 'lcov', 'cobertura'], }, }); Rstest options are top-level fields: for example, move `test.environment` to `testEnvironment`, `test.setupFiles` to `setupFiles`, and `test.coverage` to `coverage`. Rename Vitest's `coverage.reporter` option to `coverage.reporters`. Replace test API imports: import { describe, expect, it } from 'vitest'; import { describe, expect, it } from '@rstest/core'; For Testing Library and `@testing-library/jest-dom`, register matchers with Rstest's `expect` in the setup file. Use the Testing Library package for your framework: src/test/setup.ts (React) import { cleanup } from '@testing-library/react'; import * as jestDomMatchers from '@testing-library/jest-dom/matchers'; import { afterEach, expect } from '@rstest/core'; expect.extend(jestDomMatchers); afterEach(cleanup); src/test/setup.ts (Solid) import * as jestDomMatchers from '@testing-library/jest-dom/matchers'; import { cleanup } from '@testing-library/solid'; import { afterEach, expect } from '@rstest/core'; expect.extend(jestDomMatchers); afterEach(cleanup); Update scripts to use `rstest`, `rstest --watch`, and `rstest --coverage`. For more configuration mappings, see the [Rstest migration guide](https://rstest.rs/guide/migration/vitest) and the Rsbuild [Testing](https://rsbuild.rs/guide/advanced/testing) guide. [#](https://rsbuild.rs/guide/migration/tanstack-start#deploy-to-nodejs-or-docker) Deploy to Node.js or docker ------------------------------------------------------------------------------------------------------------- If `nitro/vite` is used only for Node.js or Docker deployment, remove `nitro`. A TanStack Start Rsbuild build emits its own server entry. Install [srvx](https://srvx.h3.dev/) as a production dependency: npm yarn pnpm bun deno npm remove nitro yarn remove nitro pnpm remove nitro bun remove nitro deno remove npm:nitro npm yarn pnpm bun deno npm add srvx yarn add srvx pnpm add srvx bun add srvx deno add npm:srvx package.json { "scripts": { "start": "srvx --prod -s ../client dist/server/index.js" } } The production build emits client assets in `dist/client` and the fetch-style server entry in `dist/server/index.js`. If your build emits `dist/server/server.js`, use that path instead. For Docker, install production dependencies again in the final stage. The `runner` stage starts from a fresh base image: the builder's `node_modules` includes development dependencies and should not be copied to the runtime image. Use the following `runner` stage in your Dockerfile. It detects the package manager from the project's lockfile and supports npm, Yarn, and pnpm: Dockerfile (runner stage) FROM node:24-alpine AS runner WORKDIR /app COPY package.json package-lock.json* yarn.lock* pnpm-lock.yaml* .npmrc* ./ RUN corepack enable && \ if [ -f package-lock.json ]; then \ npm ci --omit=dev --ignore-scripts; \ elif [ -f yarn.lock ]; then \ yarn install --frozen-lockfile --production=true --ignore-scripts; \ elif [ -f pnpm-lock.yaml ]; then \ pnpm install --prod --frozen-lockfile --ignore-scripts; \ else \ echo "No lockfile found." && exit 1; \ fi COPY --from=builder /app/dist ./dist CMD ["./node_modules/.bin/srvx", "--prod", "-s", "../client", "dist/server/index.js"] Configure the preceding build stages according to the TanStack Start [React](https://tanstack.com/start/latest/docs/framework/react/guide/hosting) or [Solid](https://tanstack.com/start/latest/docs/framework/solid/guide/hosting) deployment guide. For deployment targets other than Node.js or Docker, Vite-specific deployment integrations cannot be used with Rsbuild. Use a supported non-Vite adapter, or retain the Vite integration. See the [React hosting guide](https://tanstack.com/start/latest/docs/framework/react/guide/hosting) and [Solid hosting guide](https://tanstack.com/start/latest/docs/framework/solid/guide/hosting) . --- # JSON - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/basic/json-files.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/basic/json-files#json) JSON =========================================================== 复制 Markdown Rsbuild 支持在代码中引用 JSON 文件,也支持引用 [YAML](https://yaml.org/) 和 [TOML](https://toml.io/en/) 文件并将其转换为 JSON 格式。 [#](https://rsbuild.rs/zh/guide/basic/json-files#json-%E6%96%87%E4%BB%B6) JSON 文件 --------------------------------------------------------------------------------- 你可以直接在 JavaScript 文件中引用 JSON 文件。 ### [#](https://rsbuild.rs/zh/guide/basic/json-files#%E7%A4%BA%E4%BE%8B) 示例 example.json { "name": "foo", "items": [1, 2] } index.js import example from './example.json'; console.log(example.name); // 'foo'; console.log(example.items); // [1, 2]; ### [#](https://rsbuild.rs/zh/guide/basic/json-files#%E5%85%B7%E5%90%8D%E5%BC%95%E7%94%A8) 具名引用 Rsbuild 同样支持通过 named import 来引用 JSON 文件: import { name } from './example.json'; console.log(name); // 'foo'; [#](https://rsbuild.rs/zh/guide/basic/json-files#yaml-%E6%96%87%E4%BB%B6) YAML 文件 --------------------------------------------------------------------------------- [YAML](https://yaml.org/) 是一种数据序列化语言,通常用于编写配置文件。 Rsbuild 提供了 [@rsbuild/plugin-yaml](https://github.com/rstackjs/rsbuild-plugin-yaml) ,在注册插件后,你可以在 JavaScript 中引用 `.yaml` 或 `.yml` 文件,它们会被自动转换为 JavaScript 对象。 rsbuild.config.ts import { pluginYaml } from '@rsbuild/plugin-yaml'; export default { plugins: [pluginYaml()], }; ### [#](https://rsbuild.rs/zh/guide/basic/json-files#%E7%A4%BA%E4%BE%8B-1) 示例 example.yaml --- hello: world foo: bar: baz import example from './example.yaml'; console.log(example.hello); // 'world'; console.log(example.foo); // { bar: 'baz' }; [#](https://rsbuild.rs/zh/guide/basic/json-files#toml-%E6%96%87%E4%BB%B6) TOML 文件 --------------------------------------------------------------------------------- [TOML](https://toml.io/) 是一种语义明显、易于阅读的配置文件格式。 Rsbuild 提供了 [@rsbuild/plugin-toml](https://github.com/rstackjs/rsbuild-plugin-toml) ,在注册插件后,你可以在 JavaScript 中引用 `.toml` 文件,它会被自动转换为 JavaScript 对象。 rsbuild.config.ts import { pluginToml } from '@rsbuild/plugin-toml'; export default { plugins: [pluginToml()], }; ### [#](https://rsbuild.rs/zh/guide/basic/json-files#%E7%A4%BA%E4%BE%8B-2) 示例 example.toml hello = "world" [foo] bar = "baz" import example from './example.toml'; console.log(example.hello); // 'world'; console.log(example.foo); // { bar: 'baz' }; [#](https://rsbuild.rs/zh/guide/basic/json-files#%E7%B1%BB%E5%9E%8B%E5%A3%B0%E6%98%8E) 类型声明 ------------------------------------------------------------------------------------------- 当你在 TypeScript 代码中引用 YAML 或 TOML 文件时,可以使用以下任一方法添加类型声明: * 方法一:如果项目里安装了 `@rsbuild/core` 包,你可以在 `tsconfig.json` 中添加 `@rsbuild/core` 提供的 [预设类型](https://rsbuild.rs/zh/guide/basic/typescript#preset-types) : tsconfig.json { "compilerOptions": { "types": ["@rsbuild/core/types"] } } * 方法二:手动添加需要的类型声明: src/env.d.ts declare module '*.yaml' { const content: Record; export default content; } declare module '*.yml' { const content: Record; export default content; } declare module '*.toml' { const content: Record; export default content; } --- # 名词解释 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/start/glossary.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/start/glossary#%E5%90%8D%E8%AF%8D%E8%A7%A3%E9%87%8A) 名词解释 ========================================================================================= 复制 Markdown [#](https://rsbuild.rs/zh/guide/start/glossary#bundler) Bundler --------------------------------------------------------------- 指 [Rspack](https://rspack.rs/zh/) 、[webpack](https://webpack.js.org/) 等模块打包工具。 打包工具的主要目标是将 JavaScript、CSS 等文件打包在一起,打包后的文件可以在浏览器、Node.js 等环境中使用。当打包工具处理 Web 应用时,它会构建一个依赖关系图,其中包含应用需要的各个模块,然后将所有模块打包成一个或多个 bundle。 [#](https://rsbuild.rs/zh/guide/start/glossary#csr) CSR ------------------------------------------------------- CSR 是 "Client-Side Rendering"(客户端渲染)的缩写。它表示页面是在浏览器中通过 JavaScript 渲染的,数据获取、模板和路由等逻辑都在浏览器端完成,而不是在服务器上。 在 CSR 中,服务器会向浏览器端发送一个空的 HTML 外壳和一些 JavaScript 脚本,然后由浏览器端从服务器的 API 中拉取数据,并将动态内容渲染到页面中。 [#](https://rsbuild.rs/zh/guide/start/glossary#environment) Environment ----------------------------------------------------------------------- `environment` 指的是构建产物的运行环境,详见 [多环境构建](https://rsbuild.rs/zh/guide/advanced/environments) 。 [#](https://rsbuild.rs/zh/guide/start/glossary#micro-frontend) Micro-frontend ----------------------------------------------------------------------------- 微前端(Micro-frontend,简称 MFE)是一种类似于微服务的架构,是一种由独立交付的多个前端应用组成整体的架构风格,它将前端应用分解成一些更小、更简单的能够独立开发、测试、部署的应用,而在用户看来仍然是内聚的单个产品。 它主要解决了两个问题: * 随着项目迭代应用越来越庞大,难以维护。 * 跨团队或跨部门协作开发项目导致效率低下的问题。 [#](https://rsbuild.rs/zh/guide/start/glossary#modernjs) Modern.js ------------------------------------------------------------------ [Modern.js](https://github.com/web-infra-dev/modern.js) 是一个基于 Rsbuild 实现的渐进式 Web 开发框架。 [#](https://rsbuild.rs/zh/guide/start/glossary#module-federation) Module Federation ----------------------------------------------------------------------------------- Module Federation 是一种 JavaScript 应用分治的架构模式(类似于服务端的微服务),它允许你在多个 JavaScript 应用程序(或微前端)之间共享代码和资源。 详见 [模块联邦](https://rsbuild.rs/zh/guide/advanced/module-federation) 。 [#](https://rsbuild.rs/zh/guide/start/glossary#rspack) Rspack ------------------------------------------------------------- [Rspack](https://rspack.rs/zh/) 是一个基于 Rust 编写的高性能 JavaScript 打包工具,它提供对 webpack 生态良好的兼容性,能够无缝替换 webpack,并提供闪电般的构建速度。 [#](https://rsbuild.rs/zh/guide/start/glossary#rspress) Rspress --------------------------------------------------------------- [Rspress](https://github.com/web-infra-dev/rspress) 是一个基于 Rsbuild 的静态站点生成器。 [#](https://rsbuild.rs/zh/guide/start/glossary#ssr) SSR ------------------------------------------------------- SSR 是 "Server-side rendering"(服务端渲染)的缩写。它表示由服务器生成网页的 HTML,并将其发送给客户端,而不是只发送一个空的 HTML 外壳,并依赖 JavaScript 来生成页面内容。 详见 [服务端渲染(SSR)](https://rsbuild.rs/zh/guide/advanced/ssr) 。 [#](https://rsbuild.rs/zh/guide/start/glossary#swc) SWC ------------------------------------------------------- SWC (Speedy Web Compiler) 是基于 Rust 语言编写的高性能 JavaScript 和 TypeScript 转译和压缩工具。 详见 [配置 SWC](https://rsbuild.rs/zh/guide/configuration/swc) 。 [#](https://rsbuild.rs/zh/guide/start/glossary#%E6%9B%B4%E5%A4%9A) 更多 --------------------------------------------------------------------- 访问 [Rspack - 术语表](https://rspack.rs/zh/misc/glossary) 查看更多名词解释。 --- # 升级 Rsbuild - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/upgrade/upgrade-rsbuild.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/upgrade/upgrade-rsbuild#%E5%8D%87%E7%BA%A7-rsbuild) 升级 Rsbuild ============================================================================================== 复制 Markdown 本章节介绍如何升级项目中的 Rsbuild 依赖到最新版本。 Tip 参考 [npm - @rsbuild/core](https://npmjs.com/package/@rsbuild/core) 查看当前的最新版本。 [#](https://rsbuild.rs/zh/guide/upgrade/upgrade-rsbuild#%E8%AF%AD%E4%B9%89%E5%8C%96%E7%89%88%E6%9C%AC) 语义化版本 ------------------------------------------------------------------------------------------------------------ Rsbuild 遵循 [Semantic Versioning](https://semver.org/lang/zh-CN/) 语义化版本规范。 * 主版本号:包含不兼容的 API 变更。 * 次版本号:包含向下兼容的功能性变更。 * 修订号:包含向下兼容的问题修正。 [#](https://rsbuild.rs/zh/guide/upgrade/upgrade-rsbuild#%E6%9B%B4%E6%96%B0%E6%97%A5%E5%BF%97) 更新日志 -------------------------------------------------------------------------------------------------- 访问 [GitHub - release](https://github.com/web-infra-dev/rsbuild/releases) 来查看 Rsbuild 每个版本的变更内容。 [#](https://rsbuild.rs/zh/guide/upgrade/upgrade-rsbuild#%E4%BD%BF%E7%94%A8-taze) 使用 Taze ---------------------------------------------------------------------------------------- 我们推荐使用 [Taze](https://github.com/antfu-collective/taze) 来升级 Rsbuild 的版本,这是一个用于升级 npm 依赖版本的 CLI 工具。 ### [#](https://rsbuild.rs/zh/guide/upgrade/upgrade-rsbuild#%E7%94%A8%E6%B3%95) 用法 运行以下命令来升级所有名称中包含 `rsbuild` 的依赖: npx taze --include /rsbuild/ -w 运行结果类似于: rsbuild - 3 patch @rsbuild/core dev ~1mo ^1.0.0 → ^1.2.0 @rsbuild/plugin-react dev ~1mo ^1.0.0 → ^1.2.0 @rsbuild/plugin-type-check dev ~1mo ^1.0.0 → ^1.2.0 ℹ changes written to package.json, run npm i to install updates. 你也可以调整 `include` 来匹配不同的包,比如仅升级 `@rsbuild` scope 下的包: npx taze --include /@rsbuild/ -w ### [#](https://rsbuild.rs/zh/guide/upgrade/upgrade-rsbuild#%E9%80%89%E9%A1%B9) 选项 下面是一些使用 taze 选项的示例。 * 在 monorepo 中,你可以添加 `-r` 选项来递归升级: npx taze --include /rsbuild/ -w -r * 添加 `-l` 来升级被锁定的版本: npx taze --include /rsbuild/ -w -l * 升级 major 版本: npx taze major --include /rsbuild/ -w > 更多选项请参考 [taze 文档](https://github.com/antfu-collective/taze) > 。 --- # Output files - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/basic/output-files.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/basic/output-files#output-files) Output files ========================================================================== Copy Markdown This section covers the output file directory structure and how to control output directories for different file types. To learn about deploying Rsbuild projects, see [Deployment](https://rsbuild.rs/guide/basic/deployment) . [#](https://rsbuild.rs/guide/basic/output-files#default-directory-structure) Default directory structure -------------------------------------------------------------------------------------------------------- The default output directory structure is shown below. Output files are written to the `dist` directory at your project root. dist ├── static │ ├── css │ │ ├── [name].[hash].css │ │ └── [name].[hash].css.map │ │ │ └── js │ ├── [name].[hash].js │ ├── [name].[hash].js.LICENSE.txt │ └── [name].[hash].js.map │ └── [name].html The most common output files are HTML, JS, and CSS files: * HTML files: written to the root of the dist directory by default. * JS files: written to the `static/js` directory by default. * CSS files: written to the `static/css` directory by default. Additional files may be generated alongside JS and CSS files: * License files: contain open-source license information, written to the same directory as JS files with a `.LICENSE.txt` suffix. * Source map files: contain source mapping information, written to the same directory as JS and CSS files with a `.map` suffix. In the filename, `[name]` represents the entry name for this file, such as `index` or `main`. `[hash]` is a hash value generated based on the file content. [#](https://rsbuild.rs/guide/basic/output-files#development-mode-output) Development mode output ------------------------------------------------------------------------------------------------ In development mode, Rsbuild stores build outputs in memory on the dev server by default rather than writing them to disk. This reduces file system overhead. See [View static assets](https://rsbuild.rs/guide/basic/server#view-static-assets) to view all static assets generated during the current build. To write output files to disk (useful for inspecting build artifacts or configuring proxy rules), set [dev.writeToDisk](https://rsbuild.rs/config/dev/write-to-disk) to `true`: export default { dev: { writeToDisk: true, }, }; [#](https://rsbuild.rs/guide/basic/output-files#modify-the-output-directory) Modify the output directory -------------------------------------------------------------------------------------------------------- Rsbuild provides several options to customize output directories or filenames: * Use [output.filename](https://rsbuild.rs/config/output/filename) to modify the filename. * Use [output.distPath](https://rsbuild.rs/config/output/dist-path) to modify the output path. * Use [output.legalComments](https://rsbuild.rs/config/output/legal-comments) to modify the license file output. * Use [output.sourceMap](https://rsbuild.rs/config/output/source-map) to modify source map output. * Use [html.outputStructure](https://rsbuild.rs/config/html/output-structure) to modify the output structure of HTML files. [#](https://rsbuild.rs/guide/basic/output-files#static-assets) Static assets ---------------------------------------------------------------------------- Static assets imported in your code (images, SVG, fonts, media, etc.) are written to the `dist/static` directory and automatically organized by file type: dist └── static ├── image │ └── foo.[hash].png │ ├── svg │ └── bar.[hash].svg │ ├── font │ └── baz.[hash].woff2 │ └── media └── qux.[hash].mp4 Configure [output.distPath](https://rsbuild.rs/config/output/dist-path) to write static assets to a single directory. For example, to place them all in an `assets` directory: export default { output: { distPath: { image: 'assets', svg: 'assets', font: 'assets', media: 'assets', }, }, }; This configuration generates the following directory structure: dist └── assets ├── foo.[hash].png ├── bar.[hash].svg ├── baz.[hash].woff2 └── qux.[hash].mp4 [#](https://rsbuild.rs/guide/basic/output-files#nodejs-output-directory) Node.js output directory ------------------------------------------------------------------------------------------------- With [output.target](https://rsbuild.rs/config/output/target) set to `'node'`, Rsbuild generates output files for Node.js: dist ├── static └── [name].js Node.js outputs typically contain only JS files, without HTML or CSS. JS filenames do not include hash values. You can modify the output path for Node.js files using the [environments](https://rsbuild.rs/config/environments) configuration. For example, to write Node.js files to the `server` directory: export default { environments: { web: { output: { target: 'web', }, }, node: { output: { target: 'node', distPath: { root: 'dist/server', }, }, }, }, }; [#](https://rsbuild.rs/guide/basic/output-files#flatten-directories) Flatten directories ---------------------------------------------------------------------------------------- To create a flatter directory structure, set any directory path to an empty string. For example: export default { output: { distPath: { js: '', css: '', }, }, }; This configuration generates the following directory structure: dist ├── [name].[hash].css ├── [name].[hash].css.map ├── [name].[hash].js ├── [name].[hash].js.map └── [name].html --- # Improve build performance - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/optimization/build-performance.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/optimization/build-performance#improve-build-performance) Improve build performance ================================================================================================================ Copy Markdown While Rsbuild optimizes build performance by default, performance issues can arise as your project grows. This document provides optional optimization strategies to improve build performance. [#](https://rsbuild.rs/guide/optimization/build-performance#performance-profiling) Performance profiling -------------------------------------------------------------------------------------------------------- Performance profiling helps identify bottlenecks in your project for targeted optimization. See the [Build profiling](https://rsbuild.rs/guide/debug/build-profiling) section. [#](https://rsbuild.rs/guide/optimization/build-performance#general-optimization) General optimization ------------------------------------------------------------------------------------------------------ These general optimization methods speed up both development and production builds. ### [#](https://rsbuild.rs/guide/optimization/build-performance#upgrade-rsbuild) Upgrade Rsbuild Upgrading to the latest version of Rsbuild gives you access to the latest performance optimizations. See [Upgrading Rsbuild](https://rsbuild.rs/guide/upgrade/upgrade-rsbuild) for more details. ### [#](https://rsbuild.rs/guide/optimization/build-performance#enable-persistent-cache) Enable persistent cache Rsbuild provides a [performance.buildCache](https://rsbuild.rs/config/performance/build-cache) configuration that significantly improves rebuild speed. ### [#](https://rsbuild.rs/guide/optimization/build-performance#react-compiler) React Compiler If your project uses React Compiler, enable Rsbuild's built-in Rust version of [React Compiler](https://rsbuild.rs/plugins/list/plugin-react#reactcompiler) instead of running React Compiler through Babel to reduce the performance overhead introduced by Babel. ### [#](https://rsbuild.rs/guide/optimization/build-performance#reduce-module-count) Reduce module count Optimizing the number of modules in your application reduces bundle size and improves build performance. See [Bundle size optimization](https://rsbuild.rs/guide/optimization/optimize-bundle) to learn optimization strategies. ### [#](https://rsbuild.rs/guide/optimization/build-performance#parallel-processing) Parallel processing Some plugins support processing modules in parallel using worker threads. When enabled, modules are processed across multiple worker threads, reducing pressure on the main thread and improving overall build performance when compiling large numbers of modules. The following plugins support the `parallel` option: * [@rsbuild/plugin-babel - parallel](https://rsbuild.rs/plugins/list/plugin-babel#parallel) : run Babel transformations in parallel. * [@rsbuild/plugin-less - parallel](https://rsbuild.rs/plugins/list/plugin-less#parallel) : compile Less modules in parallel. * [@rsbuild/plugin-svgr - parallel](https://rsbuild.rs/plugins/list/plugin-svgr#parallel) : transform SVG modules into React components in parallel. ### [#](https://rsbuild.rs/guide/optimization/build-performance#tool-selection) Tool selection While Rsbuild delivers excellent build performance out of the box, certain JavaScript-based tools can negatively impact performance, particularly in large projects. * [@rsbuild/plugin-babel](https://rsbuild.rs/plugins/list/plugin-babel) : This plugin uses Babel. We recommend using the more performant [SWC](https://rsbuild.rs/guide/configuration/swc) for code transformation instead. * [@rsbuild/plugin-less](https://rsbuild.rs/plugins/list/plugin-less) : The Less compiler has relatively poor performance. Consider using [@rsbuild/plugin-sass](https://rsbuild.rs/plugins/list/plugin-sass) or other performant CSS solutions instead. * [@rsbuild/plugin-type-check](https://github.com/rstackjs/rsbuild-plugin-type-check) : Use TypeScript 7 or later for faster type checking. See [TypeScript 7+ support](https://github.com/rstackjs/rsbuild-plugin-type-check#typescript-7-support) for details. * [terser-webpack-plugin](https://www.npmjs.com/package/terser-webpack-plugin) or [minimizer-webpack-plugin](https://www.npmjs.com/package/minimizer-webpack-plugin) : You can replace Terser with faster minimizers like Rsbuild's built-in [SWC](https://rsbuild.rs/guide/configuration/swc) minifier. ### [#](https://rsbuild.rs/guide/optimization/build-performance#optimize-tailwind-css) Optimize Tailwind CSS When using Tailwind CSS v3, incorrectly configuring the `content` field in `tailwind.config.js` can lead to poor build and HMR performance. See [Tailwind CSS v3 - Optimize build performance](https://rsbuild.rs/guide/styling/tailwindcss-v3#optimize-build-performance) for more details. [#](https://rsbuild.rs/guide/optimization/build-performance#development-optimization) Development optimization -------------------------------------------------------------------------------------------------------------- These methods improve performance in development mode. ### [#](https://rsbuild.rs/guide/optimization/build-performance#enable-lazy-compilation) Enable lazy compilation Enabling lazy compilation significantly reduces the number of modules compiled during dev server startup, improving startup time. rsbuild.config.ts export default { dev: { lazyCompilation: true, }, }; > See [dev.lazyCompilation](https://rsbuild.rs/config/dev/lazy-compilation) > for more information. ### [#](https://rsbuild.rs/guide/optimization/build-performance#enable-native-watcher) Enable native watcher Enabling Rspack's [native watcher](https://rspack.rs/config/experiments#experimentsnativewatcher) improves HMR performance in development mode. rsbuild.config.ts export default { tools: { rspack: { experiments: { nativeWatcher: true, }, }, }, }; ### [#](https://rsbuild.rs/guide/optimization/build-performance#source-map-format) Source map format To provide a good debugging experience, Rsbuild uses the `cheap-module-source-map` format in development mode by default. This is a high-quality source map format that comes with some performance overhead. You can improve build speed by adjusting the source map format using [output.sourceMap](https://rsbuild.rs/config/output/source-map) . For example, to disable source maps: rsbuild.config.ts export default { output: { sourceMap: { js: false, }, }, }; Or set the source map format to the fastest `eval` format in development mode: rsbuild.config.ts export default { output: { sourceMap: { js: process.env.NODE_ENV === 'development' ? 'eval' : false, }, }, }; > For detailed differences between different source map formats, see [Rspack - devtool](https://rspack.rs/config/devtool) > . ### [#](https://rsbuild.rs/guide/optimization/build-performance#browserslist-for-development) Browserslist for development This strategy is similar to ["Adjust Browserslist"](https://rsbuild.rs/guide/optimization/optimize-bundle#adjust-browserslist) , except you can set different browserslist configurations for development and production, reducing compilation overhead in development. For example, you can add the following config to `.browserslistrc` to target only the latest browsers in development while supporting a broader range in production: .browserslistrc [production] chrome >= 107 edge >= 107 firefox >= 104 safari >= 16 [development] last 1 chrome version last 1 firefox version last 1 safari version Note that this can lead to differences in build output between development and production modes. --- # Wasm - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/basic/wasm-assets.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/basic/wasm-assets#wasm) Wasm ============================================================ 复制 Markdown Rsbuild 提供了对 WebAssembly (WASM) 模块的原生支持,允许在项目中直接导入和使用 `.wasm` 资源。 什么是 WebAssembly WebAssembly(缩写为 wasm)是一种可移植、高性能的字节码格式,被设计用来在现代 Web 浏览器中执行 CPU 密集型计算任务,为 Web 平台带来了接近本地编译代码的性能和可靠性。 [#](https://rsbuild.rs/zh/guide/basic/wasm-assets#%E5%BC%95%E7%94%A8%E6%96%B9%E5%BC%8F) 引用方式 -------------------------------------------------------------------------------------------- 你可以在 JavaScript 文件中通过具名导入来引用一个 WebAssembly 模块: index.js import { add } from './add.wasm'; console.log(add); // [native code] console.log(add(1, 2)); // 3 也可以通过 dynamic import 来引用 WebAssembly 模块: index.js import('./add.wasm').then(({ add }) => { console.log('---- Async Wasm Module'); console.log(add); // [native code] console.log(add(1, 2)); // 3 }); 还可以通过 `new URL` 语法来获取 WebAssembly 模块的路径: index.js const wasmURL = new URL('./add.wasm', import.meta.url); console.log(wasmURL.pathname); // "/static/wasm/[contenthash:10].module.wasm" [#](https://rsbuild.rs/zh/guide/basic/wasm-assets#source-import) Source import ------------------------------------------------------------------------------ 你可以使用 [Source Phase Imports](https://github.com/tc39/proposal-source-phase-imports) 获取编译后的 `WebAssembly.Module`,而不是直接获取模块导出: index.js import source wasmModule from './add.wasm'; const instance = await WebAssembly.instantiate(wasmModule); const { add } = instance.exports; console.log(add(1, 2)); // 3 当你需要手动实例化 Wasm 模块、使用不同的 imports 创建多个实例,或将模块传递给 worker 时,这种方式会很有用。 Tip `import source` 用法在 Rsbuild v2.1.0 及以上版本中支持。 [#](https://rsbuild.rs/zh/guide/basic/wasm-assets#%E8%BE%93%E5%87%BA%E7%9B%AE%E5%BD%95) 输出目录 -------------------------------------------------------------------------------------------- 当 `.wasm` 资源被引用后,默认会被 Rsbuild 输出到 `dist/static/wasm` 目录下。 你可以通过 [output.distPath](https://rsbuild.rs/zh/config/output/dist-path) 配置项来修改 `.wasm` 产物的输出目录。 export default { output: { distPath: { wasm: 'resource/wasm', }, }, }; [#](https://rsbuild.rs/zh/guide/basic/wasm-assets#%E7%B1%BB%E5%9E%8B%E5%A3%B0%E6%98%8E) 类型声明 -------------------------------------------------------------------------------------------- 当你在 TypeScript 代码中引用 Wasm 文件时,通常需要添加相应的类型声明。 比如 `add.wasm` 文件导出了 `add()` 方法,那么你可以在同级目录下创建一个 `add.wasm.d.ts` 文件,并添加相应的类型声明: add.wasm.d.ts export const add: (num1: number, num2: number) => number; --- # 热更新问题 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/faq/hmr.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/faq/hmr#%E7%83%AD%E6%9B%B4%E6%96%B0%E9%97%AE%E9%A2%98) 热更新问题 ============================================================================================ 复制 Markdown ### [#](https://rsbuild.rs/zh/guide/faq/hmr#%E7%83%AD%E6%9B%B4%E6%96%B0%E4%B8%8D%E7%94%9F%E6%95%88%E5%A6%82%E4%BD%95%E6%8E%92%E6%9F%A5) 热更新不生效,如何排查? 热更新不生效有很多种可能的原因,在这篇文档中会介绍大部分常见的原因,你可以参照以下内容进行排查。 在开始排查之前,请简单了解一下热更新的原理: 热更新原理 1. 浏览器和开发服务器建立一个 WebSocket 连接,用于实时通信。 2. 当开发服务器每次重新编译完成后,会通过 WebSocket 通知浏览器,浏览器向开发服务器发送 `hot-update.(js|json)` 请求,从而加载编译后的新模块。 3. 当浏览器收到新的模块后,如果是 React 项目,则会通过 React 官方的 React Refresh 来更新 React 组件,其他框架也是类似。 了解完热更新的原理后,你可以按照以下步骤来进行基本的排查: #### [#](https://rsbuild.rs/zh/guide/faq/hmr#1-%E6%A3%80%E6%9F%A5-websocket-%E8%BF%9E%E6%8E%A5) 1\. 检查 WebSocket 连接 打开浏览器的控制台,查看是否有 `[HMR] connected.` 日志。 * 如果有,说明 WebSocket 连接正常,请继续检查后续步骤。 * 如果没有,请打开 Chrome 的 Network 面板,查看 `ws://[host]:[port]/rsbuild-hmr` 的请求状态,若请求异常,说明热更新失败的原因是 WebSocket 请求没有建立成功。 WebSocket 请求没有建立成功的原因可能有很多种,例如开启了网络代理,导致 WebSocket 请求没有正确发送到开发服务器。你可以检查 WebSocket 请求的地址是否为你的开发服务器地址,如果不是,则可以通过 [dev.client](https://rsbuild.rs/zh/config/dev/client) 来配置 WebSocket 请求的地址。 #### [#](https://rsbuild.rs/zh/guide/faq/hmr#2-%E6%A3%80%E6%9F%A5-hot-update-%E8%AF%B7%E6%B1%82) 2\. 检查 hot-update 请求 当你修改一个模块的代码,并触发重新编译后,浏览器会向开发服务器发送若干个 `hot-update.json` 和 `hot-update.js` 请求,用于获取更新后的代码。 你可以尝试修改一个模块并检查 `hot-update.(js|json)` 请求的内容,如果请求的内容是最新的代码,说明热更新的请求正常。 如果请求的内容错误,大概率也是由于开启了网络代理,请检查 `hot-update.(js|json)` 请求的地址是否为你的开发服务器地址,如果不是,则需要调整代理规则,将 `hot-update.(js|json)` 请求代理到开发服务器地址。 #### [#](https://rsbuild.rs/zh/guide/faq/hmr#3-%E6%A3%80%E6%9F%A5%E5%85%B6%E4%BB%96%E5%8E%9F%E5%9B%A0) 3\. 检查其他原因 如果以上两个步骤都没有问题,那么可能是其他原因导致的热更新失败,比如没有符合 React 对热更新的要求,你可以参考下列的问题进行排查。 * * * ### [#](https://rsbuild.rs/zh/guide/faq/hmr#%E6%89%93%E5%8C%85%E6%97%B6-external-react-%E5%90%8E%E7%83%AD%E6%9B%B4%E6%96%B0%E4%B8%8D%E7%94%9F%E6%95%88) 打包时 external React 后,热更新不生效? 为了保证热更新生效,我们需要使用 React 和 ReactDOM 的开发模式产物。 当你将 React 通过 externals 排除后,通常会通过 CDN 等方式注入 React 的生产模式产物,所以热更新会不生效。 export default { output: { externals: { react: 'React', 'react-dom': 'ReactDOM', }, }, }; 为了解决该问题,你需要引用 React 的开发模式产物,同时安装 React DevTools,安装完成后即可实现热更新。 如果你不确定当前使用的 React 产物类型,可以参考:[React 官方文档 - Use the Production Build](https://legacy.reactjs.org/docs/optimizing-performance.html#use-the-production-build) 。 * * * ### [#](https://rsbuild.rs/zh/guide/faq/hmr#%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E8%AE%BE%E7%BD%AE%E6%96%87%E4%BB%B6%E5%90%8D%E7%9A%84-hash-%E5%90%8E%E7%83%AD%E6%9B%B4%E6%96%B0%E4%B8%8D%E7%94%9F%E6%95%88) 开发环境设置文件名的 hash 后,热更新不生效? 通常来说,我们只会在生产模式下设置文件名的 hash 值(即 `process.env.NODE_ENV === 'production'` 时)。 如果你在开发模式下设置了文件名的 hash,那么可能会导致热更新不生效(尤其是 CSS 文件)。这是因为每次文件内容变化时,都会引起 hash 变化,导致 [mini-css-extract-plugin](https://npmjs.com/package/mini-css-extract-plugin) 等工具无法读取到最新的文件内容。 * 正确用法: export default { output: { filename: { css: process.env.NODE_ENV === 'production' ? '[name].[contenthash:10].css' : '[name].css', }, }, }; * 错误用法: export default { output: { filename: { css: '[name].[contenthash:10].css', }, }, }; * * * ### [#](https://rsbuild.rs/zh/guide/faq/hmr#%E5%BC%80%E5%90%AF-https-%E5%90%8E%E7%83%AD%E6%9B%B4%E6%96%B0%E4%B8%8D%E7%94%9F%E6%95%88) 开启 https 后,热更新不生效? 当开启 https 时,由于证书的问题,可能会出现 HMR 连接失败的情况,此时打开控制台,会出现 HMR connect failed 的报错。 » WebSocket connection to 'wss://localhost:3000/rsbuild-hmr' failed: [HMR] disconnected. Attempting to reconnect. 此问题的解决方法为:点击 Chrome 浏览器问题页面的「高级」->「继续前往 some page(不安全)」。 > Tips: 当通过 Localhost 访问页面时,「你的连接不是私密连接」字样可能不会出现,可访问 Network 域名进行处理。 --- # 使用 Rsdoctor - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/debug/rsdoctor.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/debug/rsdoctor#%E4%BD%BF%E7%94%A8-rsdoctor) 使用 Rsdoctor ======================================================================================= 复制 Markdown [Rsdoctor](https://rsdoctor.rs/) 是一款为 Rspack 生态量身打造的构建分析工具。 Rsdoctor 致力于成为一站式、智能化的构建分析工具,通过可视化与智能分析,使整个构建流程变得透明、可预测和可优化,从而帮助开发团队精准定位瓶颈、优化性能并提升工程质量。 当你需要调试构建产物或构建过程时,可以借助 Rsdoctor 来提升排查问题的效率。 [#](https://rsbuild.rs/zh/guide/debug/rsdoctor#%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B) 快速上手 ----------------------------------------------------------------------------------------- 在基于 Rsbuild 的项目中,你可以通过以下步骤开启 Rsdoctor 分析: 1. 安装 Rsdoctor 插件: npm yarn pnpm bun deno npm add @rsdoctor/rspack-plugin -D yarn add @rsdoctor/rspack-plugin -D pnpm add @rsdoctor/rspack-plugin -D bun add @rsdoctor/rspack-plugin -D deno add npm:@rsdoctor/rspack-plugin -D 2. 在 CLI 命令前添加 `RSDOCTOR=true` 环境变量: package.json { "scripts": { "dev:rsdoctor": "RSDOCTOR=true rsbuild", "build:rsdoctor": "RSDOCTOR=true rsbuild build" } } 由于 Windows 不支持上述用法,你也可以使用 [cross-env](https://npmjs.com/package/cross-env) 来设置环境变量,这可以确保在不同的操作系统中都能正常使用: package.json { "scripts": { "dev:rsdoctor": "cross-env RSDOCTOR=true rsbuild", "build:rsdoctor": "cross-env RSDOCTOR=true rsbuild build" }, "devDependencies": { "cross-env": "^7.0.0" } } 在项目内执行上述命令后,Rsbuild 会自动注册 Rsdoctor 的插件,并在构建完成后打开本次构建的分析页面,请参考 [Rsdoctor 文档](https://rsdoctor.rs/) 来了解完整功能。 [#](https://rsbuild.rs/zh/guide/debug/rsdoctor#%E9%85%8D%E7%BD%AE%E9%A1%B9) 配置项 ------------------------------------------------------------------------------- 如果你需要配置 Rsdoctor 插件提供的 [选项](https://rsdoctor.rs/zh/config/options/options) ,请手动注册 Rsdoctor 插件: rsbuild.config.ts import { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin'; export default { tools: { rspack: { plugins: [\ process.env.RSDOCTOR === 'true' &&\ new RsdoctorRspackPlugin({\ // 插件选项\ }),\ ], }, }, }; --- # 测试 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/advanced/testing.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/advanced/testing#%E6%B5%8B%E8%AF%95) 测试 ======================================================================= 复制 Markdown Rsbuild 本身不内置测试框架,它可以与各种流行的测试工具配合使用。 本指南将介绍如何在 Rsbuild 应用中添加 [单元测试](https://rsbuild.rs/zh/guide/advanced/testing#unit-testing) 和 [端到端测试](https://rsbuild.rs/zh/guide/advanced/testing#end-to-end-testing) 。 [#](https://rsbuild.rs/zh/guide/advanced/testing#unit-testing) 单元测试 ------------------------------------------------------------------- 单元测试用于测试独立的组件和函数。Rsbuild 可以与 [Rstest](https://rstest.rs/) 、[Vitest](https://vitest.dev/) 、[Jest](https://jestjs.io/) 等测试框架配合使用。 下面以 Rstest 为例,介绍如何在 Rsbuild 应用中添加单元测试。 ### [#](https://rsbuild.rs/zh/guide/advanced/testing#rstest) Rstest [Rstest](https://rstest.rs/) 基于 Rsbuild 实现的测试框架,为 Rsbuild 应用提供了一流的支持。它提供与 Jest 兼容的 API,同时原生支持 TypeScript、ESM 等现代特性。 #### [#](https://rsbuild.rs/zh/guide/advanced/testing#%E5%AE%89%E8%A3%85) 安装 npm yarn pnpm bun deno npm add @rstest/core @rstest/adapter-rsbuild -D yarn add @rstest/core @rstest/adapter-rsbuild -D pnpm add @rstest/core @rstest/adapter-rsbuild -D bun add @rstest/core @rstest/adapter-rsbuild -D deno add npm:@rstest/core npm:@rstest/adapter-rsbuild -D #### [#](https://rsbuild.rs/zh/guide/advanced/testing#%E9%85%8D%E7%BD%AE%E8%84%9A%E6%9C%AC) 配置脚本 在 `package.json` 中添加测试脚本: { "scripts": { "test": "rstest", "test:watch": "rstest -w" } } #### [#](https://rsbuild.rs/zh/guide/advanced/testing#%E7%BC%96%E5%86%99%E6%B5%8B%E8%AF%95) 编写测试 创建测试文件,例如: src/utils.ts export function add(a: number, b: number) { return a + b; } src/utils.test.ts import { expect, test } from '@rstest/core'; import { add } from './utils'; test('should add two numbers correctly', () => { expect(add(1, 2)).toBe(3); expect(add(-1, 1)).toBe(0); }); #### [#](https://rsbuild.rs/zh/guide/advanced/testing#%E8%BF%90%E8%A1%8C%E6%B5%8B%E8%AF%95) 运行测试 # 运行测试 npm run test # 运行并监听 npm run test:watch #### [#](https://rsbuild.rs/zh/guide/advanced/testing#%E9%85%8D%E7%BD%AE-rstest) 配置 Rstest 在项目根目录创建 `rstest.config.ts` 文件,并使用 [@rstest/adapter-rsbuild](https://rstest.rs/zh/guide/integration/rsbuild#%E5%A4%8D%E7%94%A8-rsbuild-%E9%85%8D%E7%BD%AE) 复用已有的 Rsbuild 配置: rstest.config.ts import { defineConfig } from '@rstest/core'; import { withRsbuildConfig } from '@rstest/adapter-rsbuild'; export default defineConfig({ extends: withRsbuildConfig(), // 额外的 rstest 特定配置 }); 你可以在同一个配置文件中添加 Rstest 特定的配置,例如测试文件匹配规则、setup 文件和代码覆盖率。 以上就是使用 Rstest 的基本步骤,查看 [Rstest 文档](https://rstest.rs/zh/guide/start/) 了解更多用法。 ### [#](https://rsbuild.rs/zh/guide/advanced/testing#%E7%A4%BA%E4%BE%8B) 示例 [rstack-examples](https://github.com/rstackjs/rstack-examples/tree/main/rstest) 仓库收集了一些 Rstest 使用示例,可用于了解常见用法和实践。 [#](https://rsbuild.rs/zh/guide/advanced/testing#end-to-end-testing) 端到端测试 -------------------------------------------------------------------------- 端到端测试用于测试完整的用户流程,确保应用在真实浏览器环境中正常工作。 你可以使用 Playwright 进行 E2E 测试,它是一个现代的端到端测试框架,详见 [Playwright 文档](https://playwright.dev/docs/intro) 。 --- # Exceptions FAQ - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/faq/exceptions.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/faq/exceptions#exceptions-faq) Exceptions FAQ ========================================================================== Copy Markdown ### [#](https://rsbuild.rs/guide/faq/exceptions#seeing-esnext-code-in-the-compiled-files) Seeing ESNext code in the compiled files? By default, Rsbuild does not compile JavaScript files in `node_modules`. If an npm package includes ESNext syntax, that code is bundled as is. To compile these files, use the [source.include](https://rsbuild.rs/config/source/include) configuration to specify additional directories or modules. * * * ### [#](https://rsbuild.rs/guide/faq/exceptions#build-error-error-object-object-is-not-a-postcss-plugin) Build error `Error: [object Object] is not a PostCSS plugin`? Rsbuild uses PostCSS v8. If you encounter this error during compilation, it's usually because a package is using an incompatible PostCSS version. For example, the `postcss` peer dependency version in `cssnano` may not match the expected version. To find unmet peer dependencies, run `npm ls postcss`. Then fix the issue by specifying the correct PostCSS version in your package.json. npm ls postcss ├─┬ [email protected] │ └── UNMET PEER DEPENDENCY [email protected] ├─┬ [email protected] │ └── UNMET PEER DEPENDENCY [email protected] * * * ### [#](https://rsbuild.rs/guide/faq/exceptions#build-error-you-may-need-additional-loader) Build error `You may need additional loader`? If you see this error during compilation, it means some files cannot be compiled correctly. Module parse failed: Unexpected token File was processed with these loaders: * some-loader/index.js You may need an additional loader to handle the result of these loaders. Check whether you're importing unsupported file formats, and configure the appropriate Rspack loader to handle them. * * * ### [#](https://rsbuild.rs/guide/faq/exceptions#compilation-error-export-foo-imported-as-foo-was-not-found-in-utils) Compilation error `export 'foo' (imported as 'foo') was not found in './utils'`? This error means your code is importing a symbol that doesn't exist. For example, in the following code, `index.ts` is importing the `foo` variable from `utils.ts`, but `utils.ts` only exports the `bar` variable. // utils.ts export const bar = 'bar'; // index.ts import { foo } from './utils'; In this case, Rsbuild will throw the following error: Compile Error: File: ./src/index.ts export 'foo' (imported as 'foo') was not found in './utils' (possible exports: bar) To fix this, check your import/export statements and correct any errors. There are some common mistakes: * Importing a non-existent variable: // utils.ts export const bar = 'bar'; // index.ts import { foo } from './utils'; * Re-exporting a type without the `type` modifier, which prevents transpilers like SWC or Babel from recognizing the type export. // utils.ts export type Foo = 'bar'; // index.ts export { Foo } from './utils'; // Incorrect export type { Foo } from './utils'; // Correct In some cases, a third-party dependency you can't modify causes this error. If you're sure it doesn't affect your application, you can downgrade the log level from `error` to `warn`: rsbuild.config.ts export default { tools: { rspack: { module: { parser: { javascript: { exportsPresence: 'warn', }, }, }, }, }, }; However, you should still contact the dependency maintainer to report the issue. > You can refer to the Rspack documentation for more details on [module.parser.javascript.exportsPresence](https://rspack.rs/config/module-parser#javascriptexportspresence) > . * * * ### [#](https://rsbuild.rs/guide/faq/exceptions#tree-shaking-does-not-take-effect) Tree shaking does not take effect? Rsbuild enables Rspack's tree shaking by default during production builds. Whether tree shaking works depends on whether your code meets Rspack's tree shaking requirements. If tree shaking isn't working as expected, check the `sideEffects` configuration in the related npm package. To learn more about `sideEffects` and tree shaking principles, see [Rspack - Tree shaking](https://rspack.rs/guide/optimization/tree-shaking) . * * * ### [#](https://rsbuild.rs/guide/faq/exceptions#javascript-heap-out-of-memory-when-compiling) `JavaScript heap out of memory` when compiling? This error indicates a memory overflow during the build process. This typically happens when the bundled content exceeds Node.js's default memory limit. To fix out-of-memory issues, the easiest solution is to increase the memory limit using Node.js's `--max-old-space-size` option. Set this by adding [NODE\_OPTIONS](https://nodejs.org/api/cli.html#node_optionsoptions) before your CLI command. For example, add parameters before the `rsbuild build` command: package.json { "scripts": { "build": "rsbuild build" "build": "NODE_OPTIONS=--max_old_space_size=16384 rsbuild build" } } For other commands like `rsbuild dev`, add the parameters before that command instead. The value of the `max_old_space_size` parameter represents the upper limit of the memory size (MB). Generally, it can be set to `16384` (16GB). The following parameters are explained in more detail in the official Node.js documentation: * [NODE\_OPTIONS](https://nodejs.org/api/cli.html#node_optionsoptions) * [\--max-old-space-size](https://nodejs.org/api/cli.html#--max-old-space-sizesize-in-megabytes) Besides increasing the memory limit, you can also improve efficiency by enabling optimization strategies. See [Improve build performance](https://rsbuild.rs/guide/optimization/build-performance) for details. If these methods don't solve your problem, unusual logic in your project may be causing the overflow. Debug recent code changes to find the root cause. If you can't locate it, please contact us. * * * ### [#](https://rsbuild.rs/guide/faq/exceptions#cant-resolve-core-jsmodulesabcjs-when-compiling) `Can't resolve 'core-js/modules/abc.js'` when compiling? If you see an error like this during compilation, it means [core-js](https://github.com/zloirock/core-js) cannot be resolved in your project. Module not found: Can't resolve 'core-js/modules/es.error.cause.js' Rsbuild relies on the project's `core-js` when polyfill injection is enabled, so make sure `core-js` v3 is installed in your project. If `core-js` still cannot be found, the issue may be: 1. Your project overrides Rsbuild's built-in `alias` configuration, causing incorrect `core-js` path resolution. Check your `alias` configuration. 2. Some code depends on `core-js` v2. Find the corresponding code and upgrade to `core-js` v3. 3. An npm package in `node_modules` imports `core-js` but doesn't declare it in `dependencies`. Either add the `core-js` dependency to that package, or install `core-js` in your project root. --- # 代码分割 - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/optimization/code-splitting.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/optimization/code-splitting#%E4%BB%A3%E7%A0%81%E5%88%86%E5%89%B2) 代码分割 ====================================================================================================== 复制 Markdown 代码分割是将代码拆分为多个 chunk 的过程,用于按需加载代码并提升性能。通过合理地拆分代码,可以减少首屏加载体积,加快页面加载速度。 Tip chunk 通常对应一个构建后的资源文件,浏览器可以分别请求和缓存这些 chunk,而不是一次性加载全部代码。 > 参考文档:[Rspack - 代码分割](https://rspack.rs/zh/guide/optimization/code-splitting) > 。 [#](https://rsbuild.rs/zh/guide/optimization/code-splitting#%E4%BD%BF%E7%94%A8%E5%8A%A8%E6%80%81-import) 使用动态 import -------------------------------------------------------------------------------------------------------------------- 通过使用 [动态 import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) ,可以将首屏不需要的代码分割为异步的 chunks,并在需要时再加载。 当 Rsbuild 解析到 `import()` 语法时,会自动将对应的模块拆分为新的 chunk,并在运行时按需加载。 对于体积较大的模块,无论是本地模块还是第三方依赖,都可以通过动态 import 延迟加载: // 本地模块 import('./bigModule.ts').then((bigModule) => { console.log(bigModule); }); // 第三方依赖 import('some-package').then((somePackage) => { console.log(somePackage); }); [#](https://rsbuild.rs/zh/guide/optimization/code-splitting#chunk-%E6%8B%86%E5%88%86) Chunk 拆分 ---------------------------------------------------------------------------------------------- Rsbuild 提供了 [splitChunks](https://rsbuild.rs/zh/config/split-chunks) 选项来配置构建时的 chunk 拆分规则。该配置基于 Rspack 的 `optimization.splitChunks`,并在此基础上提供了一组开箱即用的预设。 通过 `splitChunks`,你可以自定义 chunk 拆分规则,例如控制哪些模块被拆分到同一个 chunk 中,以及设置 chunk 的最小体积等条件,从而更好地平衡加载性能与请求数量。 在下面的示例中,axios 会被单独拆分到一个名为 `axios.js` 的 chunk 中: export default { splitChunks: { cacheGroups: { axios: { test: /[\\/]node_modules[\\/]axios[\\/]/, name: 'axios', chunks: 'all', }, }, }, }; 更多选项与用法请参考 [splitChunks 文档](https://rsbuild.rs/zh/config/split-chunks) 。 --- # Svelte - Rsbuild For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/framework/svelte.md. 菜单目录 [#](https://rsbuild.rs/zh/guide/framework/svelte#svelte) Svelte =============================================================== 复制 Markdown 本文介绍如何基于 Rsbuild 构建 Svelte 应用。 [#](https://rsbuild.rs/zh/guide/framework/svelte#%E5%88%9B%E5%BB%BA-svelte-%E5%BA%94%E7%94%A8) 创建 Svelte 应用 ----------------------------------------------------------------------------------------------------------- 使用 [create-rsbuild](https://rsbuild.rs/zh/guide/start/quick-start#create-an-rsbuild-application) 创建基于 Rsbuild 的 Svelte 应用: npm yarn pnpm bun npm create rsbuild@latest yarn create rsbuild pnpm create rsbuild@latest bun create rsbuild@latest 然后在 `Select framework` 时选择 `Svelte` 即可。 [#](https://rsbuild.rs/zh/guide/framework/svelte#%E5%9C%A8%E5%B7%B2%E6%9C%89%E9%A1%B9%E7%9B%AE%E4%B8%AD%E4%BD%BF%E7%94%A8-svelte) 在已有项目中使用 Svelte ------------------------------------------------------------------------------------------------------------------------------------------------- 要编译 Svelte 组件(`.svelte` 文件),需注册 Rsbuild 的 [Svelte 插件](https://rsbuild.rs/zh/plugins/list/plugin-svelte) ,插件会自动添加 Svelte 构建所需的配置。 例如,在 Rsbuild 配置中注册: rsbuild.config.ts import { defineConfig } from '@rsbuild/core'; import { pluginSvelte } from '@rsbuild/plugin-svelte'; export default defineConfig({ plugins: [pluginSvelte()], }); --- # CSS - Rsbuild For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /guide/styling/css-usage.md. MenuON THIS PAGE [#](https://rsbuild.rs/guide/styling/css-usage#css) CSS ======================================================= Copy Markdown Rsbuild provides out-of-the-box support for CSS, including PostCSS, CSS Modules, CSS preprocessors, CSS inlining, and CSS compression. Rsbuild also provides several configurations to customize CSS file processing. [#](https://rsbuild.rs/guide/styling/css-usage#lightning-css) Lightning CSS --------------------------------------------------------------------------- Tip [Lightning CSS](https://lightningcss.dev/) is a high-performance CSS parser, transformer and minifier written in Rust. It supports parsing and transforming many modern CSS features into syntax supported by target browsers, and delivers better compression ratios. Rsbuild uses Rspack's built-in [lightningcss-loader](https://rspack.rs/guide/features/builtin-lightningcss-loader) to transform CSS code. It automatically reads the project's [browserslist](https://rsbuild.rs/guide/advanced/browserslist) config and converts CSS code to syntax supported by target browsers. ### [#](https://rsbuild.rs/guide/styling/css-usage#features) Features * Lightning CSS automatically adds vendor prefixes like `-webkit-`, `-moz-`, `-ms-`, etc., so you don't need to manually add prefixes or use the [autoprefixer](https://github.com/postcss/autoprefixer) plugin. * Lightning CSS automatically downgrades CSS syntax, allowing you to use modern CSS features such as CSS nesting and custom media queries without worrying about browser compatibility. * Use [tools.lightningcssLoader](https://rsbuild.rs/config/tools/lightningcss-loader) to customize `lightningcss-loader` options. ### [#](https://rsbuild.rs/guide/styling/css-usage#disabling-lightning-css) Disabling Lightning CSS If Lightning CSS does not meet your needs, you can disable Lightning CSS and use [PostCSS](https://rsbuild.rs/guide/styling/css-usage#postcss) to transform your CSS code. Steps: 1. Set [tools.lightningcssLoader](https://rsbuild.rs/config/tools/lightningcss-loader) to `false` to disable the Lightning CSS loader. 2. Use [@rsbuild/plugin-css-minimizer](https://github.com/rstackjs/rsbuild-plugin-css-minimizer) to switch the CSS minifier from Lightning CSS to cssnano or another CSS minifier. rsbuild.config.ts import { pluginCssMinimizer } from '@rsbuild/plugin-css-minimizer'; export default { plugins: [pluginCssMinimizer()], tools: { lightningcssLoader: false, }, }; 3. Refer to [PostCSS](https://rsbuild.rs/guide/styling/css-usage#postcss) to configure the PostCSS plugins you need. Here are some commonly used PostCSS plugins: * [autoprefixer](https://github.com/postcss/autoprefixer) : Adds vendor prefixes. * [postcss-preset-env](https://github.com/csstools/postcss-plugins/tree/main/plugin-packs/postcss-preset-env) : Converts modern CSS into something most browsers can understand. * [postcss-nesting](https://github.com/csstools/postcss-plugins/tree/main/plugins/postcss-nesting) : Supports CSS nesting. [#](https://rsbuild.rs/guide/styling/css-usage#css-minification) CSS minification --------------------------------------------------------------------------------- When building for production, Rsbuild enables Rspack's built-in [LightningCssMinimizerRspackPlugin](https://rspack.rs/plugins/rspack/lightning-css-minimizer-rspack-plugin) plugin to minify CSS assets for better transmission efficiency. * You can disable CSS minification using the [output.minify](https://rsbuild.rs/config/output/minify) option or customize the options for `LightningCssMinimizerRspackPlugin`. * You can use [@rsbuild/plugin-css-minimizer](https://github.com/rstackjs/rsbuild-plugin-css-minimizer) to customize the CSS minimizer, switching to [cssnano](https://github.com/cssnano/cssnano) or another CSS minimizer. [#](https://rsbuild.rs/guide/styling/css-usage#postcss) PostCSS --------------------------------------------------------------- Rsbuild supports transforming CSS code through [PostCSS](https://postcss.org/) . You can configure PostCSS in the following ways: ### [#](https://rsbuild.rs/guide/styling/css-usage#configuration-file) Configuration file Rsbuild uses [postcss-load-config](https://github.com/postcss/postcss-load-config) to load the PostCSS configuration file in the root directory of the current project, such as `postcss.config.js`: postcss.config.cjs module.exports = { plugins: { 'postcss-px-to-viewport': { viewportWidth: 375, }, }, }; `postcss-load-config` supports multiple file formats, including but not limited to the following file names: * postcss.config.js * postcss.config.mjs * postcss.config.cjs * postcss.config.ts * ... ### [#](https://rsbuild.rs/guide/styling/css-usage#toolspostcss) tools.postcss You can also configure the postcss-loader through Rsbuild's [tools.postcss](https://rsbuild.rs/config/tools/postcss) option, which supports modifying the built-in configuration through a function, for example: rsbuild.config.ts export default { tools: { postcss: (opts) => { const viewportPlugin = require('postcss-px-to-viewport')({ viewportWidth: 375, }); opts.postcssOptions.plugins.push(viewportPlugin); }, }, }; ### [#](https://rsbuild.rs/guide/styling/css-usage#configuration-priority) Configuration priority * When you configure both the `postcss.config.js` file and the `tools.postcss` option, both will take effect, and the `tools.postcss` option will take precedence. * If there is no `postcss.config.js` file in the project and the `tools.postcss` option is not configured, Rsbuild will not register `postcss-loader`. [#](https://rsbuild.rs/guide/styling/css-usage#css-modules) CSS Modules ----------------------------------------------------------------------- Rsbuild supports CSS Modules by default, please read the [CSS Modules](https://rsbuild.rs/guide/styling/css-modules) chapter for the complete usage of CSS Modules. [#](https://rsbuild.rs/guide/styling/css-usage#css-preprocessors) CSS preprocessors ----------------------------------------------------------------------------------- Rsbuild supports popular CSS preprocessors through plugins, including Sass, Less and Stylus. See how to use them: * [Sass plugin](https://rsbuild.rs/plugins/list/plugin-sass) * [Less plugin](https://rsbuild.rs/plugins/list/plugin-less) * [Stylus Plugin](https://github.com/rstackjs/rsbuild-plugin-stylus) [#](https://rsbuild.rs/guide/styling/css-usage#css-in-js) CSS-in-JS ------------------------------------------------------------------- See [CSS-in-JS](https://rsbuild.rs/guide/styling/css-in-js) to learn how to use common CSS-in-JS libraries in Rsbuild. [#](https://rsbuild.rs/guide/styling/css-usage#inline-css-files) Inline CSS files --------------------------------------------------------------------------------- By default, Rsbuild will extract CSS into a separate `.css` file and output it to the dist directory. To inline styles into your JS file, set [output.injectStyles](https://rsbuild.rs/config/output/inject-styles) to true to disable CSS extraction logic. When the JS file is requested by the browser, JS dynamically inserts the `