Changing a button label shouldn’t give you enough time to make another cup of coffee. Yet in large frontend applications, even a trivial modification can trigger a surprisingly expensive rebuild.
The problem isn’t always the bundler itself.
Sometimes it’s a Babel plugin processing thousands of files. Sometimes it’s an inefficient caching strategy. In other cases, the development server responds almost instantly, but the browser spends its time fetching hundreds of individual JavaScript modules.
These problems feel similar from a developer’s perspective, but they require different solutions.
Rspack, webpack, and Vite approach frontend tooling differently. Understanding those differences is more useful than comparing isolated build benchmarks.
In this article, we’ll look at how Rspack works internally, how it handles dependencies and chunks, what happens during a webpack migration, and when Vite might be a better choice.
1. What Is Rspack?
Rspack is a Rust-based JavaScript bundler designed to stay compatible with much of the webpack ecosystem while improving compilation performance. Version 2.0 was released in April 2026.
It handles familiar responsibilities:
- Resolving module imports.
- Processing JavaScript, TypeScript, JSX, and CSS.
- Building dependency graphs.
- Splitting applications into chunks.
- Eliminating unused code.
- Minifying production assets.
- Supporting Hot Module Replacement.
- Integrating independently deployed applications through Module Federation.
Unlike webpack, Rspack performs most of its computationally expensive work in native Rust code.
Developers still write configuration files and plugins in JavaScript or TypeScript. There is no need to learn Rust to use it.
This makes Rspack particularly interesting for teams that already have large webpack configurations and want better performance without rebuilding their entire tooling infrastructure.
Does switching to Rspack automatically make everything faster?
Not necessarily.
Public migration reports look impressive: Mews reported cutting dev startup from about three minutes to ten seconds, Alan brought a production build down from 2m10s to 34s, and Yelp saw roughly a 50% reduction in build time.
But in almost every such story, the bundler swap is only one of several changes. Teams also replace babel-loader with SWC, switch from Terser to the built-in minifier, and remove loaders that native features now cover. If you migrate the config “as is” and keep Babel processing every file, a large part of the potential gain stays on the table.
The lesson: the biggest improvement usually comes from optimizing the transformation pipeline, not from changing the bundler alone. And every number above belongs to a specific project. Your results will depend on the dependency graph, loaders, plugins, hardware, and CI configuration.
2. How Rspack Works Internally
Rspack consists of three main layers:
┌──────────────────────────────────────────────┐
│ JavaScript layer (Node.js) │
│ rspack.config.mjs · plugins · loaders (JS) │
└──────────────────────┬───────────────────────┘
│ Node-API
┌──────────────────────▼───────────────────────┐
│ Rust core │
│ resolution · module graph · chunk graph │
│ SWC transforms · optimization · minify │
└──────────────────────┬───────────────────────┘
│ emitted assets
┌──────────────────────▼───────────────────────┐
│ Browser runtime │
│ JS / CSS chunks · chunk loading · HMR │
└──────────────────────────────────────────────┘The JavaScript layer
When you execute:
npx rspack buildNode.js loads your configuration, initializes the compiler, registers plugins, and communicates with the native Rust core through Node-API.
This layer provides the familiar webpack-style configuration interface.
The Rust core
The native core handles module resolution, dependency analysis, chunk generation, optimization, and other compilation tasks.
Independent operations can run across multiple threads. Built-in transformations such as SWC also execute on the native side, reducing the amount of work that has to cross the boundary into JavaScript.
The browser runtime
The browser never runs the Rust compiler.
Instead, it receives the generated JavaScript, CSS, and other assets, along with any runtime code required to load additional chunks and manage modules.
The exact runtime depends on the output format, target environment, and enabled features.
Compiler vs. Compilation
Rspack inherits two important architectural concepts from webpack.
Compiler represents the overall build environment. It owns configuration, plugins, and the compilation lifecycle.
Compilation represents a particular build.
In watch mode, the same compiler can create multiple compilations as files change.
class BuildLoggerPlugin {
apply(compiler) {
const name = 'BuildLoggerPlugin';
compiler.hooks.compile.tap(name, () => {
console.log('Compilation started');
});
compiler.hooks.done.tap(name, stats => {
console.log({
duration: stats.endTime - stats.startTime,
errors: stats.hasErrors(),
warnings: stats.hasWarnings(),
});
});
}
}This distinction matters when writing plugins. Configuration belongs to the compiler, while modules, chunks, diagnostics, and generated assets belong to a particular compilation.
If a plugin needs historical build information, store the relevant values explicitly instead of retaining references to old compilation objects. Holding on to old compilations is a classic source of memory leaks in long-running watch processes.
3. From an Import Statement to a JavaScript Bundle
Consider a small dashboard that displays a support ticket and generates a report when the user clicks a button.
The report is loaded only when requested.
src/
├── main.js
├── ticket.js
└── report.jsFirst, create a shared utility.
src/ticket.js
export function formatTicket(id) {
return `Ticket #${id}`;
}
export function debugTicket(id) {
console.debug('Ticket ID:', id);
}The report module uses that utility.
src/report.js
import { formatTicket } from './ticket.js';
export function generateReport(id) {
return `Report generated for ${formatTicket(id)}`;
}Finally, the application entry point.
src/main.js
import { formatTicket } from './ticket.js';
const ticketId = 42;
const button = document.createElement('button');
const status = document.createElement('p');
button.textContent = `Generate report for ${formatTicket(ticketId)}`;
status.setAttribute('role', 'status');
button.addEventListener('click', async () => {
button.disabled = true;
status.textContent = 'Generating report...';
try {
const { generateReport } = await import(
/* webpackChunkName: "report" */
'./report.js'
);
status.textContent = generateReport(ticketId);
} catch (error) {
console.error(error);
status.textContent = 'Could not load the report. Try again.';
} finally {
button.disabled = false;
}
});
document.body.append(button, status);There are two different types of imports here.
The static import makes ticket.js available when the application starts. The dynamic import creates an asynchronous loading boundary for report.js.
Rspack knows about both dependencies during compilation, but the browser doesn’t need to download the report immediately.
Module resolution
Before processing a module, Rspack needs to locate it.
Relative imports are resolved against the importing file. Package imports use package entry points, exports conditions, aliases, and other resolution settings.
A typical configuration might look like this:
rspack.config.mjs
import { fileURLToPath } from 'node:url';
export default {
resolve: {
extensions: ['.tsx', '.ts', '.jsx', '.js', '.json'],
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
};You can now write:
import { formatTicket } from '@/utils/ticket';instead of:
import { formatTicket } from '../../../utils/ticket';If an import fails, distinguish between resolution and transformation errors.
A missing file or incorrect alias is a resolution problem. A TSX file that reaches the JavaScript parser without being transformed is usually a loader configuration problem.
They may look similar in the terminal, but they occur at different compilation stages, and they are fixed in different parts of the config.
4. ModuleGraph and ChunkGraph
A bundler needs to answer two separate questions:
- Which modules depend on each other?
- Which modules should be delivered together?
Rspack uses different graph structures for these responsibilities.
ModuleGraph (what depends on what) ChunkGraph (what ships together)
main.js ──static──▶ ticket.js ┌─ initial chunk: main ───────┐
│ ▲ │ main.js + ticket.js │
└──import()──▶ report.js └─────────────────────────────┘
│ ┌─ async chunk: report ───────┐
└──static──┘ │ report.js │
└─────────────────────────────┘ModuleGraph
The module graph describes relationships between source modules.
In our example, both main.js and report.js depend on ticket.js. Assuming identical resolution and processing settings, Rspack represents that shared dependency as a single module.
The dynamic import is also part of the graph. Asynchronous loading doesn’t mean the dependency is invisible to the compiler.
ChunkGraph
The chunk graph describes how modules are grouped for delivery.
With a single entry point and automatic shared chunk extraction disabled, our example produces an initial chunk containing the application and its shared utility, plus an asynchronous report chunk.
Because ticket.js is already available in the initial chunk, the report chunk can reuse it.
Changing the source code can change both graphs. For example, replacing:
const { generateReport } = await import('./report.js');with:
import { generateReport } from './report.js';makes the report part of the initial dependency graph. The previous asynchronous loading boundary disappears.
Also, the unused debugTicket export can be removed during production optimization.
This is tree shaking. It removes unused code without necessarily removing the entire module from the dependency graph.
5. Building the Example with Rspack
Create a new project (Rspack 2.0 requires Node.js 20.19+ or 22.12+):
mkdir rspack-dashboard
cd rspack-dashboard
npm init -y
npm install -D @rspack/core @rspack/cli @rspack/dev-serverAdd the three source files from the previous example and create the following configuration.
rspack.config.mjs
import { rspack } from '@rspack/core';
export default {
mode: 'production',
entry: {
main: './src/main.js',
},
output: {
publicPath: '/',
filename: 'js/[name].[contenthash:8].js',
chunkFilename: 'js/[name].[contenthash:8].js',
clean: true,
},
optimization: {
splitChunks: false,
runtimeChunk: false,
},
plugins: [
new rspack.HtmlRspackPlugin({
title: 'Support Dashboard',
}),
],
devServer: {
port: 3000,
hot: true,
},
};Add scripts to package.json:
{
"scripts": {
"dev": "rspack dev --mode development",
"build": "rspack build",
"preview": "rspack preview"
}
}Build the application and serve the result:
npm run build
npm run previewThe output should have a structure similar to this:
dist/
├── index.html
└── js/
├── main.a81c09d2.js
└── report.6f02b413.jsThe hashes are illustrative. Actual filenames depend on the generated content.
Open the browser’s Network panel. Initially, only the main JavaScript file is requested. Click the report button and the browser requests the asynchronous chunk:
Page load
GET /index.html 200 document
GET /js/main.a81c09d2.js 200 script
Click "Generate report"
GET /js/report.6f02b413.js 200 script ← loaded on demandThe runtime constructs the chunk URL, downloads the file, executes the module, and resolves the promise returned by import().
Subsequent clicks reuse the already loaded module within the same page session.
When lazy-loaded chunks fail in production
Suppose the application is deployed under:
https://example.com/portal/In that case, the output configuration may need:
output: {
publicPath: '/portal/',
filename: 'js/[name].[contenthash:8].js',
chunkFilename: 'js/[name].[contenthash:8].js',
}A wrong publicPath can cause an application to load successfully while every lazy-loaded route fails.
Another common problem appears immediately after deployment. A user keeps an old browser tab open, a new release replaces the existing assets, and the old runtime attempts to load a chunk that no longer exists.
Check the failed request before changing your bundler configuration.
| Symptom | Likely cause |
|---|---|
| Incorrect chunk URL | Wrong publicPath |
| 404 after deployment | Previous hashed assets were deleted |
| HTML returned instead of JS | Incorrect SPA fallback |
| Blocked cross-origin request | CDN or CORS configuration |
| Intermittent loading failure | Network or deployment issue |
Keeping previous hashed assets available for a reasonable period and deploying releases atomically prevents many of these failures.
6. Loaders, Plugins, and the Compilation Lifecycle
Loaders transform individual resources. Plugins interact with the compilation lifecycle and can inspect or modify the entire build.
A TypeScript loader transforms TypeScript into JavaScript. A plugin can generate an HTML document, analyze chunks, or enforce a bundle size budget.
Let’s write a plugin that reports the raw and Brotli-compressed sizes of generated JavaScript files.
BundleReportPlugin.mjs
import { brotliCompressSync } from 'node:zlib';
export class BundleReportPlugin {
apply(compiler) {
const name = 'BundleReportPlugin';
const { Compilation, sources } = compiler.rspack;
compiler.hooks.thisCompilation.tap(name, compilation => {
compilation.hooks.processAssets.tap(
{
name,
stage: Compilation.PROCESS_ASSETS_STAGE_REPORT,
},
() => {
const report = compilation
.getAssets()
.filter(({ name }) => name.endsWith('.js'))
.map(({ name, source }) => {
const content = source.buffer();
return {
file: name,
rawBytes: content.length,
brotliBytes: brotliCompressSync(content).length,
};
})
.sort((a, b) => b.rawBytes - a.rawBytes);
compilation.emitAsset(
'bundle-report.json',
new sources.RawSource(JSON.stringify(report, null, 2))
);
}
);
});
}
}Register the plugin:
rspack.config.mjs
import { rspack } from '@rspack/core';
import { BundleReportPlugin } from './BundleReportPlugin.mjs';
export default {
plugins: [new rspack.HtmlRspackPlugin(), new BundleReportPlugin()],
};After compilation, the report might look like this (example values, not measured results):
[
{
"file": "js/main.a81c09d2.js",
"rawBytes": 18420,
"brotliBytes": 6230
},
{
"file": "js/report.6f02b413.js",
"rawBytes": 4210,
"brotliBytes": 1580
}
]The plugin runs at a late asset-processing stage, when the generated files are available.
Using compilation.emitAsset() is important. It integrates the report into the normal output pipeline instead of writing directly to the dist directory. That also lets it work with development servers that serve assets from memory.
Brotli compression here provides an estimate. Actual transfer sizes depend on the server’s compression configuration.
For large applications, run this plugin only in production builds or dedicated analysis jobs. Compressing every asset synchronously during HMR would add unnecessary overhead.
7. TypeScript, React, and SWC
One of the most useful Rspack features is its built-in SWC loader.
SWC is a Rust-based compiler that transforms JavaScript and TypeScript without requiring Babel for standard transformations.
A React application can use the following configuration:
rspack.config.mjs
import { rspack } from '@rspack/core';
export default {
mode: 'development',
entry: './src/main.tsx',
resolve: {
extensions: ['.tsx', '.ts', '.jsx', '.js'],
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: {
loader: 'builtin:swc-loader',
options: {
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
transform: {
react: {
runtime: 'automatic',
},
},
},
},
},
},
],
},
plugins: [
new rspack.HtmlRspackPlugin({
template: './index.html',
}),
],
};In Rspack 2.0, builtin:swc-loader no longer reads .swcrc files, so keep all SWC options in the loader configuration, as shown above.
Install the required dependencies:
npm install react react-dom
npm install -D typescript @types/react @types/react-domCreate the HTML template.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Rspack React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>src/main.tsx
import { useState } from 'react';
import { createRoot } from 'react-dom/client';
function App() {
const [count, setCount] = useState(0);
return (
<main>
<h1>React with Rspack</h1>
<button onClick={() => setCount(count => count + 1)}>
Count: {count}
</button>
</main>
);
}
createRoot(document.getElementById('root')!).render(<App />);The loader removes TypeScript annotations and transforms JSX into JavaScript. Rspack then processes the resulting modules.
SWC does not replace TypeScript type checking
Consider this code:
interface Ticket {
id: number;
title: string;
}
const ticket: Ticket = {
id: '42',
title: 'Update profile',
};SWC will happily transform this file into valid JavaScript despite the incorrect id type.
That’s because transpilation and type checking are different operations. SWC strips types; it doesn’t analyze them.
Create a TypeScript configuration:
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"isolatedModules": true,
"noEmit": true,
"skipLibCheck": true
},
"include": ["src"]
}isolatedModules is important here: it makes TypeScript warn about code that a per-file transpiler like SWC cannot compile correctly, such as re-exporting types without export type.
Then add a separate type-checking command:
{
"scripts": {
"dev": "rspack dev --mode development",
"build": "rspack build --mode production",
"typecheck": "tsc --noEmit",
"build:ci": "npm run typecheck && npm run build"
}
}This keeps the development pipeline fast while preserving type safety in CI.
The same principle applies to Vite and other tools that transpile TypeScript without performing full type analysis.
8. Rspack vs. Rsbuild
Rspack is a bundler. Rsbuild is a higher-level build tool powered by Rspack.
The distinction is similar to the difference between an engine and a complete car.
Rspack gives you direct control over loaders, plugins, compilation hooks, and output configuration. Rsbuild provides sensible defaults and framework integrations.
For a new React application, you probably don’t need to configure every loader yourself.
npx -y create-rsbuild@latest my-app --template react-ts
cd my-app
npm install
npm run devA basic Rsbuild configuration is considerably smaller.
rsbuild.config.ts
import { defineConfig } from '@rsbuild/core';
import { pluginReact } from '@rsbuild/plugin-react';
export default defineConfig({
plugins: [pluginReact()],
server: {
port: 3000,
},
source: {
alias: {
'@': './src',
},
},
});You get React integration, Fast Refresh, TypeScript transpilation, CSS processing, and a development server without maintaining a large configuration file.
| Rspack | Rsbuild | |
|---|---|---|
| What it is | Low-level bundler | Application build tool |
| Best for | Webpack migrations | New frontend applications |
| Extensibility | Custom loaders and plugins | Framework and Rsbuild plugins |
| Compiler access | Direct | Through tools.rspack escape hatch |
| Configuration | Explicit, detailed | Convention-based, minimal |
When comparing development experience, Rsbuild is a more direct competitor to Vite than Rspack itself.
9. Incremental Compilation, Caching, and HMR
Build performance isn’t a single metric.
A development server that starts in one second might take several seconds to display a complex route. Another tool might have a slower initial compilation but deliver subsequent updates almost instantly.
It helps to distinguish four operations:
- Cold startup without an existing cache.
- Warm startup using previously cached results.
- Incremental compilation after a file changes.
- Hot Module Replacement in the browser.
Rspack keeps information from previous compilations and can reuse unaffected work.
The cost of an update depends on where the modified file sits in the dependency graph:
Edit a leaf component Edit a shared module
App App*
├── Header ├── Header*
├── Dashboard ├── Dashboard*
│ └── Button* ← changed │ └── Button*
└── Settings └── Settings*
▲
theme.ts* ← changed, imported everywhere
* = potentially affectedEditing an isolated button component usually affects a small part of the application.
Editing a shared theme, localization utility, or central state management module can invalidate a much larger portion of the graph.
This is one reason architectural decisions influence development performance. A “god module” imported by everything makes every edit expensive, regardless of which bundler you use.
Lazy compilation
Rspack can defer the compilation of dynamically imported modules until they are actually requested.
Imagine an application with several expensive features:
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Analytics = lazy(() => import('./pages/Analytics'));
const Administration = lazy(() => import('./pages/Administration'));
const Editor = lazy(() => import('./pages/Editor'));A developer working on the dashboard may never open the editor or administration panel during a session.
Since Rspack 1.7, lazy compilation of dynamically imported modules is enabled by default for web applications in development. In Rspack 2.x it’s configured with the top-level lazyCompilation option (older versions used experiments.lazyCompilation):
rspack.config.mjs
export default {
lazyCompilation: {
entries: false,
imports: true,
},
};Set lazyCompilation: false to turn it off completely.
The trade-off is that opening a previously uncompiled route for the first time takes a little longer.
Lazy compilation is most useful for large applications with many independent features. For a small application, the difference is barely noticeable.
Custom loaders and dependency tracking
Suppose a custom loader reads a translation dictionary from an external JSON file.
If that file changes, the bundler needs to know that the loader’s previous output is no longer valid.
translation-loader.cjs
const fs = require('node:fs');
const path = require('node:path');
module.exports = function translationLoader(source) {
const dictionaryPath = path.resolve(this.rootContext, 'translations/en.json');
this.addDependency(dictionaryPath);
const dictionary = JSON.parse(fs.readFileSync(dictionaryPath, 'utf8'));
return source.replace(/__TRANSLATION_([A-Z_]+)__/g, (_, key) =>
JSON.stringify(dictionary[key] ?? key)
);
};The important line is:
this.addDependency(dictionaryPath);Without it, the bundler doesn’t know the loader depends on the dictionary and won’t rebuild when it changes in watch mode. Worse, a persistent cache may keep serving the stale result across restarts.
A faster compiler cannot fix an incomplete dependency graph.
10. Code Splitting and Production Performance
A fast build doesn’t guarantee a fast website.
Build performance determines how long developers wait. Bundle size, network requests, parsing, and execution determine how long users wait.
Consider a dashboard containing a QR scanner, a rich text editor, and an analytics section.
There is little reason to include all three features in the initial JavaScript payload.
Route-level code splitting in React
import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import Dashboard from './pages/Dashboard';
const Analytics = lazy(() => import('./pages/Analytics'));
const Editor = lazy(() => import('./pages/Editor'));
const Scanner = lazy(() => import('./pages/Scanner'));
export default function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Dashboard</Link>
<Link to="/analytics">Analytics</Link>
<Link to="/editor">Editor</Link>
<Link to="/scanner">Scanner</Link>
</nav>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/analytics" element={<Analytics />} />
<Route path="/editor" element={<Editor />} />
<Route path="/scanner" element={<Scanner />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}Each lazy route creates an asynchronous loading boundary.
The initial page doesn’t need to download the editor or scanner implementation unless those features are requested.
Here is an illustrative calculation with hypothetical sizes: an application shell of 85 KB, Dashboard 35 KB, Analytics 180 KB, Editor 320 KB, and Scanner 140 KB. Without code splitting, every visitor downloads all 760 KB. With route-level splitting, a direct navigation downloads only the shell plus the current route:
| Direct navigation to | Without splitting | With route-level splitting | Reduction |
|---|---|---|---|
| Dashboard | 760 KB | 120 KB | 84% |
| Analytics | 760 KB | 265 KB | 65% |
| Editor | 760 KB | 405 KB | 47% |
| Scanner | 760 KB | 225 KB | 70% |
Real results depend on shared dependencies and chunk optimization, but the pattern holds: the most-visited route benefits most when heavy features are kept out of it.
Shared chunks
What happens when two lazy routes import the same large library?
Rspack can extract shared dependencies into separate chunks using optimization.splitChunks.
rspack.config.mjs
export default {
optimization: {
splitChunks: {
chunks: 'all',
minSize: 20000,
cacheGroups: {
shared: {
minChunks: 2,
priority: 10,
reuseExistingChunk: true,
},
},
},
},
};This allows eligible modules used by multiple chunks to be extracted and reused.
Avoid putting every dependency into a single vendor bundle without measuring the result.
A large vendor chunk may contain libraries the initial page doesn’t need, defeating the purpose of route-level splitting.
At the other extreme, hundreds of tiny chunks add request scheduling and runtime overhead.
There is no universally optimal chunk size. Measure.
11. Tree Shaking and Side Effects
Tree shaking relies heavily on static module analysis.
Consider a utility module:
formatters.ts
export function formatCurrency(value: number) {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(value);
}
export function formatDate(value: Date) {
return new Intl.DateTimeFormat('en-US').format(value);
}
export function formatPercentage(value: number) {
return `${(value * 100).toFixed(2)}%`;
}If the application imports only:
import { formatCurrency } from './formatters';the unused functions can be removed from the production output.
However, not every module can be safely discarded.
import './global.css';
import './register-components';
import './polyfills';These imports exist specifically for their side effects.
Marking the entire package as side-effect-free can accidentally remove important initialization code:
{
"sideEffects": false
}A safer configuration for a package with known side effects might look like this:
{
"sideEffects": [
"**/*.css",
"**/*.scss",
"./src/polyfills.ts",
"./src/register-components.ts"
]
}The declaration must reflect the actual files consumed by the bundler. For a published library, that usually means referencing generated files in dist, not source files.
Incorrect side effect declarations produce bugs that appear only in optimized production builds: styles disappear, custom elements are never registered, and everything works perfectly in development.
12. CSS Modules, SVGs, and Static Assets
Modern bundlers handle much more than JavaScript.
Rspack supports native CSS processing and asset modules, reducing the need for several traditional webpack loaders (in Rspack 1.x native CSS had to be enabled with experiments.css).
rspack.config.mjs
export default {
module: {
rules: [
{
test: /\.css$/,
type: 'css/auto',
},
{
test: /\.(png|jpg|webp|svg|woff2)$/i,
type: 'asset/resource',
},
],
},
output: {
assetModuleFilename: 'assets/[name].[contenthash:8][ext]',
},
};With css/auto, files ending in .module.css are treated as CSS Modules and everything else as global CSS.
Let’s create a reusable ticket component.
TicketCard.module.css
.card {
display: grid;
gap: 0.75rem;
padding: 1.25rem;
border: 1px solid #dbe2ea;
border-radius: 12px;
background: #fff;
}
.header {
display: flex;
align-items: center;
gap: 0.75rem;
}
.icon {
width: 24px;
height: 24px;
}
.status {
width: fit-content;
padding: 0.25rem 0.75rem;
border-radius: 999px;
color: #166534;
background: #dcfce7;
}TicketCard.tsx
import * as styles from './TicketCard.module.css';
import ticketIcon from './assets/ticket.svg';
interface TicketCardProps {
id: number;
title: string;
status: 'Open' | 'Closed';
}
export function TicketCard({ id, title, status }: TicketCardProps) {
return (
<article className={styles.card}>
<header className={styles.header}>
<img className={styles.icon} src={ticketIcon} alt="" />
<h2>Ticket #{id}</h2>
</header>
<p>{title}</p>
<span className={styles.status}>{status}</span>
</article>
);
}Rspack’s native CSS Modules use named exports by default, which is why the component uses import * as styles rather than a default import.
For TypeScript, add asset declarations if your project doesn’t already provide them.
src/assets.d.ts
declare module '*.module.css' {
const classes: { readonly [key: string]: string };
export = classes;
}
declare module '*.svg' {
const url: string;
export default url;
}The generated CSS uses scoped class names, while the imported SVG resolves to the URL of an emitted asset.
Inline assets vs. separate files
For small images, you can use the asset module type to choose between inline data and emitted files based on size.
{
test: /\.(png|svg|webp)$/i,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 4 * 1024,
},
},
}Assets smaller than 4 KB are embedded directly in the generated output. Larger files are emitted separately.
Inlining removes a network request but increases the size of the containing asset, and the inlined data is re-downloaded every time that asset changes.
Separate files can be cached independently and reused across pages. This is generally preferable for larger images and fonts.
13. Module Federation and Microfrontends
Module Federation allows independently built applications to share modules at runtime.
Imagine an e-commerce administration platform maintained by three teams.
The platform team owns authentication, navigation, and the application shell. Another team maintains order management. A third team develops analytics.
Each team can build and deploy its application independently:
┌──────────────────────────────┐
Browser ────────▶ │ portal (host) :3100 │
│ shell · auth · navigation │
└───────┬───────────────┬──────┘
loads at runtime │ │ loads at runtime
▼ ▼
┌──────────────────────┐ ┌──────────────────────┐
│ orders (remote) │ │ analytics (remote) │
│ :3101/remoteEntry.js │ │ remoteEntry.js │
└──────────────────────┘ └──────────────────────┘
shared singletons: react, react-domThe host doesn’t need to contain the source code of every remote feature at build time. Instead, it loads remote modules when required.
Configuring the remote application
The orders application exposes a React component.
orders/rspack.config.mjs
import { rspack } from '@rspack/core';
export default {
output: {
uniqueName: 'orders',
publicPath: 'auto',
},
devServer: {
port: 3101,
},
plugins: [
new rspack.container.ModuleFederationPlugin({
name: 'orders',
filename: 'remoteEntry.js',
exposes: {
'./OrderList': './src/OrderList.tsx',
},
shared: {
react: { singleton: true },
'react-dom': { singleton: true },
},
}),
],
};orders/src/OrderList.tsx
const orders = [
{ id: 101, customer: 'Alex', total: 149 },
{ id: 102, customer: 'Sarah', total: 89 },
{ id: 103, customer: 'Daniel', total: 230 },
];
export default function OrderList() {
return (
<section>
<h2>Recent orders</h2>
<ul>
{orders.map(order => (
<li key={order.id}>
#{order.id} | {order.customer} | ${order.total}
</li>
))}
</ul>
</section>
);
}Configuring the host application
portal/rspack.config.mjs
import { rspack } from '@rspack/core';
export default {
output: {
uniqueName: 'portal',
publicPath: 'auto',
},
devServer: {
port: 3100,
},
plugins: [
new rspack.container.ModuleFederationPlugin({
name: 'portal',
remotes: {
orders: 'orders@http://localhost:3101/remoteEntry.js',
},
shared: {
react: { singleton: true },
'react-dom': { singleton: true },
},
}),
],
};Both configurations are Federation-specific fragments. They still need the React transformation rules, entry points, and HTML setup shown earlier.
Rspack’s built-in Module Federation plugin relies on the Module Federation runtime package:
npm install @module-federation/runtime-toolsUse an asynchronous bootstrap boundary in the host, so shared dependencies can be negotiated before the application code runs:
portal/src/index.ts
import('./bootstrap');portal/src/bootstrap.tsx
import { createRoot } from 'react-dom/client';
import App from './App';
createRoot(document.getElementById('root')!).render(<App />);The host can now import the remote component.
import { lazy, Suspense } from 'react';
const OrderList = lazy(() => import('orders/OrderList'));
export default function OrdersRoute() {
return (
<Suspense fallback={<p>Loading orders...</p>}>
<OrderList />
</Suspense>
);
}For a basic TypeScript setup, declare the remote module.
declare module 'orders/OrderList' {
import type { ComponentType } from 'react';
const OrderList: ComponentType;
export default OrderList;
}More advanced Federation setups can generate or download remote type declarations automatically.
Handling unavailable remote applications
Microfrontends introduce a failure mode that doesn’t exist in a conventional monolithic frontend: a remote application may be unavailable while the host keeps running.
Suspense handles loading states, not failed module requests. Add an error boundary.
npm install react-error-boundaryimport { lazy, Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
const OrderList = lazy(() => import('orders/OrderList'));
export default function OrdersRoute() {
return (
<ErrorBoundary
fallback={
<section role="alert">
<h2>Orders are temporarily unavailable</h2>
<p>Please reload the page and try again.</p>
<button onClick={() => window.location.reload()}>Reload page</button>
</section>
}
>
<Suspense fallback={<p>Loading orders...</p>}>
<OrderList />
</Suspense>
</ErrorBoundary>
);
}A full reload is used deliberately here: React caches a rejected lazy() import, so resetting the error boundary alone won’t retry the failed module request.
Module Federation solves deployment and ownership problems. It also introduces runtime dependency management, version compatibility, availability, and security concerns.
Remote JavaScript executes inside the host application with the same privileges. Only load code from deployments you trust.
If a single team maintains the entire application and releases everything together, ordinary code splitting is usually enough.
14. How Vite Approaches the Same Problem
Vite takes a different approach to frontend development.
Traditional bundlers build chunks before serving the application. Vite’s development server serves source modules to the browser as native ES modules and transforms them on request.
When the browser encounters:
import { formatTicket } from './utils/ticket';it requests the transformed module directly from the development server.
Vite also pre-bundles dependencies from node_modules to avoid the overhead of hundreds of small files from large libraries.
Bundled dev server (webpack / Rspack) Vite dev server (native ESM)
source ──▶ [ build graph + chunks ] source ──▶ [ transform on request ]
│ ▲ │
▼ request │ ▼
browser gets a few bundles browser asks for each moduleThis architecture provides an excellent development experience for many applications.
However, as the number of modules grows, the browser may need to discover and request a large dependency graph on the first page load.
A server that starts quickly doesn’t necessarily mean the first route renders quickly.
Since Vite 8, released in March 2026, production builds use Rolldown, a Rust-based bundler that replaced the previous combination of esbuild and Rollup. Rolldown keeps compatibility with the Rollup and Vite plugin API, so most existing plugins keep working.
The old framing of “webpack bundles, Vite doesn’t” is becoming less useful. Both camps are converging on native, Rust-based bundling; the real differences are in the development model, the plugin APIs, and the ecosystem.
Creating a Vite application
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run devA typical configuration is small.
vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { fileURLToPath } from 'node:url';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
server: {
port: 3000,
},
build: {
sourcemap: true,
},
});For a conventional React application, this may be all the configuration you need.
Migrating an established webpack application is a different story. Custom loaders, compilation hooks, and webpack-specific plugins have to be replaced or rewritten for the Vite/Rollup plugin API.
15. One API Request, Three Build Tools
A useful way to compare configuration styles is to solve the same everyday problem with each tool.
Suppose your frontend talks to an Express backend running on port 3001. The frontend should call /api/tickets without hardcoding a backend URL.
Express backend
npm install expressserver.mjs
import express from 'express';
const app = express();
app.get('/api/tickets', (req, res) => {
res.json([
{ id: 1, title: 'Update account settings', status: 'open' },
{ id: 2, title: 'Generate monthly report', status: 'closed' },
]);
});
app.listen(3001, () => {
console.log('API running on http://localhost:3001');
});Run the backend:
node server.mjsRspack proxy
rspack.config.mjs
export default {
devServer: {
port: 3000,
proxy: [
{
pathFilter: '/api',
target: 'http://localhost:3001',
},
],
},
};webpack proxy
webpack.config.mjs
export default {
devServer: {
port: 3000,
proxy: [
{
context: ['/api'],
target: 'http://localhost:3001',
},
],
},
};In @rspack/dev-server, context is accepted as an alias of pathFilter, so a copied webpack proxy config keeps working.
Vite proxy
vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
server: {
port: 3000,
proxy: {
'/api': 'http://localhost:3001',
},
},
});Shared frontend code
The application code stays identical regardless of the bundler.
src/api.ts
export interface Ticket {
id: number;
title: string;
status: 'open' | 'closed';
}
export async function loadTickets(signal?: AbortSignal): Promise<Ticket[]> {
const response = await fetch('/api/tickets', { signal });
if (!response.ok) {
throw new Error(`Could not load tickets: HTTP ${response.status}`);
}
return response.json();
}A React component can consume the API while handling loading, cancellation, and errors.
src/TicketList.tsx
import { useEffect, useState } from 'react';
import { loadTickets, type Ticket } from './api';
export function TicketList() {
const [tickets, setTickets] = useState<Ticket[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const controller = new AbortController();
async function fetchTickets() {
try {
const data = await loadTickets(controller.signal);
if (!controller.signal.aborted) {
setTickets(data);
}
} catch (error) {
if (!controller.signal.aborted) {
setError(error instanceof Error ? error.message : 'Unexpected error');
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
fetchTickets();
return () => controller.abort();
}, []);
if (loading) return <p>Loading tickets...</p>;
if (error) return <p role="alert">{error}</p>;
if (tickets.length === 0) {
return <p>No tickets found.</p>;
}
return (
<ul>
{tickets.map(ticket => (
<li key={ticket.id}>
{ticket.title} ({ticket.status})
</li>
))}
</ul>
);
}The AbortController matters in development too: React Strict Mode mounts effects twice, and without cancellation the first request could overwrite state after the component has already re-run the effect.
The browser talks to the frontend’s own origin, and the development server forwards the request to the backend.
In production, this job belongs to your application server, reverse proxy, or hosting platform. Development proxy configuration does not become production routing configuration.
16. Migrating from Webpack to Rspack
A common mistake during migration is replacing the bundler, Babel, CSS loaders, minifiers, and caching configuration all at once.
If the build becomes faster, you won’t know which change produced the improvement. If something breaks, you won’t know which change caused it.
A staged migration is easier to evaluate and to roll back.
Step 1. Establish a baseline
Before touching the existing webpack configuration, collect:
- Cold and warm production build times.
- Development server startup time.
- HMR latency.
- Initial JavaScript and CSS sizes.
- Peak memory consumption.
- Total CI execution time.
- Existing warnings and errors.
Generate a webpack build report:
npx webpack --mode production --json > webpack-stats.jsonKeep this report for comparison.
Step 2. Run both bundlers
Install Rspack alongside webpack.
npm install -D @rspack/core @rspack/cli @rspack/dev-serverKeep the original webpack configuration and introduce a separate Rspack configuration.
{
"scripts": {
"build:webpack": "webpack --mode production",
"build:rspack": "rspack build --mode production",
"dev:webpack": "webpack serve --mode development",
"dev:rspack": "rspack dev --mode development"
}
}Use separate output directories during the pilot so one build doesn’t overwrite the other.
Initially, keep existing loaders and transformations wherever possible. The first goal is functional equivalence, not maximum performance.
Step 3. Replace expensive transformations
An existing webpack configuration might contain:
{
test: /\.[jt]sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-typescript',
],
},
},
}For TypeScript and TSX files, the corresponding native SWC rule looks like this:
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: {
loader: 'builtin:swc-loader',
options: {
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
transform: {
react: {
runtime: 'automatic',
},
},
},
},
},
}For JavaScript and JSX, use a separate rule with the ECMAScript parser.
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'builtin:swc-loader',
options: {
jsc: {
parser: {
syntax: 'ecmascript',
jsx: true,
},
transform: {
react: {
runtime: 'automatic',
},
},
},
},
},
}These rules cover common syntax transformations, but they are not automatic replacements for every Babel configuration.
Check custom Babel plugins, decorators, browser targets, polyfills, and framework-specific transformations before removing Babel.
If a particular transformation is needed by only a handful of files, you can keep Babel for those files and use SWC everywhere else.
Step 4. Review legacy loaders
Some older webpack loaders can be replaced with native functionality.
| Existing configuration | Possible Rspack replacement |
|---|---|
babel-loader | builtin:swc-loader |
file-loader | asset/resource |
url-loader | asset or asset/inline |
raw-loader | asset/source |
MiniCssExtractPlugin | Native CSS or CssExtractRspackPlugin |
TerserPlugin | Built-in SWC minification |
HtmlWebpackPlugin | HtmlRspackPlugin |
These are migration candidates, not guaranteed drop-in replacements.
For example, a project using file-loader with custom naming and public URL logic must preserve that behavior when switching to asset modules.
Step 5. Inspect the resulting bundles
Generate an Rspack statistics report.
npx rspack build --mode production --json stats.jsonCreate a script that distinguishes initial and asynchronous chunks.
inspect-chunks.mjs
import { readFileSync } from 'node:fs';
const stats = JSON.parse(readFileSync('stats.json', 'utf8'));
const chunks = (stats.chunks ?? []).map(chunk => ({
id: chunk.id,
type: chunk.initial ? 'initial' : 'async',
files: (chunk.files ?? []).join(', '),
sizeKB: Number(((chunk.size ?? 0) / 1024).toFixed(2)),
}));
console.table(chunks);
const initialSize = chunks
.filter(chunk => chunk.type === 'initial')
.reduce((total, chunk) => total + chunk.sizeKB, 0);
console.log(`Reported initial chunk size: ${initialSize.toFixed(2)} KB`);Run it:
node inspect-chunks.mjsThe output might resemble:
┌─────────┬────┬───────────┬─────────────────────┬────────┐
│ (index) │ id │ type │ files │ sizeKB │
├─────────┼────┼───────────┼─────────────────────┼────────┤
│ 0 │ 1 │ 'initial' │ 'main.a81c09d2.js' │ 124.5 │
│ 1 │ 2 │ 'async' │ 'report.6f02b413.js'│ 48.2 │
│ 2 │ 3 │ 'async' │ 'editor.7a03f2b1.js'│ 210.4 │
└─────────┴────┴───────────┴─────────────────────┴────────┘The size in chunk statistics is the uncompressed module size, not the actual network transfer size.
For deeper analysis, use Rsdoctor. It helps identify expensive loaders, duplicate dependencies, oversized modules, and unexpected relationships between chunks.
Step 6. Validate production behavior
A successful compilation is not enough.
Test lazy-loaded routes, CSS ordering, source maps, asset URLs, browser compatibility, environment variables, worker scripts, and Module Federation integrations.
Run the existing end-to-end test suite against both builds.
If a critical webpack plugin relies heavily on private compiler internals, migrating it may cost more than the performance gain is worth.
Keeping webpack is a perfectly reasonable outcome of a migration pilot.
17. Benchmarking Build Performance Properly
Comparing a cached Rspack build with an uncached webpack build tells you very little.
Use the same machine, source commit, Node.js version, dependency lockfile, browser targets, and optimization settings.
One convenient benchmarking tool is Hyperfine.
hyperfine --warmup 2 --runs 10 \
"npm run build:webpack" \
"npm run build:rspack"This measures repeated builds after warmup. For cold-build measurements, add a --prepare step that removes the relevant caches before each run.
Measure development performance separately.
| Metric | What it tells you |
|---|---|
| Cold startup | Cost of starting without cached work |
| Warm startup | Effectiveness of persistent caching |
| First route render | Actual initial development experience |
| Leaf component HMR | Speed of ordinary UI edits |
| Shared module HMR | Cost of broad dependency invalidation |
| Production build | Compilation and optimization cost |
| Peak memory | Hardware and CI requirements |
| Initial Brotli size | Approximate initial transfer cost |
| Total CI duration | Impact on release delivery |
Why a faster bundler doesn’t mean an equally faster CI
A 70% reduction in bundling time doesn’t mean a 70% reduction in CI duration. Here’s a worked example with hypothetical numbers, assuming tasks run sequentially:
| Stage | Before | After |
|---|---|---|
| Bundling | 5m 0s | 1m 21s (−73%) |
| Tests, type checking, other jobs | 7m 0s | 7m 0s |
| Total CI | 12m 0s | 8m 21s |
The bundler got 73% faster, but the whole pipeline only got 30% faster, saving 3m 39s per run.
If most of the pipeline is spent running integration tests, installing dependencies, or building containers, bundler optimization will have a relatively small effect on release times.
Measure the bottleneck before investing engineering time in removing it.
18. Rspack vs. Webpack vs. Vite
The following comparison focuses on architectural differences rather than claiming that one tool is always faster.
| Feature | Rspack 2.x | webpack 5 | Vite 8 |
|---|---|---|---|
| Core implementation | Rust | JavaScript | JS dev server + Rust bundler |
| Development model | Bundled | Bundled | Native ESM (unbundled) |
| Production bundler | Rspack | webpack | Rolldown |
| TypeScript | Built-in SWC | Configurable loaders | Built-in transpilation |
| Code splitting | Yes | Yes | Yes |
| Tree shaking | Yes | Yes | Yes |
| CSS Modules | Native support | Via loaders | Built-in |
| HMR | Yes | Yes | Yes |
| Module Federation | Built-in | Built-in | Via plugin |
| Webpack compatibility | High, not complete | Native | Requires migration |
| Plugin API | Webpack-style hooks | Mature hooks API | Vite/Rollup-style hooks |
| Configuration effort | Moderate | Moderate to high | Usually low |
| High-level app tooling | Rsbuild | External integrations | Built in |
| Migration from webpack | Relatively straightforward | Not required | Potentially significant |
Having the same feature doesn’t mean its implementation or configuration is identical across tools.
When to choose Rspack
Rspack is particularly attractive when an existing webpack application has become expensive to compile.
Consider a large React application with hundreds of routes, extensive TypeScript usage, several internal packages, and a mature webpack configuration.
Rewriting that entire setup for Vite might require substantial engineering effort.
Rspack offers a migration path that preserves most of the existing architecture while moving the expensive work into native code.
It is also worth evaluating for microfrontend platforms that already depend on webpack-style Module Federation.
When to stay with webpack
Webpack remains a capable and mature build system.
If your application relies on specialized plugins, unusual compilation stages, or carefully tuned output behavior, replacing webpack may introduce more risk than value.
A stable build that completes in an acceptable amount of time is not necessarily a problem that needs solving.
Webpack is a reasonable choice when compilation isn’t the main bottleneck, or when migration would require maintaining custom compatibility layers.
When to choose Vite
Vite is an excellent starting point for a new frontend application without mandatory webpack integrations.
Its development server, framework templates, straightforward configuration, and production tooling make it a natural fit for conventional React, Vue, Svelte, and TypeScript projects.
For a small SaaS application, internal dashboard, PWA, or standalone frontend, Vite is often the simplest option.
For very large applications, benchmark the first route render, full reloads, and HMR behavior instead of looking only at dev server startup time.
When to choose Rsbuild
Rsbuild deserves consideration alongside Vite when starting a new application.
It combines Rspack’s native bundling with a higher-level, batteries-included developer experience.
If you prefer bundled development, need Rspack-specific capabilities, or expect to integrate with an existing webpack-oriented ecosystem, Rsbuild is a practical choice.
19. A Practical Decision Guide
| Your situation | Suggested starting point |
|---|---|
| Existing webpack app, builds are slow, standard loaders/plugins | Rspack: run a staged migration pilot |
| Existing webpack app with critical custom compiler plugins | Stay on webpack, or pilot Rspack carefully |
| Existing webpack app using Module Federation | Rspack |
| New app, conventional framework setup | Vite or Rsbuild |
| New app that needs Module Federation or webpack-ecosystem plugins | Rsbuild |
| CI is slow, but bundling is a small part of it | Optimize tests and pipeline first, not the bundler |
| No significant bottleneck | Keep what you have |
This guide is intentionally simplified. The final choice should be based on a representative application and actual measurements.
Conclusion
The frontend tooling ecosystem is moving toward native compilation, incremental processing, and increasingly sophisticated caching.
Rspack brings those improvements to much of the webpack ecosystem. Vite provides a streamlined development environment with a modern Rust-based production bundler. Webpack continues to offer extensive control and mature integrations.
None of them can compensate for every architectural problem.
An expensive transformation remains expensive until it is optimized. An unnecessarily large dependency graph still needs to be processed. A poorly designed chunking strategy can make a website slow no matter how quickly its assets were generated.
For existing webpack applications, Rspack is often the most practical migration candidate. For new projects, Vite and Rsbuild deserve serious consideration. For applications built around specialized webpack integrations, keeping the current tooling may be the better engineering decision.
Profile first. Change one thing at a time. Measure the result.
The best build tool is the one that solves your project’s actual problems without introducing unnecessary complexity.
