### Initialize TanStack Start Example Project Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/framework/solid.mdx Clone and set up the TanStack Start example project for a full-stack Solid experience with Rsbuild. ```bash pnpx degit https://github.com/rstackjs/rstack-examples/rsbuild/tanstack-start-solid tanstack-start cd tanstack-start pnpm i ``` -------------------------------- ### Initialize TanStack Start Example Project Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/framework/react.mdx Clone and set up the TanStack Start example project, which is a full-stack React framework built on Rsbuild. ```bash pnpx degit https://github.com/rstackjs/rstack-examples/rsbuild/tanstack-start tanstack-start cd tanstack-start pnpm i ``` -------------------------------- ### Async Setup Function Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/server/setup.mdx Use an async function for `server.setup` to perform asynchronous tasks before the server starts. The example shows returning a promise from an async task. ```typescript export default { server: { setup: async ({ server, action }) => { return someAsyncTask(); }, }, }; ``` -------------------------------- ### Array Form for Multiple Setup Functions Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/server/setup.mdx Provide an array of functions to `server.setup` to execute multiple setup routines independently. This example registers both an authentication and a logging middleware. ```typescript export default { server: { setup: [ ({ server }) => { server.middlewares.use(authMiddleware); }, ({ server }) => { server.middlewares.use(logMiddleware); }, ], }, }; ``` -------------------------------- ### Start Development Server Source: https://github.com/web-infra-dev/rsbuild/blob/main/packages/create-rsbuild/template-common/AGENTS.md Use this command to start the development server for local development and testing. ```bash npm run dev ``` -------------------------------- ### Start Rsbuild Dev Server and Get Instance Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/server-api.mdx Start the dev server and retrieve the server instance using rsbuild.startDevServer(). ```typescript const { server } = await rsbuild.startDevServer(); console.log('the dev server is ', server); ``` -------------------------------- ### Install migrate-to-rsbuild skill Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/migration/cra.mdx Install the migrate-to-rsbuild skill using npx to assist with the migration process. ```bash npx skills add rstackjs/agent-skills --skill migrate-to-rsbuild ``` -------------------------------- ### Install and View CPU Profile with Speedscope Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/debug/build-profiling.mdx Install the speedscope tool globally and use it to visualize the generated *.cpuprofile file. Replace the filename with your actual profile file name. ```bash # 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 ``` -------------------------------- ### Demonstrate All Logger Methods Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/advanced/logging.mdx Showcase the usage of various logger methods including greet, info, start, warn, ready, success, error, debug, and log. Includes an example of logging an error with a stack trace. ```typescript import { logger } from '@rsbuild/core'; // A gradient welcome log logger.greet(` ➜ Rsbuild v1.0.0 `); // 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'); ``` -------------------------------- ### Start Rsbuild Preview Server Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Use `preview` to start a server for locally previewing production builds. Ensure `rsbuild.build` has been executed prior to calling this method. ```typescript 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); } ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/web-infra-dev/rsbuild/blob/main/packages/create-rsbuild/template-common/README.md Run this command to install all necessary project dependencies using your package manager. ```bash {{ packageManager }} install ``` -------------------------------- ### listen Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/server-api.mdx Starts the development server and returns information about the listening port and URLs. ```APIDOC ## listen ### Description Starts the server and returns the listening result. If you are using [server.middlewareMode](/config/server/middleware-mode), you usually don't need to call this method. ### Method `() => Promise<{ port: number; urls: string[]; server: RsbuildDevServer }> ` ### Response #### Success Response (200) - **port** (number) - The port the server is listening on. - **urls** (string[]) - An array of URLs the server is accessible at. - **server** (RsbuildDevServer) - The RsbuildDevServer instance. ### Request Example ```ts const rsbuildServer = await rsbuild.createDevServer(); const { port, urls } = await rsbuildServer.listen(); console.log(port, urls); ``` ``` -------------------------------- ### Install React Plugin Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/zh/plugins/list/plugin-react.mdx Install the React plugin using your preferred package manager. ```bash npm install @rsbuild/plugin-react -D # or yarn add @rsbuild/plugin-react -D # or pnpm add @rsbuild/plugin-react -D ``` -------------------------------- ### Start Rsbuild Development Server Source: https://github.com/web-infra-dev/rsbuild/blob/main/packages/create-rsbuild/template-common/README.md Use this command to start the development server. Your application will be accessible at http://localhost:3000. ```bash {{ packageManager }} run dev ``` -------------------------------- ### Preview Server Started - onAfterStartPreviewServer Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Called after the preview server has successfully started. Access the port and routes information. ```typescript rsbuild.onAfterStartPreviewServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); ``` -------------------------------- ### Setting up ESLint in package.json Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/migration/cra.mdx Configure the 'lint' script in your package.json to run ESLint on your source files. This example assumes you have ESLint and eslint-config-react-app installed. ```json { "scripts": { "lint": "eslint src" }, "eslintConfig": { "extends": ["react-app", "react-app/jest"] } } ``` -------------------------------- ### Get Rsbuild Config Examples Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/shared/getRsbuildConfig.mdx Demonstrates how to use the `getRsbuildConfig` function to retrieve different versions of the Rsbuild configuration. Ensure 'normalized' is called after the `modifyRsbuildConfig` hook. ```javascript // Get the original Rsbuild config defined by the user. getRsbuildConfig('original'); ``` ```javascript // 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'); ``` ```javascript // 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'); ``` -------------------------------- ### On Before Start Dev Server Hook Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/plugins/dev/hooks.mdx This hook executes just before the development server starts. It provides access to the server instance and environment contexts, allowing for pre-server setup or configuration. ```typescript 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); }); }, }); ``` -------------------------------- ### Server API - Integrate with Custom Server Example Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/server-api.mdx An example demonstrating how to integrate Rsbuild's dev server with a custom Express.js server. ```APIDOC ## Server API - Integrate with Custom Server Example Here is an example of integrating [express](https://expressjs.com/) with Rsbuild dev server: ```ts 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`](/api/javascript-api/instance#rsbuildcreatedevserver) - [`server.middlewareMode`](/config/server/middleware-mode) ``` -------------------------------- ### Start the Rsbuild development server Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/server-api.mdx Call `listen` to start the development server. It returns the port number and URLs the server is listening on. Avoid using this if `server.middlewareMode` is enabled. ```typescript const rsbuildServer = await rsbuild.createDevServer(); const { port, urls } = await rsbuildServer.listen(); console.log(port, urls); ``` -------------------------------- ### Example File Descriptors for Manifest Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/output/manifest.mdx Illustrates the structure of the `files` parameter passed to the `manifest.generate` function, showing example file objects. ```typescript const files = [ { name: 'index.js', path: '/static/js/index.[hash].js', isAsset: false, isChunk: true, isInitial: true, isModuleAsset: false, chunk: { // Chunk info... }, }, { name: 'index.html', path: '/index.html', isAsset: true, isChunk: false, isInitial: false, isModuleAsset: false, }, ]; ``` -------------------------------- ### Create Rsbuild Instance Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/core.mdx Instantiate Rsbuild with basic configuration. Use this to start a new build process. ```javascript import { createRsbuild } from '@rsbuild/core'; const rsbuild = await createRsbuild({ config: { // Rsbuild configuration }, }); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/start/quick-start.mdx Install project dependencies using npm. Replace 'npm install' with your package manager's install command if necessary. ```bash npm install ``` -------------------------------- ### Install UnoCSS and PostCSS Plugin Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/styling/unocss.mdx Install the necessary UnoCSS packages for your project using your preferred package manager. ```bash npm install unocss @unocss/postcss -D # or yarn add unocss @unocss/postcss -D # or pnpm add unocss @unocss/postcss -D ``` -------------------------------- ### Install Dependencies and Run Development Checks Source: https://github.com/web-infra-dev/rsbuild/blob/main/AGENTS.md Installs project dependencies using pnpm and runs essential development checks like linting, unit tests, and end-to-end tests. ```bash # setup corepack enable && pnpm install # dev checks pnpm lint pnpm test pnpm e2e ``` -------------------------------- ### Rsbuild Prefetch Configuration Example Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/performance/prefetch.mdx Configure Rsbuild to enable prefetching for all async resources on the current page. ```typescript export default { performance: { prefetch: true, }, }; ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/web-infra-dev/rsbuild/blob/main/CONTRIBUTING.md Installs project dependencies, links monorepo packages, and runs the prepare script. Ensure Corepack is enabled and updated to the latest version. ```sh npm i corepack@latest -g corepack enable pnpm install ``` -------------------------------- ### Dev Server Started - onAfterStartDevServer Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Called after the development server has successfully started. Access the port it's running on and its routes. ```typescript rsbuild.onAfterStartDevServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); ``` -------------------------------- ### Install Rsbuild dependencies Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/migration/cra.mdx Install Rsbuild core and the React plugin as development dependencies. ```bash npm add @rsbuild/core @rsbuild/plugin-react -D ``` -------------------------------- ### rsbuild.startDevServer Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Starts the local dev server, serving your application and watching for file changes to trigger recompilation. ```APIDOC ## 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 ### Description This method initiates a local development server that serves your application and automatically recompiles upon detecting file changes. It returns information about the server's URLs and port, and provides a method to close the server. ### Method `startDevServer(options?: StartDevServerOptions): Promise` ### Parameters #### Options - **getPortSilently** (boolean) - Optional - Whether to get port silently and not print any logs. Defaults to `false`. ### Returns - **urls** (string[]) - The URLs that the server is listening on. - **port** (number) - The actual port used by the server. - **server** (RsbuildDevServer) - The server instance. ### Example ```ts // 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); } // Get server details const { urls, port } = await rsbuild.startDevServer(); console.log(urls); // ['http://localhost:3000', 'http://192.168.0.1:3000'] console.log(port); // 3000 // Close server const { server } = await rsbuild.startDevServer(); await server.close(); // Get port silently await rsbuild.startDevServer({ getPortSilently: true, }); ``` ``` -------------------------------- ### Example Manifest JSON Structure Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/output/manifest.mdx This is an example of the `manifest.json` file generated by Rsbuild, showing the mapping of all files and entries. ```json { "allFiles": [ "/static/css/index.[hash].css", "/static/js/index.[hash].js", "/static/images/logo.[hash].png", "/index.html" ], "entries": { "index": { "initial": { "js": ["/static/js/index.[hash].js"], "css": ["/static/css/index.[hash].css"] }, "assets": ["/static/images/logo.[hash].png"], "html": ["/index.html"] } } } ``` -------------------------------- ### Rsbuild Dev Client Configuration Example Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/dev/client.mdx Configure the WebSocket URL for HMR. This example sets the protocol to 'ws', host to '127.0.0.1', and port to 3000. ```typescript export default { dev: { client: { protocol: 'ws', // Usually `127.0.0.1` is used to avoid cross-origin requests being blocked by the browser host: '127.0.0.1', port: 3000, }, }, }; ``` -------------------------------- ### Pre-Plugin Dependency Example Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/plugins/dev/core.mdx Demonstrates how the 'pre' property can be used to specify that 'plugin-foo' must execute before 'plugin-bar'. ```typescript const pluginFoo = { name: 'plugin-foo', }; const pluginBar = { name: 'plugin-bar', pre: ['plugin-foo'], }; ``` -------------------------------- ### Post-Plugin Dependency Example Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/plugins/dev/core.mdx Demonstrates how the 'post' property can be used to specify that 'plugin-foo' must execute after 'plugin-bar'. ```typescript const pluginFoo = { name: 'plugin-foo', }; const pluginBar = { name: 'plugin-bar', post: ['plugin-foo'], }; ``` -------------------------------- ### Example tsconfig.json with paths Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/resolve/alias-strategy.mdx Demonstrates how to define path aliases in tsconfig.json. This configuration is used when resolve.aliasStrategy is 'prefer-tsconfig'. ```json { "compilerOptions": { "paths": { "@common/*": ["./src/common-1/*"] } } } ``` -------------------------------- ### rsbuild.onAfterStartDevServer Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Registers a callback function to be executed after the development server has started. This hook provides information about the port and routes. ```APIDOC ## rsbuild.onAfterStartDevServer ### Description Registers a callback function to be executed after the development server has started. This hook provides information about the port and routes. ### Method `onAfterStartDevServer` ### Parameters - `callback` (function) - Required - A function that receives an object containing `port` and `routes`. - `port` (number) - The port the development server is running on. - `routes` (Array) - The routes available on the development server. ### Example ```javascript rsbuild.onAfterStartDevServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); ``` ``` -------------------------------- ### Extend Built-in Server with Middleware Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/blog/v2-0.mdx Use the `server.setup` option to run initialization logic when the dev server or preview server starts. This allows for customization like registering middleware or running tasks before startup. ```typescript export default { server: { setup: ({ server }) => { server.middlewares.use((req, res, next) => { if (req.url === '/api/health') { res.end('ok'); return; } next(); }); }, }, }; ``` -------------------------------- ### Preview Server Instance with Rsbuild Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/server-api.mdx Get the preview server instance using rsbuild.preview(). ```typescript const { server } = await rsbuild.preview(); console.log('the preview server is ', server); ``` -------------------------------- ### rsbuild.onAfterStartPreviewServer Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Registers a callback function to be executed after the preview server has started. This hook provides information about the port and routes. ```APIDOC ## rsbuild.onAfterStartPreviewServer ### Description Registers a callback function to be executed after the preview server has started. This hook provides information about the port and routes. ### Method `onAfterStartPreviewServer` ### Parameters - `callback` (function) - Required - A function that receives an object containing `port` and `routes`. - `port` (number) - The port the preview server is running on. - `routes` (Array) - The routes available on the preview server. ### Example ```javascript rsbuild.onAfterStartPreviewServer(({ port, routes }) => { console.log('this port is: ', port); console.log('this routes is: ', routes); }); ``` ``` -------------------------------- ### Incorrect Babel Plugin Name or Installation Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/plugins/list/plugin-babel.mdx This example shows an incorrect usage where a non-existent Babel plugin is added. Ensure all plugin names are correct and installed. ```typescript pluginBabel({ babelLoaderOptions: (config, { addPlugins }) => { // The plugin has the wrong name or is not installed addPlugins('babel-plugin-not-exists'); }, }); ``` -------------------------------- ### afterListen Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/server-api.mdx Notifies Rsbuild that the custom server has successfully started. Rsbuild will trigger the onAfterStartDevServer hook at this stage. ```APIDOC ## afterListen ### Description Notifies Rsbuild that the custom server has successfully started. Rsbuild will trigger the [onAfterStartDevServer](/plugins/dev/hooks#onafterstartdevserver) hook at this stage. ### Method `() => Promise` ### Request Example ```ts 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(); }); ``` ``` -------------------------------- ### Create a New Rsbuild Project Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/framework/preact.mdx Use the create-rsbuild command to initialize a new project. Select 'Preact' when prompted for the framework. ```bash npm create rsbuild@latest ``` ```bash yarn create rsbuild ``` ```bash pnpm create rsbuild@latest ``` ```bash bun create rsbuild@latest ``` -------------------------------- ### Rsbuild Plugin Example: Custom Message on Server Start Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/plugins/dev/index.mdx A basic Rsbuild plugin that logs a custom message when the development server starts. It accepts an options object for customization. ```typescript 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); }); }, }); ``` -------------------------------- ### Register Sass Plugin in Rsbuild Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/plugins.mdx Example of registering the Sass plugin in Rsbuild configuration. Ensure the plugin is installed first. ```typescript import { defineConfig } from '@rsbuild/core'; import { pluginSass } from '@rsbuild/plugin-sass'; export default defineConfig({ plugins: [pluginSass()] }); ``` -------------------------------- ### Define Rsbuild Plugin Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/migration/vite-plugin.mdx Example of defining an Rsbuild plugin using the setup function and accessing hooks via the api object. ```typescript const rsbuildPlugin = (options) => ({ name: 'rsbuild-plugin', setup(api) { api.transform(() => { // ... }); }, }); ``` -------------------------------- ### Start Development Server Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Launches a local development server for serving the application and watching for file changes. Includes error handling for startup failures. ```typescript 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); } ``` -------------------------------- ### Example: Using '2023-11' Decorator Version Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/source/decorators.mdx Configure Rsbuild to use the '2023-11' decorator syntax version. ```APIDOC ## Configuration: source.decorators.version = '2023-11' ### Description This example demonstrates how to set the decorator version to '2023-11' in your `rsbuild.config.ts` file. ### Method Configuration ### Endpoint N/A ### Request Example ```typescript // rsbuild.config.ts export default { source: { decorators: { version: '2023-11', }, }, }; ``` ### Response Example (Configuration applied, no direct response) ``` -------------------------------- ### Example: Using '2022-03' Decorator Version Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/source/decorators.mdx Configure Rsbuild to use the '2022-03' decorator syntax version. ```APIDOC ## Configuration: source.decorators.version = '2022-03' ### Description This example shows how to configure Rsbuild to use the '2022-03' decorator syntax version, which is equivalent to TypeScript 5.0's default. ### Method Configuration ### Endpoint N/A ### Request Example ```typescript // rsbuild.config.ts export default { source: { decorators: { version: '2022-03', }, }, }; ``` ### Response Example (Configuration applied, no direct response) ``` -------------------------------- ### rsbuild.preview Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Starts a server to preview the production build locally. This method should be called after `rsbuild.build` and provides access to server details like URLs and port. ```APIDOC ## rsbuild.preview ### Description Starts a server to preview the production build locally. This method should be called after `rsbuild.build` and provides access to server details like URLs and port. ### Method ```ts function preview(options?: PreviewOptions): Promise; ``` ### Parameters #### Options - **getPortSilently** (boolean) - Optional - Whether to get port silently. - **checkDistDir** (boolean) - Optional - Whether to check if the dist directory exists and is not empty. ### Returns - **urls** (string[]) - URLs to access server. - **port** (number) - The actual listening port number. - **server** (RsbuildPreviewServer) - Server instance. ### Example Start the server: ```ts 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); } ``` Accessing returned parameters: ```ts const { urls, port } = await rsbuild.preview(); console.log(urls); console.log(port); ``` ### Close server Calling the `close()` method will close the preview server. ```ts const { server } = await rsbuild.preview(); await server.close(); ``` ``` -------------------------------- ### Asynchronous Entry Point Setting with Glob Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/source/entry.mdx Demonstrates how to set entry points asynchronously by exporting an async function from the config file. It uses the 'glob' package to find entry files and dynamically creates the entry configuration. ```typescript import path from 'node:path'; import { glob } from 'glob'; import { defineConfig } from '@rsbuild/core'; export default defineConfig(async () => { const entryFiles = await glob('./src/**/main.{ts,tsx,js,jsx}'); const entry = Object.fromEntries( entryFiles.map((file) => { const entryName = path.basename(path.dirname(file)); return [entryName, `./${file}`]; }), ); return { source: { entry: entry, }, }; }); ``` -------------------------------- ### Get Rsbuild Core Version Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/core.mdx Import and use the `version` constant from `@rsbuild/core` to retrieve the currently installed version of the Rsbuild core package. ```typescript import { version } from '@rsbuild/core'; console.log(version); // 1.0.0 ``` -------------------------------- ### Trigger Agent Skill Prompt Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/start/ai.mdx After installing a skill, use natural language prompts to trigger it. For example, ask AI to help migrate a project. ```text Help me migrate this Vite project to Rsbuild ``` -------------------------------- ### Named Component Example for Prefresh Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/framework/preact.mdx This demonstrates how to name a component, which is required for Prefresh to recognize and hot-reload it effectively. ```jsx const MyComponent = () => { return

Want to refresh

; }; export default MyComponent; ``` -------------------------------- ### Build, Format, and Generate Docs Source: https://github.com/web-infra-dev/rsbuild/blob/main/AGENTS.md Commands to build the project, format code according to conventions, and generate documentation. ```bash # build / format / docs pnpm build pnpm format pnpm doc ``` -------------------------------- ### Getting Rsbuild Configuration in Plugin Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/plugins/dev/core.mdx Illustrates how to retrieve the current Rsbuild configuration object within a plugin's setup function to inspect or modify settings like the HTML title. ```typescript const pluginFoo = () => ({ setup(api) { const config = api.getRsbuildConfig(); console.log(config.html?.title); }, }); ``` -------------------------------- ### Start Dev Server on All Interfaces Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/basic/cli.mdx To make the development server listen on all available network interfaces, use the `--host` flag without a value or with `0.0.0.0`. This is useful for accessing the dev server from other devices on the same network. ```bash npx rsbuild --host ``` ```bash # equivalent to: npx rsbuild --host 0.0.0.0 ``` -------------------------------- ### Implement Custom Pug Transformation Plugin Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/blog/v0-6.mdx This example shows how to create a Rsbuild plugin to transform `.pug` files into JavaScript code using the `api.transform` method. It requires the `pug` package to be installed. ```typescript 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;`; }); }, }); ``` -------------------------------- ### Prepare Preview Server Start - onBeforeStartPreviewServer Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Intercept the preview server startup. This hook provides the server instance and environment contexts before the server begins. ```typescript rsbuild.onBeforeStartPreviewServer(({ server, environments }) => { console.log('before start!'); console.log('the server is ', server); console.log('the environments contexts are: ', environments); }); ``` -------------------------------- ### Open Page Automatically on Startup Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/basic/cli.mdx Use the `--open` flag to automatically open a page in your browser when the development server starts. This flag can also accept a specific URL to open. ```bash rsbuild --open ``` ```bash rsbuild --open http://localhost:3000/foo ``` ```bash rsbuild -o ``` -------------------------------- ### Access build output stats for an environment Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/server-api.mdx Use the `environments` API to retrieve build output information for a specific environment on the server side. This example shows how to get stats for the 'web' environment. ```typescript const rsbuildServer = await rsbuild.createDevServer(); const webStats = await rsbuildServer.environments.web.getStats(); console.log(webStats.toJson({ all: false })); ``` -------------------------------- ### Configure Rsbuild Server Setup Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/server-api.mdx Use the server.setup option to access dev and preview server instances within your Rsbuild configuration. ```typescript export default { server: { setup: ({ server }) => { console.log('the server is ', server); }, }, }; ``` -------------------------------- ### GitHub Actions Workflow for Rsbuild Deployment Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/basic/deployment.mdx A sample GitHub Actions workflow to build and deploy an Rsbuild site to GitHub Pages. This workflow handles checkout, Node.js setup, dependency installation, building, and deployment. ```yaml # 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 ``` -------------------------------- ### Incorrect Tailwind CSS Content Configuration in Monorepo Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/styling/tailwindcss-v3.mdx This example illustrates an incorrect content path configuration in a monorepo setup, where a `node_modules` directory within a package is inadvertently scanned. Always ensure paths accurately point to the source files within your packages. ```javascript module.exports = { content: [ './src/**/*.{html,js,ts,jsx,tsx}', // Incorrectly includes the `packages/ui/node_modules` directory // Should be '../../packages/ui/src/**/*.{html,js,ts,jsx,tsx}' '../../packages/ui/**/*.{html,js,ts,jsx,tsx}', ], }; ``` -------------------------------- ### Build for Production Source: https://github.com/web-infra-dev/rsbuild/blob/main/packages/create-rsbuild/template-common/AGENTS.md Execute this command to create an optimized production build of your application. ```bash npm run build ``` -------------------------------- ### Server API - How to Use Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/server-api.mdx Demonstrates various ways to access and utilize Rsbuild server instances, including configuration options, plugin hooks, and JavaScript API methods. ```APIDOC ## Server API - How to Use Rsbuild provides server APIs for both dev and preview servers, available through configuration, plugin hooks, and JavaScript API. ### Configuration Rsbuild provides the `server.setup` option to access dev and preview server instances. ```ts export default { server: { setup: ({ server }) => { console.log('the server is ', server); }, }, }; ``` ### Plugin Hooks Plugin authors can access dev and preview server instances through the `onBeforeStartDevServer` and `onBeforeStartPreviewServer` hooks. ```ts const myPlugin = () => ({ setup(api) { api.onBeforeStartDevServer(({ server }) => { console.log('the dev server is ', server); }); api.onBeforeStartPreviewServer(({ server }) => { console.log('the preview server is ', server); }); }, }); ``` ### JavaScript API - Create a dev server instance via `rsbuild.createDevServer()`: ```ts const devServer = await rsbuild.createDevServer(); console.log('the dev server is ', devServer); ``` - Get the dev server instance via `rsbuild.startDevServer()`: ```ts const { server } = await rsbuild.startDevServer(); console.log('the dev server is ', server); ``` - Get the preview server instance via `rsbuild.preview()`: ```ts const { server } = await rsbuild.preview(); console.log('the preview server is ', server); ``` ``` -------------------------------- ### Set dev.assetPrefix with a relative path string Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/dev/asset-prefix.mdx Configure dev.assetPrefix to '/example/', which will be prepended to static resource URLs. ```typescript export default { dev: { assetPrefix: '/example/', }, }; ``` -------------------------------- ### Unnamed Component Example Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/framework/preact.mdx This shows an example of a component that Prefresh might not recognize due to being unnamed. ```jsx export default () => { return

Want to refresh

; }; ``` -------------------------------- ### Prepare Dev Server Start - onBeforeStartDevServer Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Intercept the dev server startup process. This hook provides access to the server instance and environment contexts before it begins serving. ```typescript rsbuild.onBeforeStartDevServer(({ server, environments }) => { console.log('before starting dev server.'); console.log('the server is ', server); console.log('the environments contexts are: ', environments); }); ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/start/quick-start.mdx Initialize a Git repository in the current project directory. ```bash git init ``` -------------------------------- ### Example of a legal comment in React Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/output/legal-comments.mdx This is an example of a legal comment found in the React source code, typically containing license information. ```javascript /** * @license React * react.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ ``` -------------------------------- ### Create Rsbuild Project with CLI Flags Source: https://github.com/web-infra-dev/rsbuild/blob/main/packages/create-rsbuild/README.md Create a new Rsbuild project specifying the directory and template using npx. Abbreviations are also supported. ```bash npx create-rsbuild --dir my-project --template react ``` ```bash npx create-rsbuild -d my-project -t react ``` -------------------------------- ### Notify Rsbuild after custom server starts Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/server-api.mdx Use `afterListen` to notify Rsbuild when your custom server has successfully started. This hook is triggered before `onAfterStartDevServer`. ```typescript 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(); }); ``` -------------------------------- ### Classic JSX Runtime Usage Example Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/plugins/list/plugin-react.mdx Example of a React component using the classic JSX runtime, requiring explicit React import. ```jsx import React from 'react'; function App() { return

Hello World

; } ``` -------------------------------- ### Start Development Server Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/start/index.mdx Call `rsbuild.startDevServer()` to launch a local development server for rapid iteration. Logs indicate the server's local and network addresses upon successful startup. ```typescript await rsbuild.startDevServer(); ``` -------------------------------- ### Rename dev.startUrl to server.open Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/upgrade/v0-to-v1.mdx The `dev.startUrl` configuration option has been renamed to `server.open`. Update your configuration accordingly. ```js export default { // [!code --] dev: { startUrl: true, // [!code --] }, // [!code --] // [!code ++] server: { open: true, // [!code ++] }, // [!code ++] }; ``` -------------------------------- ### Create a new Rsbuild project Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/start/quick-start.mdx Use the create-rsbuild CLI to initialize a new project. You can specify a template and additional tools like ESLint and Prettier. ```bash npx -y create-rsbuild@latest my-app -t react ``` ```bash npx -y create-rsbuild@latest my-app -t react --tools eslint,prettier ``` -------------------------------- ### Importing a YAML file Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/basic/json-files.mdx Demonstrates importing a YAML file after configuring the YAML plugin and accessing its data. ```yaml --- hello: world foo: bar: baz ``` ```js import example from './example.yaml'; console.log(example.hello); // 'world'; console.log(example.foo); // { bar: 'baz' }; ``` -------------------------------- ### Install Agent Skill Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/start/ai.mdx Use the 'skills' package to install a specific Agent Skill for Rsbuild. This enables AI to provide more accurate suggestions and perform actions in specific scenarios. ```bash skills add rstackjs/agent-skills --skill migrate-to-rsbuild ``` -------------------------------- ### Preview Production Build Source: https://github.com/web-infra-dev/rsbuild/blob/main/packages/create-rsbuild/template-common/AGENTS.md This command allows you to preview the production build locally before deploying. ```bash npm run preview ``` -------------------------------- ### Example Usage of Tailwind CSS Utility Classes Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/styling/tailwindcss.mdx Demonstrates how to use Tailwind CSS utility classes directly in your HTML for styling. This example shows basic text styling. ```html

Hello world!

``` -------------------------------- ### Configure Prefetch Include with String Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/performance/prefetch.mdx Use a string that will be converted to a regular expression to include files for prefetching. This example includes .png files. ```typescript export default { performance: { prefetch: { include: '\.png', // equivalent to `new RegExp('\.png')` }, }, }; ``` -------------------------------- ### Rstest Unit Test Example Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/advanced/testing.mdx Example of a simple utility function and its corresponding unit test using Rstest. Ensure the test file is named with a .test.ts or similar suffix. ```typescript export function add(a: number, b: number) { return a + b; } ``` ```typescript 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); }); ``` -------------------------------- ### Rsbuild OnAfterStartDevServer Hook Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/shared/onAfterStartDevServer.mdx The `OnAfterStartDevServer` hook allows you to execute a callback function after the dev server starts. The callback receives `port`, `routes`, and `environments` as parameters. Use this to perform actions based on server startup details. ```typescript function OnAfterStartDevServer( callback: (params: { port: number; routes: Routes; environments: Record; }) => Promise | void, ): void; ``` -------------------------------- ### Getting Normalized Config in Plugin Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/plugins/dev/core.mdx Demonstrates how to get the normalized Rsbuild configuration within a plugin, specifically using the `onBeforeBuild` hook to access settings like the HTML title. ```typescript const pluginFoo = () => ({ setup(api) { api.onBeforeBuild(({ bundlerConfigs }) => { const config = api.getNormalizedConfig(); console.log(config.html.title); }); }, }); ``` -------------------------------- ### Start Dev Server Silently Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/instance.mdx Starts the development server while suppressing logs related to port selection. Useful when the default port is occupied and Rsbuild automatically finds a new one. ```typescript await rsbuild.startDevServer({ getPortSilently: true, }); ``` -------------------------------- ### Create Rsbuild configuration file Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/migration/webpack.mdx Initialize an Rsbuild configuration file with basic settings. ```typescript import { defineConfig } from '@rsbuild/core'; export default defineConfig({ plugins: [], }); ``` -------------------------------- ### Customize Help Hint Message Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/dev/cli-shortcuts.mdx Provide a custom string to the `help` option to display a personalized help message when the server starts. ```typescript export default { dev: { cliShortcuts: { help: 'type "h + enter" to view available commands', }, }, }; ``` -------------------------------- ### Environment Plugin Example Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/plugins/dev/index.mdx This example demonstrates how to create an environment plugin that modifies the HTML title and sets a chain name based on the environment. It uses `modifyEnvironmentConfig` to ensure environment-specific configuration. ```typescript 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); }); }, }); ``` -------------------------------- ### Example AGENTS.md Content Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/start/ai.mdx An example AGENTS.md file content that provides key project information to AI agents, including commands and documentation links. This file is generated when creating a new project with create-rsbuild. ```markdown # AGENTS.md You are an expert in JavaScript, Rsbuild, and web application development. You write maintainable, performant, and accessible code. ## Commands - `npm run dev` - Start the dev server - `npm run build` - Build the app for production - `npm run preview` - Preview the production build locally ## Docs - Rsbuild: https://rsbuild.rs/llms.txt - Rspack: https://rspack.rs/llms.txt ``` -------------------------------- ### Get Build Stats Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/environment-api.mdx Fetches the build statistics for the current environment. ```APIDOC ### getStats Get the build stats of current environment. - **Type:** ```ts type GetStats = () => Promise; ``` - **Example:** ```ts const webStats = await environments.web.getStats(); console.log(webStats.toJson({ all: false })); ``` ``` -------------------------------- ### Create Rsbuild Project with deno Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/start/quick-start.mdx Use deno to create a new Rsbuild project. Follow the prompts to select options like TypeScript and ESLint. ```bash deno init --npm rsbuild@latest ``` -------------------------------- ### Importing a TOML file Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/basic/json-files.mdx Demonstrates importing a TOML file after configuring the TOML plugin and accessing its data. ```toml hello = "world" [foo] bar = "baz" ``` ```js import example from './example.toml'; console.log(example.hello); // 'world'; console.log(example.foo); // { bar: 'baz' }; ``` -------------------------------- ### Add Rsdoctor Plugin Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/debug/rsdoctor.mdx Install the Rsdoctor plugin using your package manager. ```bash npm install @rsdoctor/rspack-plugin -D # or yarn add @rsdoctor/rspack-plugin -D # or pnpm add @rsdoctor/rspack-plugin -D ``` -------------------------------- ### RsbuildPluginAPI Type Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/types.mdx The API interface that Rsbuild exposes to plugins through the setup function. ```APIDOC ## RsbuildPluginAPI Type ### Description 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. ### Code Example ```typescript import type { RsbuildPluginAPI } from '@rsbuild/core'; const myPlugin = { name: 'my-plugin', setup(api: RsbuildPluginAPI) {}, }; ``` ``` -------------------------------- ### Create Rsbuild Project with npm create Source: https://github.com/web-infra-dev/rsbuild/blob/main/packages/create-rsbuild/README.md Use this command to initiate a new Rsbuild project with the latest version of create-rsbuild. ```bash npm create rsbuild@latest ``` -------------------------------- ### Get Transformed HTML Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/api/javascript-api/environment-api.mdx Retrieves the HTML template content after it has been compiled and transformed. ```APIDOC ### getTransformedHtml Get the HTML template content after compilation and transformation. - **Type:** ```ts type GetTransformedHtml = (entryName: string) => Promise; ``` - **Example:** ```ts // 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. ``` -------------------------------- ### Example CSS Module Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/styling/css-modules.mdx A basic CSS Module file defining a class name. ```css .page-header { color: black; } ``` -------------------------------- ### Create Rsbuild Project with bun Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/start/quick-start.mdx Use bun to create a new Rsbuild project. Follow the prompts to select options like TypeScript and ESLint. ```bash bun create rsbuild@latest ``` -------------------------------- ### Define Environment Variables in .env Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/guide/advanced/env-vars.mdx Example of defining environment variables in a .env file. ```shell FOO=hello BAR=1 ``` -------------------------------- ### Configure CSS Extract Loader Options Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/tools/css-extract.mdx Example of how to set `esModule` option for CssExtractRspackLoader. ```typescript export default { tools: { cssExtract: { loaderOptions: { esModule: false, }, }, }, }; ``` -------------------------------- ### Configure CSS Extract Plugin Options Source: https://github.com/web-infra-dev/rsbuild/blob/main/website/docs/en/config/tools/css-extract.mdx Example of how to override the `ignoreOrder` option for CssExtractRspackPlugin. ```typescript export default { tools: { cssExtract: { pluginOptions: { ignoreOrder: false, }, }, }, }; ```