This example demonstrates the use of experimental.nativeMagicString in Rolldown.
The nativeMagicString option enables a native Rust implementation of MagicString for source map generation and code transformation. This provides significant performance improvements over the JavaScript implementation, especially for large codebases.
- Better Performance: Native Rust implementation is faster than JavaScript
- Background Processing: Source map generation happens asynchronously in a background thread
- Seamless Integration: Works with existing plugins that use the MagicString API
When experimental.nativeMagicString is enabled:
- Rolldown provides a
magicStringobject in themetaparameter of transform hooks - Plugins can use this object to manipulate code (replace, prepend, append, etc.)
- Source maps are automatically generated from the transformations
- The native implementation handles the heavy lifting in a background thread
npm run buildThis will:
- Bundle the source files
- Apply transformations using the native MagicString implementation
- Generate source maps
- Output the bundled code to the
dist/directory
The example includes two plugins demonstrating different use cases:
Demonstrates basic MagicString operations:
- Replace: Changes "Hello" to "Hi" in the code
- Prepend: Adds a comment at the beginning of each file
- Append: Adds a timestamp comment at the end of each file
Demonstrates combining meta.ast and meta.magicString for code transformation:
- Analyzes code structure using the parsed AST (Abstract Syntax Tree) generated by
oxcparser. - Transforms patterns transform
fn(() => import(url))intofn(() => import(url), url)with native magicString - Shows how to:
- Use
meta.astto find specific code patterns - Use
meta.magicStringto modify code at precise locations - Maintain accurate source maps during transformation
- Use
Example transformation in lazy-loader.js:
// Before:
registerLazyModule(() => import('./greet.js'));
// After:
registerLazyModule(() => import('./greet.js'), './greet.js');All transformations maintain accurate source maps thanks to the native MagicString implementation.
export default defineConfig({
experimental: {
nativeMagicString: true, // Enable native Rust implementation
},
output: {
sourcemap: true, // Enable source map generation
},
});