### Initial Application Structure
Source: https://rolldown.rs/in-depth/manual-code-splitting
Example of a basic React application setup and its resulting bundled output.
```jsx
// index.jsx
import * as ReactDom from 'react-dom';
import App from './App.jsx';
ReactDom.createRoot(document.getElementById('root')).render( );
// App.jsx
import * as React from 'react';
import { Button } from 'ui-lib';
export default function App() {
return alert('Button clicked!')} />;
}
```
```js
// node_modules/react/index.js
'React library code';
// node_modules/ui-lib/index.js
'UI library code';
// node_modules/react-dom/index.js
'ReactDOM library code';
// App.js
function App() {
return alert('Button clicked!')} />;
}
// index.js
ReactDom.createRoot(document.getElementById('root')).render( );
```
--------------------------------
### Create Source Files
Source: https://rolldown.rs/guide/getting-started
Example source files for a basic bundling demonstration.
```js
import { hello } from './hello.js';
hello();
```
```js
export function hello() {
console.log('Hello Rolldown!');
}
```
--------------------------------
### View CLI Help
Source: https://rolldown.rs/guide/getting-started
Display available CLI options and usage examples.
```sh
$ ./node_modules/.bin/rolldown --help
```
--------------------------------
### Target environment configuration examples
Source: https://rolldown.rs/reference/Interface.TransformOptions-1
Examples of valid target environment settings for the target property.
```ts
'es2015'
['es2020', 'chrome58', 'edge16', 'firefox57', 'node12', 'safari11']
```
--------------------------------
### Polyfilling globalThis with intro
Source: https://rolldown.rs/reference/Interface.OutputOptions
Example of using the intro option to inject a globalThis polyfill.
```js
export default {
output: {
intro: `
var globalThis = (function() {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
throw new Error('Unable to locate global object');
})();`,
},
};
```
--------------------------------
### Define ESM importer and CJS importee
Source: https://rolldown.rs/in-depth/bundling-cjs
Example setup demonstrating how default imports behave differently based on the __esModule flag.
```js
import foo from './importee.cjs';
console.log(foo);
```
```js
Object.defineProperty(module.exports, '__esModule', {
value: true,
});
module.exports.default = 'foo';
```
--------------------------------
### Add use strict directive
Source: https://rolldown.rs/reference/Interface.OutputOptions
Example of prepending a string to the bundle output.
```js
export default {
output: {
format: 'cjs',
banner: '"use strict";',
},
};
```
--------------------------------
### Configure manualPureFunctions
Source: https://rolldown.rs/reference/InputOptions.treeshake
Example and default configuration for specifying functions that should be treated as pure.
```js
treeshake: {
manualPureFunctions: ['console.log', 'debug.trace']
}
```
```ts
[]
```
--------------------------------
### TLA bundling transformation example
Source: https://rolldown.rs/in-depth/tla-in-rolldown
Demonstrates how source modules with TLA are transformed into sequential execution after bundling.
```javascript
// main.js
import { bar } from './sync.js';
import { foo1 } from './tla1.js';
import { foo2 } from './tla2.js';
console.log(foo1, foo2, bar);
// tla1.js
export const foo1 = await Promise.resolve('foo1');
// tla2.js
export const foo2 = await Promise.resolve('foo2');
// sync.js
export const bar = 'bar';
```
```javascript
// tla1.js
const foo1 = await Promise.resolve('foo1');
// tla2.js
const foo2 = await Promise.resolve('foo2');
// sync.js
const bar = 'bar';
// main.js
console.log(foo1, foo2, bar);
```
--------------------------------
### trimStart()
Source: https://rolldown.rs/reference/Interface.RolldownMagicString
Trims whitespace or specified characters from the start of the string.
```APIDOC
## trimStart(charType?: string | null)
### Description
Trims whitespace or specified characters from the start of the string.
### Parameters
- **charType** (string | null) - Optional - The characters to trim.
### Returns
- **this** (RolldownMagicString) - Returns the instance for chaining.
```
--------------------------------
### Migrate from Rollup Plugin
Source: https://rolldown.rs/builtin-plugins/replace
Example showing the syntax difference when migrating from @rollup/plugin-replace to Rolldown.
```javascript
// Before (@rollup/plugin-replace)
replace({
values: { __VERSION__: () => getVersion() },
include: ['src/**/*.js'],
});
// After (rolldown)
replacePlugin({
__VERSION__: JSON.stringify(getVersion()),
});
```
--------------------------------
### Example tsconfig.json Structure
Source: https://rolldown.rs/reference/InputOptions.tsconfig
A sample configuration file demonstrating compilerOptions for path mapping and JSX transformation.
```json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"jsx": "react-jsx",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"]
}
}
}
```
--------------------------------
### Configure input entry points
Source: https://rolldown.rs/reference/Interface.InputOptions
Examples of defining single, multiple, or named entry points for the Rolldown bundler.
```js
export default defineConfig({
input: 'src/index.js',
});
```
```js
export default defineConfig({
input: ['src/index.js', 'src/vendor.js'],
});
```
```js
export default defineConfig({
input: {
index: 'src/index.js',
utils: 'src/utils/index.js',
'components/Foo': 'src/components/Foo.js',
},
});
```
--------------------------------
### Configure platform options
Source: https://rolldown.rs/reference/Interface.InputOptions
Examples of setting the platform to browser, node, or neutral to influence module resolution and environment behavior.
```js
export default {
platform: 'browser',
output: {
format: 'esm',
},
};
```
```js
export default {
platform: 'node',
output: {
format: 'cjs',
},
};
```
```js
export default {
platform: 'neutral',
output: {
format: 'esm',
},
};
```
--------------------------------
### Verify Rolldown Installation
Source: https://rolldown.rs/guide/getting-started
Check the installed version of Rolldown via the CLI.
```sh
$ ./node_modules/.bin/rolldown --version
```
--------------------------------
### Define Entry and Shared Modules
Source: https://rolldown.rs/in-depth/automatic-code-splitting
Example source files demonstrating shared dependencies across multiple entry points.
```js
// entry-a.js (included in `input` option)
import 'shared-by-ab.js';
import 'shared-by-abc.js';
console.log(globalThis.value);
// entry-b.js (included in `input` option)
import 'shared-by-ab.js';
import 'shared-by-bc.js';
import 'shared-by-abc.js';
console.log(globalThis.value);
// entry-c.js (included in `input` option)
import 'shared-by-bc.js';
import 'shared-by-abc.js';
console.log(globalThis.value);
// shared-by-ab.js
globalThis.value = globalThis.value || [];
globalThis.value.push('ab');
// shared-by-bc.js
globalThis.value = globalThis.value || [];
globalThis.value.push('bc');
// shared-by-abc.js
globalThis.value = globalThis.value || [];
globalThis.value.push('abc');
```
--------------------------------
### Configure code splitting in Rolldown
Source: https://rolldown.rs/reference/Interface.OutputOptions
Examples demonstrating manual code splitting configurations using groups, priorities, and size constraints.
```js
export default defineConfig({
output: {
codeSplitting: {
minSize: 20000,
groups: [
{
name: 'vendor',
test: /node_modules/,
},
],
},
},
});
```
```js
export default defineConfig({
output: {
codeSplitting: {
groups: [
{
name: 'react-vendor',
test: /node_modules[\\/]react/,
priority: 20,
},
{
name: 'ui-vendor',
test: /node_modules[\\/]antd/,
priority: 15,
},
{
name: 'vendor',
test: /node_modules/,
priority: 10,
},
{
name: 'common',
minShareCount: 2,
minSize: 10000,
priority: 5,
},
],
},
},
});
```
```js
export default defineConfig({
output: {
codeSplitting: {
groups: [
{
name: 'large-libs',
test: /node_modules/,
minSize: 100000, // 100KB
maxSize: 250000, // 250KB
priority: 10,
},
],
},
},
});
```
--------------------------------
### Define project file structure
Source: https://rolldown.rs/glossary/entry-chunk
Example file structure for an application that functions as both a standalone app and a library.
```js
// component.js
export function component() {
return 'Hello World';
}
// render.js
export function render(component) {
console.log(component());
}
// app.js
import { component } from './component.js';
import { render } from './render.js';
render(component);
// lib.js
export { component } from './component.js';
```
--------------------------------
### Export and Import Components
Source: https://rolldown.rs/in-depth/dead-code-elimination
Example exports and imports within the component library.
```js
export { Button } from './components/Button.js';
export { Modal } from './components/Modal.js';
```
```js
import './Button.css';
export function Button(props) {
/* ... */
}
```
--------------------------------
### Configure watch include
Source: https://rolldown.rs/reference/InputOptions.watch
Example of using glob patterns to limit file watching to specific directories.
```js
export default defineConfig({
watch: {
include: 'src/**',
},
})
```
--------------------------------
### Example output structure after code splitting
Source: https://rolldown.rs/in-depth/manual-code-splitting
Demonstrates how the application imports and library chunks appear after applying the code splitting configuration.
```js
import ... from './react-hash0.js';
import ... from './react-dom-hash0.js';
import ... from './ui-lib-hash0.js';
// App.js
function App() {
return alert("Button clicked!")} />;
}
// index.js
ReactDom.createRoot(document.getElementById("root")).render( );
```
```js
"React library code";
export { ... };
```
```js
"ReactDOM library code";
export { ... };
```
```js
"UI library code";
export { ... };
```
--------------------------------
### Define ES Module output format
Source: https://rolldown.rs/reference/Interface.OutputOptions
Example of the bundle structure when output.format is set to 'es'.
```js
function exportedFunction() {
/* ... */
}
let exportedValue = '/* ... */';
export { exportedFunction, exportedValue };
```
--------------------------------
### Set custom context
Source: https://rolldown.rs/reference/InputOptions.context
Example configuration setting the context to globalThis for an IIFE output format.
```js
export default {
context: 'globalThis',
output: {
format: 'iife',
},
};
```
--------------------------------
### Define Build Script in package.json
Source: https://rolldown.rs/apis/cli
Example of setting environment variables within a package.json script definition.
```json
{
"scripts": {
"build": "rolldown -c --environment BUILD:production"
}
}
```
--------------------------------
### Configure external modules with string, regex, array, or function
Source: https://rolldown.rs/reference/Interface.InputOptions
Examples of defining external modules using various pattern types.
```js
export default {
external: 'react',
};
```
```js
export default {
external: /^react\//,
};
```
```js
export default {
external: ['react', 'react-dom', /^lodash/],
};
```
```js
import path from 'node:path';
export default {
external: (id) => {
return !id.startsWith('.') && !path.isAbsolute(id);
},
};
```
--------------------------------
### Dependency graph visualization
Source: https://rolldown.rs/in-depth/automatic-code-splitting
A DOT graph representing the module dependency structure of the singleton precedence example.
```dot
digraph {
bgcolor="transparent";
rankdir=TB;
node [shape=box, style="filled,rounded", fontname="Arial", fontsize=12, margin="0.2,0.1", color="${#3c3c43|#dfdfd6}", fontcolor="${#3c3c43|#dfdfd6}"];
edge [fontname="Arial", fontsize=10, color="${#3c3c43|#dfdfd6}", fontcolor="${#3c3c43|#dfdfd6}"];
compound=true;
subgraph cluster_entry {
label="entry.js chunk";
labeljust="l";
fontname="Arial";
fontsize=11;
fontcolor="${#3c3c43|#dfdfd6}";
style="dashed,rounded";
color="${#d44803|#ff712a}";
entry [label="entry.js", fillcolor="${#fff0e0|#4a2a0a}"];
setup [label="setup.js", fillcolor="${#fff0e0|#4a2a0a}"];
}
subgraph cluster_dyn {
label="dyn-entry.js chunk";
labeljust="l";
fontname="Arial";
fontsize=11;
fontcolor="${#3c3c43|#dfdfd6}";
style="dashed,rounded";
color="${#d44803|#ff712a}";
dyn [label="dyn-entry.js", fillcolor="${#fff0e0|#4a2a0a}"];
}
subgraph cluster_common {
label="common-execution.js chunk";
labeljust="l";
fontname="Arial";
fontsize=11;
fontcolor="${#3c3c43|#dfdfd6}";
style="dashed,rounded";
color="${#0366d6|#58a6ff}";
execution [label="execution.js", fillcolor="${#dbeafe|#1e3a5f}"];
}
entry -> setup [label="import"];
entry -> execution [label="import"];
entry -> dyn [label="import()", style=dashed];
dyn -> execution [label="import"];
}
```
--------------------------------
### Outro Configuration
Source: https://rolldown.rs/reference/Interface.OutputOptions
Demonstrates how outro code can access internal scope variables and provides an example for freezing exports.
```js
// banner is placed here
var MyBundle = (function () {
// intro is placed here
var privateVar = 'internal'; // Only accessible inside IIFE
// ... bundle code ...
// outro is placed here - can access privateVar
console.log(privateVar); // Works!
})();
// footer is placed here (global scope) - cannot access privateVar
```
```js
export default {
output: {
format: 'iife',
name: 'MyLib',
outro: `
// Freeze the exported API to prevent modifications
if (typeof Object.freeze === 'function') {
Object.freeze(exports);
}`,
},
};
```
--------------------------------
### Configure Replace Plugin
Source: https://rolldown.rs/builtin-plugins/replace
Basic setup for the replacePlugin within the Rolldown configuration file.
```javascript
import { defineConfig } from 'rolldown';
import { replacePlugin } from 'rolldown/plugins';
export default defineConfig({
input: 'src/index.js',
output: {
dir: 'dist',
format: 'esm',
},
plugins: [
replacePlugin(
{
'process.env.NODE_ENV': JSON.stringify('production'),
__buildVersion: 15,
},
{
preventAssignment: false,
},
),
],
});
```
--------------------------------
### Define IIFE output format
Source: https://rolldown.rs/reference/Interface.OutputOptions
Example of the bundle structure when output.format is set to 'iife', requiring output.name to be defined.
```js
var MyLibrary = (function () {
function exportedFunction() {
/* ... */
}
let exportedValue = '/* ... */';
return { exportedFunction, exportedValue };
})();
```
--------------------------------
### Define UMD output format
Source: https://rolldown.rs/reference/Interface.OutputOptions
Example of the bundle structure when output.format is set to 'umd', requiring output.name to be defined.
```js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
? factory(exports)
: typeof define === 'function' && define.amd
? define(['exports'], factory)
: ((global = typeof globalThis !== 'undefined' ? globalThis : global || self),
factory((global.myBundle = {})));
})(this, function (exports) {
function exportedFunction() {
/* ... */
}
let exportedValue = '/* ... */';
exports.exportedFunction = exportedFunction;
exports.exportedValue = exportedValue;
});
```
--------------------------------
### Example scenario for missing exports
Source: https://rolldown.rs/reference/Interface.InputOptions
Demonstrates how missing exports are handled in source files and the resulting bundled output when shimming is enabled.
```js
// module-a.js:
export { nonExistent } from './module-b.js';
```
```js
// module-b.js:
// nonExistent is not actually exported here
export const something = 'value';
```
```js
// Bundled output (simplified)
const nonExistent = undefined;
export { nonExistent, something };
```
--------------------------------
### Configure sourcemapIgnoreList
Source: https://rolldown.rs/reference/Interface.OutputOptions
Examples of configuring the sourcemapIgnoreList option using static values for performance or functions for custom logic.
```js
// ✅ Preferred: Use RegExp for better performance
sourcemapIgnoreList: /node_modules/
// ✅ Preferred: Use string pattern for better performance
sourcemapIgnoreList: "vendor"
// ! Use sparingly: Function calls have high overhead
sourcemapIgnoreList: (source, sourcemapPath) => {
return source.includes('node_modules') || source.includes('.min.');
}
```
--------------------------------
### Circular Import Example in Output Code
Source: https://rolldown.rs/in-depth/manual-code-splitting
Demonstrates how manual code splitting can result in circular imports where runtime functions are called before initialization.
```javascript
// first.js
import { __esm, __export, init_second, value$1 as value } from './second.js';
var first_exports = {};
__export(first_exports, { value: () => value$1 });
var value$1;
var init_first = __esm({
'first.js'() {
init_second();
// ...
},
});
export { first_exports, init_first, value$1 as value };
// main.js
import { first_exports, init_first } from './first.js';
import { __esm, init_second, second_exports } from './second.js';
var init_main = __esm({
'main.js'() {
init_first();
init_second();
// ...
},
});
init_main();
// second.js
import { init_first, value } from './first.js';
var __esm = '...';
var __export = '...';
var second_exports = {};
__export(second_exports, { value: () => value$1 });
var value$1;
var init_second = __esm({
'second.js'() {
init_first();
// ...
},
});
export { __esm, __export, init_second, second_exports, value$1 };
```
--------------------------------
### Singleton module precedence example
Source: https://rolldown.rs/in-depth/automatic-code-splitting
Illustrates a scenario where singleton module guarantees override original execution order.
```js
// entry.js (included in `input` option)
import './setup.js';
import './execution.js';
import('./dyn-entry.js');
// setup.js
globalThis.value = 'hello, world';
// execution.js
console.log(globalThis.value);
// dyn-entry.js
import './execution.js';
```
```js
import './common-execution.js';
// setup.js
globalThis.value = 'hello, world';
```
```js
import './common-execution.js';
```
```js
console.log(globalThis.value);
```
--------------------------------
### remove(start, end)
Source: https://rolldown.rs/reference/Interface.RolldownMagicString
Removes the characters between start and end.
```APIDOC
### remove(start: number, end: number) -> this
Removes the content between `start` and `end`.
```
--------------------------------
### relocate(start, end, to)
Source: https://rolldown.rs/reference/Interface.RolldownMagicString
Relocates characters from start to end to the specified position.
```APIDOC
### relocate(start: number, end: number, to: number) -> this
Relocates the characters from `start` to `end` to the `to` position.
```
--------------------------------
### Bundle and Execute
Source: https://rolldown.rs/guide/getting-started
Run the bundler via CLI and execute the resulting bundle.
```sh
$ ./node_modules/.bin/rolldown src/main.js --file bundle.js
```
```sh
$ node bundle.js
```
--------------------------------
### move(start, end, index)
Source: https://rolldown.rs/reference/Interface.RolldownMagicString
Moves the characters from start to end to the specified index. Returns the instance for method chaining.
```APIDOC
### move(start: number, end: number, index: number) -> this
Moves the characters from `start` to `end` to `index`. Returns `this` for method chaining.
```
--------------------------------
### Configure CSS transformation plugins for benchmarking
Source: https://rolldown.rs/in-depth/why-plugin-hook-filter
This diff shows the setup for dynamically generating CSS transformation plugins in a Rolldown configuration file.
```diff
diff --git a/apps/10000/rolldown.config.mjs b/apps/10000/rolldown.config.mjs
--- a/apps/10000/rolldown.config.mjs
+++ b/apps/10000/rolldown.config.mjs
@@ -1,8 +1,25 @@
import { defineConfig } from "rolldown";
-import { minify } from "rollup-plugin-esbuild";
+// import { minify } from "rollup-plugin-esbuild";
const sourceMap = !!process.env.SOURCE_MAP;
const m = !!process.env.MINIFY;
+const transformPluginCount = process.env.PLUGIN_COUNT || 0;
+let transformCssPlugin = Array.from({ length: transformPluginCount }, (_, i) => {
+ let index = i + 1;
+ return {
+ name: `transform-css-${index}`,
+ transform(code, id) {
+ if (id.endsWith(`foo${index}.css`)) {
+ return {
+ code: `.index-${index} {
+ color: red;
+}`,
+ map: null,
+ };
+ }
+ }
+ }
+})
export default defineConfig({
input: {
main: "./src/index.jsx",
@@ -11,13 +28,7 @@ export default defineConfig({
"process.env.NODE_ENV": JSON.stringify("production"),
},
plugins: [
- m
- ? minify({
- minify: true,
- legalComments: "none",
- target: "es2022",
- })
- : null,
+ ...transformCssPlugin,
].filter(Boolean),
profilerNames: !m,
output: {
diff --git a/apps/10000/src/index.css b/apps/10000/src/index.css
deleted file mode 100644
diff --git a/apps/10000/src/index.jsx b/apps/10000/src/index.jsx
--- a/apps/10000/src/index.jsx
+++ b/apps/10000/src/index.jsx
@@ -1,7 +1,16 @@
import React from "react";
import ReactDom from "react-dom/client";
import App1 from "./f0";
-import './index.css'
+import './foo1.css'
+import './foo2.css'
+import './foo3.css'
+import './foo4.css'
+import './foo5.css'
+import './foo6.css'
+import './foo7.css'
+import './foo8.css'
+import './foo9.css'
+import './foo10.css'
ReactDom.createRoot(document.getElementById("root")).render(
```
--------------------------------
### trimLines()
Source: https://rolldown.rs/reference/Interface.RolldownMagicString
Trims newlines from the start and end of the string.
```APIDOC
## trimLines()
### Description
Trims newlines from the start and end of the string.
### Returns
- **this** (RolldownMagicString) - Returns the instance for chaining.
```
--------------------------------
### slice(start?, end?)
Source: https://rolldown.rs/reference/Interface.RolldownMagicString
Returns the content between the specified indices.
```APIDOC
### slice(start?: number | null, end?: number | null) -> string
Returns the content between the specified UTF-16 code unit positions.
```
--------------------------------
### trim(charType?)
Source: https://rolldown.rs/reference/Interface.RolldownMagicString
Trims whitespace or specified characters from the start and end.
```APIDOC
### trim(charType?: string | null) -> this
Trims whitespace or characters defined by `charType` from the start and end of the string.
```
--------------------------------
### Configure plugins in Rolldown
Source: https://rolldown.rs/reference/InputOptions.plugins
Demonstrates how to define plugins, use conditional logic for activation, and group plugins using nested arrays.
```js
import { defineConfig } from 'rolldown'
export default defineConfig({
plugins: [
examplePlugin1(),
// Conditional plugins
process.env.ENV1 && examplePlugin2(),
// Nested plugins arrays are flattened
[examplePlugin3(), examplePlugin4()],
]
})
```
--------------------------------
### Configuring cleanDir with multiple configurations
Source: https://rolldown.rs/reference/Interface.OutputOptions
Shows how to handle directory cleaning when multiple configurations target the same output directory.
```js
export default [
{
input: 'src/index.js',
output: {
dir: 'dist',
cleanDir: true, // Clean on first configuration
},
},
{
input: 'src/other.js',
output: {
dir: 'dist',
// cleanDir defaults to false, so files from first config are preserved
},
},
];
```
--------------------------------
### reset(start, end)
Source: https://rolldown.rs/reference/Interface.RolldownMagicString
Resets the specified range to its original content.
```APIDOC
### reset(start: number, end: number) -> this
Undoes modifications made to the range from `start` to `end`.
```
--------------------------------
### Consumer Import Usage
Source: https://rolldown.rs/in-depth/dead-code-elimination
Example of a consumer importing only the Button component.
```js
import { Button } from 'my-component-lib';
render( );
```
--------------------------------
### Filter IDs by regular expression
Source: https://rolldown.rs/reference/Interface.HookFilter
Matches module IDs starting with 'http'.
```js
{ id: /^http/ }
```
--------------------------------
### Configure configurationFieldConflict warning
Source: https://rolldown.rs/reference/InputOptions.checks
Example showing a conflict between rolldown.config.js and tsconfig.json settings.
```js
export default {
transform: {
jsx: 'preserve',
},
};
```
```json
{
"compilerOptions": {
"jsx": "react"
}
}
```
--------------------------------
### input
Source: https://rolldown.rs/reference/Interface.InputOptions
Defines the entry points for the bundling process. It accepts a single string, an array of strings, or an object mapping names to file paths.
```APIDOC
## input
### Description
Defines entries and location(s) of entry modules for the bundle. Relative paths are resolved based on the `cwd` option.
### Type
`string` | `string[]` | `Record`
### Examples
#### Single entry
```js
export default defineConfig({
input: 'src/index.js',
});
```
#### Multiple entries
```js
export default defineConfig({
input: ['src/index.js', 'src/vendor.js'],
});
```
#### Named multiple entries
```js
export default defineConfig({
input: {
index: 'src/index.js',
utils: 'src/utils/index.js',
'components/Foo': 'src/components/Foo.js',
},
});
```
```
--------------------------------
### renderStart
Source: https://rolldown.rs/reference/Interface.Plugin
The renderStart hook is called at the beginning of the bundle generation or write process.
```APIDOC
## renderStart
### Description
Called initially each time bundle.generate() or bundle.write() is invoked. This hook provides access to output options and input options.
```
--------------------------------
### snip(start, end)
Source: https://rolldown.rs/reference/Interface.RolldownMagicString
Returns a clone with content outside the specified range removed.
```APIDOC
### snip(start: number, end: number) -> BindingMagicString
Returns a new `BindingMagicString` instance containing only the content between `start` and `end`.
```
--------------------------------
### overwrite(start, end, content, options?)
Source: https://rolldown.rs/reference/Interface.RolldownMagicString
Overwrites the specified range with new content.
```APIDOC
### overwrite(start: number, end: number, content: string, options?: BindingOverwriteOptions | null) -> this
Overwrites the content between `start` and `end` with the provided `content` string.
```
--------------------------------
### buildStart
Source: https://rolldown.rs/reference/Interface.FunctionPluginHooks
Called on each rolldown() build, providing access to normalized input options.
```APIDOC
## buildStart
### Description
Called on each rolldown() build. This is the recommended hook to use when you need access to the options passed to rolldown() as it takes the transformations by all options hooks into account.
### Parameters
- **this** (PluginContext) - Required
- **options** (NormalizedInputOptions) - Required
### Returns
- **void**
```
--------------------------------
### Expose and consume plugin APIs
Source: https://rolldown.rs/apis/plugin-api/inter-plugin-communication
Use the api property to expose methods and access them via the plugins array in buildStart.
```js
function parentPlugin() {
return {
name: 'parent',
api: {
//...methods and properties exposed for other plugins
doSomething(...args) {
// do something interesting
},
},
// ...plugin hooks
};
}
function dependentPlugin() {
let parentApi;
return {
name: 'dependent',
buildStart({ plugins }) {
const parentName = 'parent';
const parentPlugin = plugins.find((plugin) => plugin.name === parentName);
if (!parentPlugin) {
// or handle this silently if it is optional
throw new Error(`This plugin depends on the "${parentName}" plugin.`);
}
// now you can access the API methods in subsequent hooks
parentApi = parentPlugin.api;
},
transform(code, id) {
if (thereIsAReasonToDoSomething(id)) {
parentApi.doSomething(id);
}
},
};
}
```
--------------------------------
### Define CommonJS output format
Source: https://rolldown.rs/reference/Interface.OutputOptions
Example of the bundle structure when output.format is set to 'cjs'.
```js
function exportedFunction() {
/* ... */
}
let exportedValue = '/* ... */';
exports.exportedFunction = exportedFunction;
exports.exportedValue = exportedValue;
```
--------------------------------
### build(options: BuildOptions[])
Source: https://rolldown.rs/reference/Function.build
Builds multiple outputs sequentially based on an array of build options.
```APIDOC
## build(options: BuildOptions[])
### Description
Builds multiple outputs sequentially. This function is experimental.
### Parameters
- **options** (BuildOptions[]) - Required - The build options for each output.
### Returns
- **Promise** - A Promise that resolves to the build outputs for each option.
```
--------------------------------
### Example of a Rolldown log code
Source: https://rolldown.rs/reference/Interface.RolldownError
Represents the identifier for a specific log or error type.
```ts
'PLUGIN_ERROR'
```
--------------------------------
### Invalid @__PURE__ Annotation Positions
Source: https://rolldown.rs/in-depth/dead-code-elimination
Examples of incorrect placement that will trigger an INVALID_ANNOTATION warning.
```javascript
// Before a non-call expression
/* @__PURE__ */ globalThis.createElement;
// Before a declaration
/* @__PURE__ */ function foo() {}
// Between an identifier and `=` in a variable declarator
const foo /* @__PURE__ */ = bar();
```
--------------------------------
### Define Rolldown Configuration
Source: https://rolldown.rs/guide/getting-started
Create a configuration file to manage bundling options.
```js
import { defineConfig } from 'rolldown';
export default defineConfig({
input: 'src/main.js',
output: {
file: 'bundle.js',
},
});
```
--------------------------------
### Define entry and dependency modules
Source: https://rolldown.rs/in-depth/manual-code-splitting
Initial module structure for entry.js, a.js, and b.js before manual splitting.
```js
// entry.js
import { value } from './a.js';
console.log(value);
export const foo = 'foo';
// a.js
import { value as valueB } from './b.js';
export const value = 'a' + valueB;
// b.js
export const value = 'b';
```
--------------------------------
### Configure external with recommended patterns
Source: https://rolldown.rs/reference/InputOptions.external
Demonstrates portable ways to define external modules by avoiding absolute paths containing node_modules.
```js
export default {
// Exact package names
external: ['vue', 'react', 'react-dom'],
// Package name patterns
external: [/^vue/, /^react/, /^@mui/],
// All bare module IDs (not starting with `.` or `/` or `C:\`)
external: /^[^./](?!:[/\])/,
};
```
--------------------------------
### Configure static group name
Source: https://rolldown.rs/reference/TypeAlias.CodeSplittingGroup
Example of defining a static name for a code splitting group.
```js
import { defineConfig } from 'rolldown';
export default defineConfig({
output: {
codeSplitting: {
groups: [
{
name: 'libs',
test: /node_modules/,
},
],
},
},
});
```
--------------------------------
### Configure importIsUndefined check
Source: https://rolldown.rs/reference/InputOptions.checks
Example showing an import of a non-existent variable which triggers an undefined warning.
```js
import * as utils from './utils.js'; // 'nonExistent' is not exported
console.log(utils.nonExistent); // Always undefined
```
```js
export const helper = () => 'help';
```
--------------------------------
### visit(program: Program)
Source: https://rolldown.rs/reference/Class.Visitor
Initiates the traversal of the provided AST program using the handlers defined in the Visitor instance.
```APIDOC
## visit()
### Description
Traverses the AST starting from the provided program node. This method is experimental.
### Parameters
- **program** (Program) - Required - The root node of the AST to traverse.
### Returns
- **void**
```
--------------------------------
### Example of a Rolldown error message
Source: https://rolldown.rs/reference/Interface.RolldownError
Provides a descriptive string explaining the nature of the error encountered.
```ts
'The "transform" hook used by the output plugin "rolldown-plugin-foo" is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.'
```
--------------------------------
### Import-then-export patterns
Source: https://rolldown.rs/in-depth/lazy-barrel-optimization
Demonstrates manual import and export sequences that are functionally equivalent to direct re-exports.
```js
// Equivalent to `export { a } from './a'`
import { a } from './a';
export { a };
// Equivalent to `export { a as default } from './a'`
import { a } from './a';
export { a as default };
// Equivalent to `export * as ns from './module'`
import * as ns from './module';
export { ns };
// Equivalent to `export { default as b } from './b'`
import b from './b';
export { b };
```
--------------------------------
### Configure watch exclude
Source: https://rolldown.rs/reference/InputOptions.watch
Example of using glob patterns to exclude directories from the file watcher.
```js
export default defineConfig({
watch: {
exclude: 'node_modules/**',
},
})
```
--------------------------------
### Visualize TLA bundling behavior
Source: https://rolldown.rs/in-depth/tla-in-rolldown
A DOT graph illustrating the transition from concurrent execution before bundling to sequential execution after bundling.
```dot
digraph {
bgcolor="transparent";
rankdir=LR;
node [shape=box, style="filled,rounded", fontname="Arial", fontsize=12, margin="0.2,0.1", color="${#3c3c43|#dfdfd6}", fontcolor="${#3c3c43|#dfdfd6}"];
edge [fontname="Arial", fontsize=10, color="${#3c3c43|#dfdfd6}", fontcolor="${#3c3c43|#dfdfd6}"];
compound=true;
subgraph cluster_before {
label="Before bundling (concurrent)";
labeljust="l";
fontname="Arial";
fontsize=12;
fontcolor="${#3c3c43|#dfdfd6}";
style="dashed,rounded";
color="${#22863a|#3fb950}";
b_main [label="main.js\nimport tla1, tla2", fillcolor="${#fff0e0|#4a2a0a}"];
b_all [label="Promise.all([\n tla1,\n tla2\n])", fillcolor="${#dcfce7|#14532d}"];
b_tla1 [label="tla1.js\nawait ...", fillcolor="${#dbeafe|#1e3a5f}"];
b_tla2 [label="tla2.js\nawait ...", fillcolor="${#dbeafe|#1e3a5f}"];
b_done [label="both resolved", fillcolor="${#dcfce7|#14532d}"];
b_main -> b_all;
b_all -> b_tla1;
b_all -> b_tla2;
b_tla1 -> b_done;
b_tla2 -> b_done;
}
subgraph cluster_after {
label="After bundling (sequential)";
labeljust="l";
fontname="Arial";
fontsize=12;
fontcolor="${#3c3c43|#dfdfd6}";
style="dashed,rounded";
color="${#d44803|#ff712a}";
a_tla1 [label="await tla1", fillcolor="${#dbeafe|#1e3a5f}"];
a_tla2 [label="await tla2", fillcolor="${#dbeafe|#1e3a5f}"];
a_main [label="console.log(\n foo1, foo2\n)", fillcolor="${#fff0e0|#4a2a0a}"];
a_tla1 -> a_tla2 [label="then"];
a_tla2 -> a_main [label="then"];
}
}
```
--------------------------------
### Using the Concise Build API
Source: https://rolldown.rs/guide/getting-started
Utilizes the build function for a simplified interface that writes bundles to disk by default.
```js
import { build } from 'rolldown';
// build writes to disk by default
await build({
input: 'src/main.js',
output: {
file: 'bundle.js',
},
});
```
--------------------------------
### CommonJS tree-shaking example
Source: https://rolldown.rs/reference/InputOptions.treeshake
Demonstrates how enabling commonjs tree-shaking affects the inclusion of exports in the final bundle.
```js
// source.js (CommonJS)
exports.used = 'This will be kept';
exports.unused = 'This will be tree-shaken away';
// main.js
import { used } from './source.js';
// With commonjs: true, only the 'used' export is included in the bundle
// With commonjs: false, both exports are included
```
--------------------------------
### mkdir and rmdir
Source: https://rolldown.rs/reference/Interface.RolldownFsModule
Creates or removes directories.
```APIDOC
### mkdir(path, options?) / rmdir(path, options?)
Creates or removes a directory.
- **path** (string): The directory path.
- **options** (object, optional): Configuration for recursive operations or mode.
```
--------------------------------
### Intro placement in bundle
Source: https://rolldown.rs/reference/Interface.OutputOptions
Visual representation of where the intro string is injected within the bundle wrapper.
```js
// banner is placed here, outside the IIFE (global scope)
var MyBundle = (function () {
// intro is placed here, inside the IIFE (local scope)
var __DEV__ = true; // This won't leak to global scope
// ... bundle code ...
// outro is placed here
})();
// footer is placed here
```
--------------------------------
### Example of Automatic Code Splitting
Source: https://rolldown.rs/in-depth/automatic-code-splitting
Demonstrates how static imports and dynamic imports result in separate chunks.
```javascript
// entry.js (included in `input` option)
import foo from './foo.js';
import('./dyn-entry.js');
// dyn-entry.js
require('./bar.js');
// foo.js
export default 'foo';
// bar.js
module.exports = 'bar';
```
--------------------------------
### Benchmark performance results without filters
Source: https://rolldown.rs/in-depth/why-plugin-hook-filter
Displays the build time benchmarks for varying plugin counts, demonstrating the linear performance degradation.
```bash
Benchmark 1: PLUGIN_COUNT=0 node --run build:rolldown
Time (mean ± σ): 745.6 ms ± 11.8 ms [User: 2298.0 ms, System: 1161.3 ms]
Range (min … max): 732.1 ms … 753.6 ms 3 runs
Benchmark 2: PLUGIN_COUNT=1 node --run build:rolldown
Time (mean ± σ): 862.6 ms ± 61.3 ms [User: 2714.1 ms, System: 1192.6 ms]
Range (min … max): 808.3 ms … 929.2 ms 3 runs
Benchmark 3: PLUGIN_COUNT=2 node --run build:rolldown
Time (mean ± σ): 1.106 s ± 0.020 s [User: 3.287 s, System: 1.382 s]
Range (min … max): 1.091 s … 1.130 s 3 runs
Benchmark 4: PLUGIN_COUNT=5 node --run build:rolldown
Time (mean ± σ): 1.848 s ± 0.022 s [User: 4.398 s, System: 1.728 s]
Range (min … max): 1.825 s … 1.869 s 3 runs
Benchmark 5: PLUGIN_COUNT=10 node --run build:rolldown
Time (mean ± σ): 2.792 s ± 0.065 s [User: 6.013 s, System: 2.198 s]
Range (min … max): 2.722 s … 2.850 s 3 runs
Summary
'PLUGIN_COUNT=0 node --run build:rolldown' ran
1.16 ± 0.08 times faster than 'PLUGIN_COUNT=1 node --run build:rolldown'
1.48 ± 0.04 times faster than 'PLUGIN_COUNT=2 node --run build:rolldown'
2.48 ± 0.05 times faster than 'PLUGIN_COUNT=5 node --run build:rolldown'
3.74 ± 0.10 times faster than 'PLUGIN_COUNT=10 node --run build:rolldown'
```
--------------------------------
### Configure package.json Build Script
Source: https://rolldown.rs/guide/getting-started
Define a build script in package.json to simplify the bundling command.
```json
{
"name": "my-rolldown-project",
"type": "module",
"scripts": {
"build": "rolldown src/main.js --file bundle.js"
},
"devDependencies": {
"rolldown": "^1.0.0"
}
}
```
--------------------------------
### Basic usage of replacePlugin
Source: https://rolldown.rs/reference/Function.replacePlugin
Demonstrates the standard implementation of replacePlugin by passing a record of key-value pairs for string replacement.
```js
replacePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
__buildVersion: 15
})
```
--------------------------------
### InputOptions.checks
Source: https://rolldown.rs/reference/InputOptions.checks
Configuration object for build-time warning settings.
```APIDOC
## InputOptions.checks
### Description
Controls which warnings are emitted during the build process. Each property can be set to true to enable the warning or false to suppress it.
### Properties
- **cannotCallNamespace** (boolean) - Optional - Whether to emit warnings when a namespace is called as a function. Default: true.
- **circularDependency** (boolean) - Optional - Whether to emit warnings when detecting circular dependencies. Default: false.
- **commonJsVariableInEsm** (boolean) - Optional - Whether to emit warnings when a CommonJS variable (like module or exports) is used in an ES module. Default: true.
```
--------------------------------
### Bundle code with build()
Source: https://rolldown.rs/apis/bundler-api
A simplified, experimental API similar to esbuild that handles bundling and writing in one call.
```js
import { build } from 'rolldown';
const result = await build({
input: 'src/main.js',
output: {
file: 'bundle.js',
},
});
console.log(result);
```
--------------------------------
### Add shebang to CLI entry point
Source: https://rolldown.rs/reference/Interface.OutputOptions
Example of using a function to conditionally prepend a shebang to a specific chunk.
```js
export default {
output: {
banner: (chunk) => {
// Add shebang only to the CLI entry point
if (chunk.name === 'cli') {
return '#!/usr/bin/env node';
}
return '';
},
},
};
```
--------------------------------
### Dynamically configure entry points with globbing
Source: https://rolldown.rs/reference/InputOptions.input
Uses the tinyglobby package to dynamically map a set of files as entry points while maintaining structure.
```js
import { defineConfig } from 'rolldown';
import { globSync } from 'tinyglobby';
import path from 'node:path';
export default defineConfig({
input: Object.fromEntries(
globSync('src/**/*.js').map((file) => [
// This removes `src/` as well as the file extension from each
// file, so e.g. src/nested/foo.js becomes nested/foo, and
// normalizes Windows backslashes to forward slashes.
path
.relative('src', file.slice(0, file.length - path.extname(file).length))
.split(path.sep)
.join('/'),
// This expands the relative paths to absolute paths, so e.g.
// src/nested/foo.js becomes /project/src/nested/foo.js
path.resolve(file),
]),
),
output: {
dir: 'dist',
format: 'esm',
},
});
```
--------------------------------
### Configure filenameConflict warning
Source: https://rolldown.rs/reference/InputOptions.checks
Example configuration that triggers a filenameConflict warning due to identical entry file names.
```js
export default {
input: ['src/entry1.js', 'src/entry2.js'],
output: {
// Both entries will try to use the same filename
entryFileNames: 'bundle.js',
},
};
```
--------------------------------
### Example scenario for missing exports
Source: https://rolldown.rs/reference/InputOptions.shimMissingExports
Demonstrates a scenario where a module attempts to export a non-existent member from another module.
```js
export { nonExistent } from './module-b.js';
```
```js
// nonExistent is not actually exported here
export const something = 'value';
```