### Example of using compiler.run
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/javascript-api/compiler.mdx
Demonstrates how to use the `compiler.run` method, including handling compiler and module errors, processing build results, and closing the compiler before starting a new compilation.
```javascript
compiler.run((err, stats) => {
// Deal with the compiler errors
handleCompilerError(err);
// Deal with the compilation errors
handleModuleErrors(stats.toJson().errors);
// Deal with the result
handleBuildResult(stats);
// End this compilation
compiler.close((closeErr) => {
// Start a new compilation
compiler.run((err, stats) => {});
});
});
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/web-infra-dev/rspack/blob/main/packages/create-rspack/template-common/README.md
Run this command to install all necessary project dependencies.
```bash
{{ packageManager }} install
```
--------------------------------
### Setup Rspack Binding Build in build.rs
Source: https://github.com/web-infra-dev/rspack/blob/main/crates/rspack_binding_build/README.md
Use `rspack_binding_build::setup()` in your `build.rs` file to configure the build process for Rspack bindings. This example is intended for `build.rs` and is ignored by standard Rust compilation.
```rust
fn main() {
rspack_binding_build::setup();
}
```
--------------------------------
### Original File Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/loader-api/inline-match-resource.mdx
This is an example of an original file before transformation.
```javascript
/* STYLE: body { background: red; } */
console.log('yep');
```
--------------------------------
### Import HTTP Resource Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/blog/announcing-1-3.mdx
Example of importing an HTTP resource using an external URL.
```javascript
import pMap from 'https://esm.sh/p-map';
```
--------------------------------
### Configuration Files for Different Versions
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/plugins/webpack/normal-module-replacement-plugin.mdx
Example configuration files for different application targets (VERSION_A and VERSION_B).
```javascript
export const config = {
title: 'I am version A',
};
```
```javascript
export const config = {
title: 'I am version B',
};
```
--------------------------------
### Install project dependencies
Source: https://github.com/web-infra-dev/rspack/blob/main/website/README.md
Installs all necessary dependencies for the project using pnpm. This command should be run after enabling pnpm.
```bash
pnpm install
```
--------------------------------
### System.register Module Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/config/output.mdx
Example of a System.register module output. This format is used when output.library.type is set to 'system'.
```javascript
System.register([], function (__WEBPACK_DYNAMIC_EXPORT__, __system_context__) {
return {
execute: function () {
// ...
},
};
});
```
--------------------------------
### Install @swc/plugin-styled-components
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/blog/announcing-1-0-alpha.mdx
Install the styled-components SWC plugin as a development dependency.
```bash
npm i @swc/plugin-styled-components -D
```
--------------------------------
### Install Rspack Dev Server
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/cli.mdx
Install the required dependency for the `rspack preview` command using your package manager.
```bash
npm install @rspack/dev-server -D
```
--------------------------------
### EnableLibraryPlugin Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/plugins/webpack/enable-library-plugin.mdx
Instantiate the EnableLibraryPlugin to enable library format bundling for the 'var' library type.
```javascript
new rspack.library.EnableLibraryPlugin('var');
```
--------------------------------
### DotenvPlugin Configuration Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/plugins/webpack/environment-plugin.mdx
This example shows how to configure the third-party `DotenvPlugin` to load environment variables from a `.env` file. It includes options for specifying the path to the `.env` file and enabling safety checks against a `.env.example` file.
```javascript
new Dotenv({
path: './.env', // Path to .env file (this is the default)
safe: true, // load .env.example (defaults to "false" which does not use dotenv-safe)
});
```
--------------------------------
### Install next-rspack
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/tech/next.mdx
Install the `next-rspack` package as a development dependency.
```bash
npm install next-rspack -D
yarn add next-rspack -D
pnpm add next-rspack -D
```
--------------------------------
### Basic Asset Emitted Hook Example
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/hookCases/compiler
This snippet demonstrates a basic setup for the `assetEmitted` hook. It shows how to access the asset content and output path, and how to modify the content before it's emitted. This is useful for tasks like adding headers or transforming asset data.
```javascript
var __webpack_modules__ = ({
402: (function (module) {
module.exports = "This is hook"
}),
});
/************************************************************************/
// The module cache
var __webpack_module_cache__ = {};
// The require function
function __webpack_require__(moduleId) {
// Check if module is in cache
var cachedModule = __webpack_module_cache__[moduleId];
if (cachedModule !== undefined) {
return cachedModule.exports;
}
// Create a new module (and put it into the cache)
var module = (__webpack_module_cache__[moduleId] = {
exports: {}
});
// Execute the module function
__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
// Return the exports of the module
return module.exports;
}
/************************************************************************/
// startup
// Load entry module and return exports
// This entry module is referenced by other modules so it can't be inlined
var __webpack_exports__ = __webpack_require__(402);
```
--------------------------------
### Check Installed Tools
Source: https://github.com/web-infra-dev/rspack/blob/main/xtask/benchmark/README.md
Verify that `cargo-codspeed`, `codspeed`, and `valgrind` are installed and accessible.
```bash
cargo codspeed --version
```
```bash
codspeed --version
```
```bash
valgrind --version
```
--------------------------------
### Start Development Server
Source: https://github.com/web-infra-dev/rspack/blob/main/packages/create-rspack/template-common/README.md
Use this command to start the Rspack development server. The application will be accessible at http://localhost:8080.
```bash
{{ packageManager }} run dev
```
--------------------------------
### Initialize BannerPlugin
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/plugins/webpack/banner-plugin.mdx
Instantiate the BannerPlugin with options. This is the basic setup for the plugin.
```javascript
new rspack.BannerPlugin(options);
```
--------------------------------
### Example: Specifying Manifest File Name
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/plugins/webpack/module-federation-plugin.mdx
Example of how to set a custom file name for the Module Federation manifest and stats files.
```typescript
export default {
// ...
manifest: {
fileName: 'mf.json',
},
};
```
--------------------------------
### Library Export with 'default' Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/config/output.mdx
Example of library code when output.library.export is set to 'default'. The default export is assigned to the library name.
```javascript
// If your library has a default export
var MyLibrary = _entry_return_.default;
```
--------------------------------
### JSONP Library Output Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/config/output.mdx
Example of a JSONP library output. The library name is used to call the callback function with the entry point's return value.
```javascript
MyLibrary(_entry_return_);
```
--------------------------------
### Example of EnvironmentPlugin in use
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/plugins/webpack/environment-plugin.mdx
Demonstrates how `process.env` variables injected by `EnvironmentPlugin` are evaluated in your application code. This example shows conditional logic based on `NODE_ENV` and `DEBUG`.
```javascript
if (process.env.NODE_ENV === 'production') {
console.log('Welcome to production');
}
if (process.env.DEBUG) {
console.log('Debugging output');
}
```
--------------------------------
### Async Two CSS Example
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/builtinCases/plugin-css/multiple-entry/__snapshots__/output.snap.txt
This CSS file also defines background colors for the body, serving as another example for asynchronous loading.
```css
body {
background: yellow;
}
body {
background: blue;
}
```
--------------------------------
### Consuming a Library Exposed as a String
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/config/output.mdx
Example of how to include and use a library that was exposed as a global string variable.
```html
```
--------------------------------
### Install Node.js Dependencies with pnpm
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/contribute/development/building.md
Enable pnpm using corepack and then install Node.js dependencies. Ensure Rust and Node.js are set up as per prerequisites.
```bash
corepack enable
pnpm i
```
--------------------------------
### Install Xcode Command Line Tools
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/contribute/development/profiling.md
Install the necessary Xcode Command Line Tools for using Instruments on macOS. This is a prerequisite for profiling with Xcode Instruments.
```bash
xcode-select --install
```
--------------------------------
### Example AGENTS.md Content
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/start/ai.mdx
An example of the AGENTS.md file content, which provides key project information to AI agents. It includes commands and documentation links.
```markdown
# AGENTS.md
You are an expert in JavaScript, Rspack, 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
- Rspack: https://rspack.rs/llms.txt
```
--------------------------------
### Install NestJS Dependencies
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/tech/nestjs.mdx
Install the necessary NestJS runtime packages using your preferred package manager. This command is a continuation of the Node.js guide dependencies.
```bash
npm install @nestjs/common @nestjs/core @nestjs/platform-express reflect-metadata rxjs
yarn add @nestjs/common @nestjs/core @nestjs/platform-express reflect-metadata rxjs
pnpm add @nestjs/common @nestjs/core @nestjs/platform-express reflect-metadata rxjs
```
--------------------------------
### Build for Production
Source: https://github.com/web-infra-dev/rspack/blob/main/packages/create-rspack/template-common/README.md
Execute this command to create a production-ready build of your application.
```bash
{{ packageManager }} run build
```
--------------------------------
### Get loader options with TypeScript types
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/loader-api/context.mdx
This TypeScript example shows how to define and use specific types for loader options when calling this.getOptions().
```typescript
import type { LoaderContext } from '@rspack/core';
type MyLoaderOptions = {
foo: string;
};
export default function myLoader(
this: LoaderContext,
source: string,
) {
const options = this.getOptions();
console.log(options); // { foo: 'bar' }
return source;
}
```
--------------------------------
### Get loader options from configuration
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/loader-api/context.mdx
Use this.getOptions() to retrieve options passed to the loader in the Rspack configuration. This example shows how to access and log these options.
```javascript
module.exports = function myLoader(source) {
const options = this.getOptions();
console.log(options); // { foo: 'bar' }
return source;
};
```
--------------------------------
### Configure ModuleFederationPluginV1 in Rspack
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/plugins/webpack/module-federation-plugin-v1.mdx
Example of how to integrate the ModuleFederationPluginV1 into your Rspack configuration. This setup requires importing 'rspack' and defining the plugin within the 'plugins' array.
```javascript
import { rspack } from '@rspack/core';
export default {
plugins: [
new rspack.container.ModuleFederationPluginV1({
// options
}),
],
};
```
--------------------------------
### Example of using compiler.watch
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/javascript-api/compiler.mdx
Shows how to initiate file watching using `compiler.watch` with specific options and a handler to process build results after each compilation.
```javascript
const watching = compiler.watch(
{
aggregateTimeout: 300,
poll: undefined,
},
(err, stats) => {
// Deal with the result
handleBuildResult(stats);
},
);
```
--------------------------------
### Resolve server-relative URLs with roots
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/config/resolve.mdx
Configure a list of directories where server-relative URLs (starting with '/') are resolved. This example sets the project root as a resolution directory.
```javascript
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default {
resolve: {
roots: [__dirname],
},
};
```
--------------------------------
### Prepare Benchmark Fixtures
Source: https://github.com/web-infra-dev/rspack/blob/main/xtask/benchmark/README.md
Run this command to prepare benchmark fixtures, including creating a local 'threejs-10x' fixture.
```bash
pnpm run bench:prepare
```
--------------------------------
### Configure Proxy in Rspack Dev Server
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/features/dev-server.mdx
Set up the `devServer.proxy` option to route specific requests to a different server. This example proxies requests starting with `/api` to `http://localhost:3000`.
```javascript
export default {
devServer: {
proxy: [
{
context: ['/api'],
target: 'http://localhost:3000',
changeOrigin: true,
},
],
},
};
```
--------------------------------
### Main Entry Point (main.mjs)
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/esmOutputCases/interop/namespace-import-asset/__snapshots__/esm.snap.txt
This file demonstrates importing the asset module using a namespace import and asserting its presence.
```mjs
import { __webpack_require__ } from "./runtime.mjs";
// ./foo.mjs
import foo_namespaceObject from "./407a5f26e1107499.mjs";
var foo_namespaceObject2 = /*#__PURE__*/__webpack_require__.t(foo_namespaceObject);
// ./index.js
it('should have ns', () => {
expect(foo_namespaceObject2).toBeDefined()
})
export {};
```
--------------------------------
### Async Loader Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/loader-api/writing-loaders.mdx
Use an async loader when performing asynchronous operations. Call `this.async()` to get a callback function, which you then use to return the result, error, source maps, and metadata.
```javascript
module.exports = function (source, map, meta) {
// Get the async callback function
const callback = this.async();
// Perform async operation
someAsyncOperation(source, function (err, result) {
// Handle error case
if (err) return callback(err);
// Return the processing result on success
callback(null, result, map, meta);
});
};
```
--------------------------------
### Main Module (main.mjs)
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/esmOutputCases/namespace/star-export-as-namespace/__snapshots__/esm.snap.txt
This snippet defines the main entry point of the example. It imports from a runtime module and demonstrates how a namespace object is created and populated from another module's exports.
```mjs
import { __webpack_require__ } from "./runtime.mjs";
// NAMESPACE OBJECT: ./foo.js
var foo_namespaceObject = {};
__webpack_require__.r(foo_namespaceObject);
__webpack_require__.d(foo_namespaceObject, {
foo: () => (foo) });
// ./foo.js
const foo = 123
// ./index.js
let index_foo = 234
it('should compile', () => {
expect(foo_namespaceObject).toHaveProperty('foo')
expect(foo).toBe(123)
expect(index_foo).toBe(234)
})
export {};
```
--------------------------------
### Asynchronous Loader Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/zh/api/loader-api/writing-loaders.mdx
An asynchronous loader that uses `this.async()` to get a callback function for handling operations like file I/O or network requests. The callback should be invoked with an error or the processed result.
```javascript
module.exports = function (source, map, meta) {
// 获取异步回调函数
const callback = this.async();
// 执行异步操作
someAsyncOperation(source, function (err, result) {
// 处理错误情况
if (err) return callback(err);
// 成功时返回处理结果
callback(null, result, map, meta);
});
};
```
--------------------------------
### Configure Source Paths with Various Options
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/plugins/rspack/copy-rspack-plugin.mdx
Demonstrates using different types of paths for the `from` option, including relative paths, absolute paths, and glob patterns. It also shows how to construct absolute paths and handle potential backslash issues in glob patterns.
```javascript
import { rspack } from '@rspack/core';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default {
plugins: [
new rspack.CopyRspackPlugin({
patterns: [
// relative path
{ from: 'relative/path/to/file.js' },
{ from: 'relative/path/to/dir' },
// absolute path
{ from: path.resolve(__dirname, 'src', 'file.js') },
{ from: path.resolve(__dirname, 'src', 'dir') },
// glob
{ from: 'dir/**/*' },
// If absolute path is a `glob` we replace backslashes with forward slashes,
// because only forward slashes can be used in the `glob`
{
from: path.posix.join(
path.resolve(__dirname, 'src').replace(/\/g, '/'),
'*.txt',
),
},
],
}),
],
};
```
--------------------------------
### Accessing RawSource from Compiler
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/javascript-api/compiler.mdx
Get the exports of @rspack/core to obtain associated internal objects. This is useful when you cannot directly reference @rspack/core or there are multiple Rspack instances. For example, accessing the sources object in a Rspack plugin.
```javascript
const { RawSource } = compiler.rspack.sources;
const source = new RawSource('console.log("Hello, world!");');
```
--------------------------------
### Consuming Libraries from Object Entry
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/config/output.mdx
Example of how to consume libraries when multiple entry points are defined using an object and the library name is an array.
```html
```
--------------------------------
### Enable React Fast Refresh with SWC Loader
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/tech/react.mdx
Configure Rspack to enable React Fast Refresh by installing the @rspack/plugin-react-refresh and integrating it with the builtin:swc-loader. This setup includes code injection and transformation for live updates.
```js
import { rspack } from '@rspack/core';
import { ReactRefreshRspackPlugin } from '@rspack/plugin-react-refresh';
const isDev = process.env.NODE_ENV === 'development';
export default {
mode: isDev ? 'development' : 'production',
module: {
rules: [
{
test: /\.(?:js|mjs|jsx|ts|tsx)$/,
use: {
loader: 'builtin:swc-loader',
options: {
detectSyntax: 'auto',
jsc: {
transform: {
react: {
development: isDev,
refresh: isDev,
},
},
},
},
},
},
],
},
plugins: [
isDev && new ReactRefreshRspackPlugin(),
isDev && new rspack.HotModuleReplacementPlugin(),
],
};
```
--------------------------------
### foo.mjs - Inline Export Alias Example
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/esmOutputCases/dynamic-import/inline-export-alias/__snapshots__/esm.snap.txt
Defines a function to set a global variable and exports a variable 'x' with two aliases, 'a' and 'b'. This snippet demonstrates the setup for testing inline export alias preservation.
```mjs
// ./foo.js
const call = value => {
globalThis.__inlineExportAlias = value;
};
const x = 1;
call(x);
export { x as a, x as b };
```
--------------------------------
### Main Module with Dynamic Imports
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/treeShakingCases/webpack-inner-graph-switch/__snapshots__/treeshaking.snap.txt
This example illustrates a main entry point that imports modules and utilizes dynamic imports for code splitting.
```js
(self["rspackChunk"] = self["rspackChunk"] || []).push([["main"], {
"./import-module.js"(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.d(__webpack_exports__, {
test: () => (test)
});
/* import */ var _module__rspack_import_0 = __webpack_require__("./module.js");
function test() {
(0,_module__rspack_import_0["default"])({
type: "inline"
});
}
},
"./index.js"(__unused_rspack_module, __unused_rspack_exports, __webpack_require__) {
it("should generate correct code when pure expressions are in dead branches", () => {
(__webpack_require__("./import-module.js")/* .test */.test)();
return Promise.all([Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, "./some-module.js")), __webpack_require__.e(/* import() */ "chunk_js").then(__webpack_require__.bind(__webpack_require__, "./chunk.js"))]);
});
},
"./module.js"(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.d(__webpack_exports__, {
"default": () => (__rspack_default_export)
});
/* import */ var _some_module__rspack_import_0 = __webpack_require__("./some-module.js");
function getType(obj) {
return obj.type;
}
// Local functions
function doSomethingWithBlock(obj) {
return _some_module__rspack_import_0.Block.doSomething(obj);
}
function doSomethingWithInline(obj) {
return _some_module__rspack_import_0.Inline.doSomething(obj);
}
function doSomethingWithDocument(obj) {
return _some_module__rspack_import_0.Document.doSomething(obj);
}
// Exported functions
function doSomething(obj) {
const type = getType(obj);
switch (type) {
case "document":
return doSomethingWithDocument(obj);
case "block":
return doSomethingWithBlock(obj);
case "inline":
return doSomethingWithInline(obj);
default:
throw new Error();
}
}
function useDocument(obj) {
return doSomethingWithDocument(obj);
}
/* export default */ const __rspack_default_export = (doSomething);
},
"./some-module.js"(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
Block: () => (Block),
Document: () => (Document),
Inline: () => (Inline)
});
class Block {
static doSomething() {}
}
class Inline {
static doSomething() {}
}
class Document {
static doSomething() {}
}
},
},function(__webpack_require__) {
var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) }
var __webpack_exports__ = (__webpack_exec__("./index.js"));
}]);
```
--------------------------------
### Pitching Loader Execution Order Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/contribute/architecture/rspack-loader.md
Details the execution flow for a series of loaders, highlighting the order of pitch and normal phases.
```text
```
loader-A(pitch)
loader-B(pitch)
loader-C(pitch)
loader-B(normal)
loader-A(normal)
```
```
--------------------------------
### Create Rspack Project and Initialize npm
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/start/quick-start.mdx
Use these bash commands to create a new project directory, navigate into it, and initialize an npm package.json file.
```bash
mkdir rspack-demo
cd rspack-demo
npm init -y
```
--------------------------------
### Configure `from` Path Options
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/zh/plugins/rspack/copy-rspack-plugin.mdx
Demonstrates various ways to specify the `from` path, including relative paths, absolute paths, and glob patterns. It also shows how to handle absolute paths with glob patterns by ensuring forward slashes.
```javascript
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default {
plugins: [
new rspack.CopyRspackPlugin({
patterns: [
// Relative path
{ from: 'relative/path/to/file.js' },
{ from: 'relative/path/to/dir' },
// Absolute path
{ from: path.resolve(__dirname, 'src', 'file.js') },
{ from: path.resolve(__dirname, 'src', 'dir') },
// glob
{ from: 'dir/**/*' },
// If the absolute path is `glob`, we replace backslashes with forward slashes,
// because only forward slashes can be used for `glob`
{
from: path.posix.join(
path.resolve(__dirname, 'src').replace(/\/g, '/'),
'*.txt',
),
},
],
}),
],
};
```
--------------------------------
### Configure Build Entries for Client and Server Compilers
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/tech/rsc.mdx
Set up entry points for both client and server compilers. A crucial convention is that the client compiler must have an entry with the exact same name as a server entry. This matching entry serves as the root for the client RSC runtime.
```javascript
export default [
{
target: 'web',
entry: {
// A 'main' entry with the same name as the server entry must exist,
// acting as the module graph root node for the client RSC runtime.
main: { import: './src/entry.client.tsx' },
},
},
{
target: 'node',
entry: {
// The server entry name is 'main'
main: { import: './src/entry.rsc.tsx' },
},
},
];
```
--------------------------------
### Install Rsdoctor Rspack Plugin
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/optimization/use-rsdoctor.mdx
Install the Rsdoctor Rspack plugin as a development dependency.
```bash
npm install @rsdoctor/rspack-plugin -D
# or
yarn add @rsdoctor/rspack-plugin -D
# or
pnpm add @rsdoctor/rspack-plugin -D
```
--------------------------------
### Run Rspack Preview Command
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/cli.mdx
Execute the `rspack preview` command to start a local server for your production build output. Ensure you have built your project first using `rspack build`.
```bash
npx rspack preview
```
--------------------------------
### Install @rspack/cli
Source: https://github.com/web-infra-dev/rspack/blob/main/packages/rspack-cli/README.md
Install the @rspack/cli package as a development dependency using your preferred package manager.
```bash
pnpm add -D @rspack/cli
```
```bash
npm install -D @rspack/cli
```
```bash
yarn add -D @rspack/cli
```
--------------------------------
### Emit a file with asset info
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/loader-api/context.mdx
This example demonstrates emitting a file using emitFile and providing additional asset information, such as the source filename.
```javascript
module.exports = function loader(source) {
this.emitFile(
'foo.js',
'console.log("Hello, world!");',
undefined, // no sourcemap
{
sourceFilename: this.resourcePath,
},
);
return source;
};
```
--------------------------------
### JavaScript createRequire Usage Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/config/module-parser.mdx
Example demonstrating how to use `createRequire` imported from the 'module' module in an index.js file.
```javascript
import { createRequire as r } from 'module';
const require = r(import.meta.url);
const value = require('./value.cjs');
```
--------------------------------
### Using Loader Utilities
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/loader-api/context.mdx
Shows how to use utility functions like `contextify`, `absolutify`, and `createHash` provided in the loader context for path manipulation and hashing.
```javascript
module.exports = function (content) {
this.utils.contextify(
this.context,
this.utils.absolutify(this.context, './index.js'),
);
this.utils.absolutify(this.context, this.resourcePath);
const mainHash = this.utils.createHash(
this._compilation.outputOptions.hashFunction,
);
mainHash.update(content);
mainHash.digest('hex');
return content;
};
```
--------------------------------
### Install react-refresh Dependency
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/blog/announcing-0-5.mdx
If you are using `@rspack/plugin-react-refresh` and encounter errors resolving `react-refresh` modules, install it as a development dependency.
```bash
npm install react-refresh --save-dev
# or
yarn add react-refresh --dev
# or
pnpm add react-refresh --save-dev
```
--------------------------------
### Main Entry Point with Dynamic Imports
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/esmOutputCases/dynamic-import/import-cjs/__snapshots__/esm.snap.txt
This snippet serves as the main entry point, demonstrating how to perform dynamic imports and assert the expected values. It uses `import()` and `then` with `__webpack_require__.t` for module loading.
```mjs
import { __webpack_require__ } from "./runtime.mjs";
// ./index.js
it('should support dynamic import', async () => {
const mod = await import("./dynamic.mjs").then(__webpack_require__.t.bind(__webpack_require__, /*! ./dynamic */ "./dynamic.js", 19))
const mod2 = await import("./esm.mjs")
expect(mod.value).toBe(42)
expect(mod2.value).toBe(42)
})
export {};
```
--------------------------------
### Install @rspack/dev-server
Source: https://github.com/web-infra-dev/rspack/blob/main/packages/rspack-cli/README.md
Install the @rspack/dev-server package as a development dependency, which is required for `rspack dev` and `rspack preview` commands.
```bash
pnpm add -D @rspack/dev-server
```
```bash
npm install -D @rspack/dev-server
```
```bash
yarn add -D @rspack/dev-server
```
--------------------------------
### Main Entry Point with Exports and Test
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/esmOutputCases/basic/entry-depends-entry/__snapshots__/esm.snap.txt
This is the main entry point that exports values from other entry points and includes a test case to verify the exports.
```mjs
// ./entry1.js
it('should have all exports', async () => {
const { entry3, entry2 } = await import(/*webpackIgnore: true*/'./main.mjs')
expect(entry2).toBe('entry2')
expect(entry3).toBe('entry3')
})
export { entry2 } from "./entry2.mjs";
export { entry3 } from "./entry3.mjs";
```
--------------------------------
### UMD Named Define Output Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/config/output.mdx
Example of the AMD module definition when output.library.umdNamedDefine is true. The module is named 'MyLibrary'.
```javascript
define('MyLibrary', [], factory);
```
--------------------------------
### Main Entry Point (main.mjs)
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/esmOutputCases/namespace/re-export-namespace-missing-export-no-capture/__snapshots__/esm.snap.txt
This snippet demonstrates the main entry point of the test case. It imports a runtime utility and defines a namespace object for './bar.js'. It then asserts that an inlined export is correct and that a missing property 'foo' on the namespace object is undefined.
```mjs
import { __webpack_require__ } from "./runtime.mjs";
// NAMESPACE OBJECT: ./bar.js
var bar_namespaceObject = {};
__webpack_require__.r(bar_namespaceObject);
// ./bar.js
const x = 123;
// ./index.js
it("should render a missing property from an exported namespace binding without capturing the object", () => {
expect((/* inlined export .x */123)).toBe(123);
expect(bar_namespaceObject.foo).toBeUndefined();
});
export {};
```
--------------------------------
### Install Rspack Node.js Dependencies
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/tech/node.mdx
Install Rspack and necessary helper packages for Node.js development, including webpack-node-externals and run-script-webpack-plugin.
```bash
npm install @rspack/core @rspack/cli @rspack/dev-server webpack-node-externals run-script-webpack-plugin --save-dev
```
--------------------------------
### Create a New Rsbuild Project
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/blog/announcing-2-0.mdx
Use this command to start a new project with Rsbuild, which is powered by Rspack. This is recommended for new users.
```bash
npm create rsbuild@latest
```
--------------------------------
### Main Two CSS Example
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/builtinCases/plugin-css/multiple-entry/__snapshots__/output.snap.txt
This CSS file provides an alternative set of background colors for the body, also for main entry point processing.
```css
body {
background: green;
}
body {
background: red;
}
```
--------------------------------
### Library Export with Path Array Example
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/config/output.mdx
Example of library code when output.library.export is an array. The nested export is assigned to the library name.
```javascript
var MyLibrary = _entry_return_.default.subModule;
```
--------------------------------
### Entry Point with Multiple Modules
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/config/entry.mdx
Configure an entry point to include multiple modules by providing an array of strings. Modules are processed in declaration order, useful for injecting polyfills or setup code before the main application.
```javascript
export default {
entry: {
page: ['./src/pre.js', './src/post.js'],
},
};
```
```javascript
export default {
entry: {
main: ['./src/polyfill.js', './src/index.js'],
},
};
```
--------------------------------
### Main Module with Context Replacement
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/esmOutputCases/dynamic-import/import-context-multi-chunk/__snapshots__/esm.snap.txt
Sets up a context module replacement for dynamically loading modules from './modules/' and a recursive context for dynamic imports.
```mjs
import { __webpack_require__ } from "./runtime.mjs";
__webpack_require__.add({
"./modules lazy recursive ^\.\/.*\.js$ referencedExports: default"
/*!**************************************************************************************************************************!*
!*** ./modules|lazy|/^\.\/.*\.js$|referencedExports: default|groupOptions: {}|namespace object|importPhase: evaluation ***!
**************************************************************************************************************************/
(module, __unused_rspack_exports, __webpack_require__) {
var map = {
"./a.js": [
"./modules/a.js",
[
"shared-chunk",
0,
"a"
]
],
"./b.js": [
"./modules/b.js",
[
"shared-chunk",
0,
"b"
]
]
};
function __rspack_async_context(req) {
if(!__webpack_require__.o(map, req)) {
return Promise.resolve().then(() => {
var e = new Error("Cannot find module '" + req + "'");
e.code = 'MODULE_NOT_FOUND';
throw e;
});
}
var ids = map[req], id = ids[0];
return Promise.all(ids[1].map(function(chunkId) { return __webpack_require__.e(chunkId); })).then(() => (__webpack_require__(id)));
}
__rspack_async_context.keys = () => (Object.keys(map));
__rspack_async_context.id = "./modules lazy recursive ^\.\/.*\.js$ referencedExports: default";
module.exports = __rspack_async_context;
},
"./modules lazy ./modules/*.js"
/*!*******************************************************************!*
!*** ./modules|lazy|nonrecursive|./modules/*.js|namespace object ***!
*******************************************************************/
(module, __unused_rspack_exports, __webpack_require__) {
module.exports = {
"./modules/a.js": function() { return Promise.all(/*! esm */ [__webpack_require__.e("shared-chunk"), __webpack_require__.e(0), __webpack_require__.e("a")]).then(__webpack_require__.bind(__webpack_require__, /*! ./modules/a.js */ "./modules/a.js")); },
"./modules/b.js": function() { return Promise.all(/*! esm */ [__webpack_require__.e("shared-chunk"), __webpack_require__.e(0), __webpack_require__.e("b")]).then(__webpack_require__.bind(__webpack_require__, /*! ./modules/b.js */ "./modules/b.js")); }
};
},
});
// ./index.js
it("should wrap multi chunk context ensure calls", async () => {
const modules = __webpack_require__(/*! ./modules/ */ "./modules lazy ./modules/*.js");
const value = await modules["./modules/a.js"]();
const name = "b";
const dynamicValue = await __webpack_require__(/*! ./modules */ "./modules lazy recursive ^\.\/.*\.js$ referencedExports: default")(`./${name}.js`);
expect(value.default).toBe(42);
expect(dynamicValue.default).toBe(43);
expect(Object.keys(modules).sort()).toEqual([
"./modules/a.js",
"./modules/b.js",
]);
});
export {};
```
--------------------------------
### Install Rspack Dependencies
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/migration/webpack.mdx
Install Rspack core, CLI, and dev-server. `@rspack/cli` and `@rspack/dev-server` are optional if you are not using `webpack-cli` or `webpack-dev-server` respectively.
```bash
npm install @rspack/core @rspack/cli @rspack/dev-server -D
# or
yarn add @rspack/core @rspack/cli @rspack/dev-server -D
# or
pnpm add @rspack/core @rspack/cli @rspack/dev-server -D
```
--------------------------------
### Raw Loader Example (CJS)
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/api/loader-api/writing-loaders.mdx
Configure a loader to process raw binary data by exporting `raw: true`. This allows the loader to receive a `Buffer` object instead of a UTF-8 string, which is useful for handling binary files.
```javascript
// Process binary content
// Here source is a Buffer instance
const processed = someBufferOperation(source);
// Return the processed result
return processed;
};
// Mark as Raw Loader
module.exports.raw = true;
```
--------------------------------
### Install @swc/helpers Dependency
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/blog/announcing-0-5.mdx
When using `externalHelpers: true` with SWC loaders and encountering errors resolving `@swc/helpers`, install it as a project dependency.
```bash
npm install @swc/helpers
# or
yarn add @swc/helpers
# or
pnpm add @swc/helpers
```
--------------------------------
### Configure npm Scripts for Rspack
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/guide/tech/node.mdx
Define scripts in package.json for development (`dev`), production builds (`build`), and starting the application (`start`).
```json
{
"scripts": {
"build": "rspack build",
"dev": "rspack dev",
"start": "node dist/main.js"
}
}
```
--------------------------------
### Import Assets as Bytes (Static and Dynamic)
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/blog/announcing-1-7.mdx
Demonstrates how to import binary assets as Uint8Array using the Import Bytes proposal for both static and dynamic imports. Useful for handling raw binary data.
```js
// Static import
import fileBytes from './file.bin' with { type: 'bytes' };
const decoder = new TextDecoder('utf-8');
const text = decoder.decode(fileBytes);
// Dynamic import
const module = await import('./file.bin', { with: { type: 'bytes' } });
const decoder = new TextDecoder('utf-8');
const text = decoder.decode(module.default);
```
--------------------------------
### Mark Entry as Loaded and Get Module
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/hotCases/sharing/share-plugin/__snapshots__/web/1.snap.txt
Marks a shared module entry as loaded and then retrieves the module using its `get` function.
```javascript
var get = function(entry) {
entry.loaded = 1;
return entry.get()
};
```
--------------------------------
### Example: Disabling Asset Analysis in Manifest
Source: https://github.com/web-infra-dev/rspack/blob/main/website/docs/en/plugins/webpack/module-federation-plugin.mdx
Example of disabling asset analysis for the Module Federation manifest, which omits shared and exposes fields.
```typescript
export default {
// ...
manifest: {
disableAssetsAnalyze: true,
},
};
```
--------------------------------
### Main One CSS Example
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/builtinCases/plugin-css/multiple-entry/__snapshots__/output.snap.txt
This CSS file sets background colors for the body and is intended for main entry point processing.
```css
body {
background: red;
}
body {
background: green;
}
```
--------------------------------
### JavaScript Assertion Examples
Source: https://github.com/web-infra-dev/rspack/blob/main/tests/rspack-test/builtinCases/plugin-javascript/builtins-define/__snapshots__/output.snap.txt
These examples show basic assertion checks in JavaScript using `assert.deepStrictEqual` to verify equality between values and boolean expressions.
```javascript
assert.deepStrictEqual(205 == 205, true);
```
```javascript
assert.deepStrictEqual(207 == 205, false);
```
--------------------------------
### Preview Production Build
Source: https://github.com/web-infra-dev/rspack/blob/main/packages/create-rspack/template-common/README.md
This command allows you to preview the production build locally before deploying.
```bash
{{ packageManager }} run preview
```