Bundler Integrations
local graph
Chapter 5 — Bundler Integrations
Section titled “Chapter 5 — Bundler Integrations”Chapter 5 – Bundler Integrations
Section titled “Chapter 5 – Bundler Integrations”In the modern web development landscape, bundlers like Vite, Webpack, and Rollup are the glue that stitches your JavaScript, CSS, assets—and now, WebAssembly—into optimized deliverables. In this chapter, we’ll show you how to integrate your Rust-Wasm package into each of these workflows, generate and consume TypeScript definitions, and tailor builds for different environments (development, production, or even Node.js). By the end, you’ll treat your Wasm module just like any other npm dependency.
5.1: Using Vite, Webpack, and Rollup
Section titled “5.1: Using Vite, Webpack, and Rollup”Integrating your Rust-Wasm package into a modern bundler ties your WebAssembly code seamlessly into a JavaScript ecosystem. We’ll cover three popular tools—Vite, Webpack, and Rollup—showing you exactly how to configure each, import your Wasm module, and benefit from their dev-server or tree-shaking features.
A. High-Level Integration Flow
Section titled “A. High-Level Integration Flow”plaintext flowchart LR subgraph Build Step A[wasm-pack build] —> B[pkg/ with .wasm + JS] end subgraph Bundler B —> C[Resolve pkg/ via import] C —> D[Transform/Bundle Assets] D —> E[Emit optimized dist/] end subgraph Dev/Serve E —> F[Local Dev Server with HMR] end
---
### B. Vite
Vite shines with instant startup and Hot Module Replacement (HMR).
1. **Install Vite and your Wasm package**
<!-- page: 054 -->
bashnpm init vite@latest my-app -- --template vanillacd my-appnpm installnpm install rust-wasm-demo2. Configure Vite (optional)
Section titled “2. Configure Vite (optional)”Vite already handles ES modules and static assets. If you hit dependency-prebuilding errors, add:
import { defineConfig } from 'vite';
export default defineConfig({ optimizeDeps: { include: ['rust-wasm-demo'] }});3. Import and initialize
Section titled “3. Import and initialize”import init, { greet } from 'rust-wasm-demo';
async function run() { await init(); console.log(greet('Vite'));}
run();4. Develop
Section titled “4. Develop”npm run devVite’s dev server watches for changes in both your JS and the pkg/ folder. Rebuild your Wasm with wasm-pack build --target web --out-dir pkg and Vite will auto-refresh.
Personal Insight:
Section titled “Personal Insight:”When I switched from Create React App to Vite for my Wasm-powered widget, build startup dropped from 20 s to 250 ms—letting me iterate on Rust code and see changes instantly.
<!-- page: 055 -->
# C. Webpack
Webpack offers fine-grained control and a rich plugin ecosystem.
## 1. Install dependencies
bashnpm install --save-dev webpack webpack-cli html-webpack-plugin @wasm-tool/wasm-pack-pluginnpm install rust-wasm-demo2. Create webpack.config.js
Section titled “2. Create webpack.config.js”const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');const WasmPackPlugin = require('@wasm-tool/wasm-pack-plugin');
module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, plugins: [ new HtmlWebpackPlugin({ template: 'src/index.html' }), new WasmPackPlugin({ crateDirectory: path.resolve(__dirname, '../hello_browser'), outDir: path.resolve(__dirname, 'pkg'), outName: 'rust_wasm_demo', }), ], module: { rules: [{ test: /\.wasm$/, type: 'webassembly/async' }], }, experiments: { asyncWebAssembly: true },};3. Use in your code
Section titled “3. Use in your code”import init, { greet } from '../pkg/rust_wasm_demo.js';
(async () => { await init(); console.log(greet('Webpack'));})();<!-- page: 056 -->
# 4. Build & Serve
bashnpx webpack serve --mode developmentnpx webpack --mode productionWebpack compiles your Rust crate on the fly via WasmPackPlugin, bundles the results alongside your JS, and serves with HMR if in dev mode.
Case Study:
Section titled “Case Study:”For a legacy dashboard, adding WasmPackPlugin saved me from juggling manual build scripts. Webpack handled building, bundling, and live-reloading the Wasm in one go, simplifying my CI pipeline drastically.
D. Rollup
Section titled “D. Rollup”Rollup produces lean bundles by default, ideal for small widgets.
1. Install
Section titled “1. Install”npm install --save-dev rollup @rollup/plugin-node-resolve rollup-plugin-wasmnpm install rust-wasm-demo2. Create rollup.config.js
Section titled “2. Create rollup.config.js”import resolve from '@rollup/plugin-node-resolve';import wasm from 'rollup-plugin-wasm';
export default { input: 'src/main.js', output: { dir: 'public', format: 'esm', }, plugins: [ resolve(), wasm({ // set to true to inline small modules as base64 sync: ['rust-wasm-demo'], }), ],};- Import in your entry
import init, { greet } from 'rust-wasm-demo';
init().then(() => { console.log(greet('Rollup'));});- Bundle
npx rollup -cThe plugin loads your Wasm as an ES module and Rollup applies tree-shaking to drop unused exports.
Expert Tip:
Use sync: [] only for very small .wasm modules—otherwise prefer async loading to avoid blocking page execution.
Key Takeaways
Section titled “Key Takeaways”- Vite: Easiest setup, fastest startup, ideal for rapid prototyping.
- Webpack: Most control, plugin-rich, works well in established codebases.
- Rollup: Smallest bundles, tree-shaking-friendly, perfect for embedding.
5.2: TypeScript Declarations & Loader Plugins
Section titled “5.2: TypeScript Declarations & Loader Plugins”Providing TypeScript declarations for your Rust-Wasm package ensures consumers enjoy full IDE autocompletion, type safety, and early error catching. Meanwhile, loader plugins teach your bundler how to handle .wasm files, so everything just works out of the box.
A. Generating and Publishing .d.ts
Section titled “A. Generating and Publishing .d.ts”When you run:
wasm-pack build --target bundler --out-dir pkgby default, wasm-pack emits:
your_crate.js– the JS glueyour_crate_bg.wasm– the Wasm binaryyour_crate.d.ts– TypeScript declarations
These declarations look like:
/* tslint:disable *//* eslint-disable */export function greet(name: string): string;export class Counter { constructor(initial: number); increment(): void; readonly value: number;}To surface them to TypeScript consumers, add to your pkg/package.json:
{ "name": "rust-wasm-demo", "version": "0.1.0", "main": "your_crate.js", "types": "your_crate.d.ts", "files": ["your_crate.js", "your_crate_bg.wasm", "your_crate.d.ts"], "type": "module"}typestells TS where to find declarations.filesrestricts the published files to only what’s needed.
B. Configuring Your TypeScript Project
Section titled “B. Configuring Your TypeScript Project”In your consuming project’s tsconfig.json, ensure:
{ “compilerOptions”: { “module”: “esnext”, “target”: “es2017”, “moduleResolution”: “node”, “esModuleInterop”: true, “allowSyntheticDefaultImports”: true, “skipLibCheck”: true, // avoid third-party mismatch errors “resolveJsonModule”: true } }
skipLibCheckprevents your build from breaking if.d.tscome from different TS versions.allowSyntheticDefaultImportslets you import Wasm packages smoothly when they default-export aninitfunction.
C. Loader Plugins for Bundlers
Section titled “C. Loader Plugins for Bundlers”Vite natively supports .wasm as an asset. When importing:
import init, { greet } from 'rust-wasm-demo';await init();console.log(greet('Vite+TS'));Vite will fetch the .wasm binary at runtime. No extra plugin needed, but ensure your tsconfig.json includes:
{ "compilerOptions": { "resolveJsonModule": true, "allowJs": true }, "include": ["src/**/*.*ts", "pkg/**/*.*d.ts"]}Webpack
Section titled “Webpack”- Add rule in
webpack.config.js:
module.exports = { // ... module: {rules: [ { test: /.wasm/, type: 'webassembly/async' }, { test: /\.ts/, use: ‘ts-loader’, exclude: /node_modules/ } ], resolve: { extensions: [‘.ts’, ‘.js’] }, experiments: { asyncWebAssembly: true } };
- Import in TypeScript (src/index.ts):
import init, { greet } from ‘rust-wasm-demo’;
async function main() { await init(); console.log(greet(‘Webpack+TS’)); } main();
Rollup
- Install plugins:
npm install —save-dev @rollup/plugin-node-resolve rollup-plugin-wasm rollup-plugin-typescript2
rollup.config.js: import resolve from ‘@rollup/plugin-node-resolve’; import wasm from ‘rollup-plugin-wasm’; import typescript from ‘rollup-plugin-typescript2’;
export default { input: ‘src/main.ts’, output: { dir: ‘dist’, format: ‘esm’ }, plugins: [ resolve(), wasm({ sync: [] }), // async loading by default typescript({ tsconfig: ’./tsconfig.json’ }) ] };
D. Case Study: Smoothing Onboarding
Section titled “D. Case Study: Smoothing Onboarding”On a team project, we published a Rust-Wasm utility for image processing. Early adopters hit “cannot find type definitions” errors—because our package.json didn’t point types to the .d.ts. Adding that field and advising them to enable skipLibCheck in TS resolved over a dozen onboarding tickets overnight, reducing friction for frontend engineers.
E. Personal Tips & Gotchas
Section titled “E. Personal Tips & Gotchas”- Keep
.d.tsin sync: Whenever you add or remove exports in Rust, rebuild withwasm-packto regenerate declarations. - Avoid deep imports: Consumers should import only from your package root (e.g.,
import { greet } from 'rust-wasm-demo')—don’t surface internal paths. - Watch for plugin order: In Rollup/Webpack, resolve before wasm plugin to ensure imports are mapped correctly.
- Type-check your declarations: Occasionally open the
.d.tsto verify function signatures match your Rust code.
Summary
Section titled “Summary”wasm-packemits.d.tsautomatically—just configure yourpackage.json.- A well-tuned
tsconfig.jsonand loader rules make TypeScript integration seamless. - Vite needs minimal setup; Webpack and Rollup require explicit loader configurations.
- Thoughtful setup reduces onboarding headaches and elevates developer experience.
5.3: Environment-Specific Builds
Section titled “5.3: Environment-Specific Builds”Different deployment targets—development, production, or even Node.js—have distinct requirements for performance, debugging, and packaging.
A. Development vs. Production
Section titled “A. Development vs. Production”| Aspect | Development | Production |
|---|---|---|
| Wasm Build | wasm-pack build --dev | wasm-pack build --release |
| Optimization | Debug symbols enabled, fast compile | LTO, size-oriented optimizations (opt-level = "z") |
| Source Maps | Enable for easier stepping through Rust in DevTools | Strip to reduce binary size |
| Bundler Mode | npm run dev (unminified, HMR) | npm run build (minified, cache-busted assets) |
flowchart LR A[Source Code] —> B{Environment} B — Dev —> C[wasm-pack build —dev] B — Prod —> D[wasm-pack build —release] C & D —> E[Bundler (mode)] E —> F[Dev server or Production deploy]
1. Development Build
Section titled “1. Development Build”wasm-pack build --dev --target bundler --out-dir pkgnpm run dev # Vite/webpack-dev-server/Rollupwatch- Fast iterations: skips heavy optimizations
- Source maps: automatically available if your bundler is configured to serve them
2. Production Build
Section titled “2. Production Build”wasm-pack build --release --target bundler --out-dir pkg# thennpm run build # Vite/webpack/rollup productionmode- Release optimizations: enables LTO, strip debug info, size-oriented opt-level
- Asset compression: run brotli or gzip on .wasm in your CI pipeline
Personal Insight:
During a major product launch, switching from a default --dev Wasm build to --release with LTO cut our .wasm from 300 KB to 80 KB and eliminated a 200 ms initialization lag that plagued first-visit users.
B. Targeting Node.js and SSR
If you share logic between server and client, or need to run Wasm on the edge, use the Node.js target:
- Build for Node
wasm-pack build --release --target nodejs --out-dir pkg-node- Consume in Node.js
const wasm = require('./pkg-node/your_crate.js');
(async () => { await wasm.default(); console.log(wasm.some_exported_function());})();- Use in SSR frameworks (Next.js, SvelteKit) by importing the Node build in server-only routes.
flowchart TBA[Cargo Project] --> B{wasm-pack build}B -- web --> C[pkg-web/]B -- nodejs --> D[pkg-node/]C --> E[Browser App]D --> F[Node.js Server]Case Study: In an analytics dashboard, we validated user inputs in Rust on both client
and server. Building with --target nodejs let us import the same validation functions in our Express.js API—ensuring consistency and eliminating duplication.
C. Build Pipelines & CI Integration
Section titled “C. Build Pipelines & CI Integration”Automate environment-specific builds in CI (e.g., GitHub Actions):
name: CI
on: [push]
jobs: build: runs-on: ubuntu-latest strategy: matrix: target: [web, nodejs] profile: [dev, release] steps: - uses: actions/checkout@v3 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: stable - name: Add Wasm Target run: rustup target add wasm32-unknown-unknown - name: Install wasm-pack run: cargo install wasm-pack - name: Build Wasm (${{ matrix.target }}, ${{ matrix.profile }}) run: wasm-pack build --target ${{ matrix.target }} --${{ matrix.profile }} --out-dir pkg- ${{ matrix.target }}- ${{ matrix.profile }} - name: Publish Artifacts uses: actions/upload-artifact@v3 with: name: wasm- ${{ matrix.target }}- ${{ matrix.profile }} path: pkg- ${{ matrix.target }}- ${{ matrix.profile }}- Matrix strategy builds all combinations automatically.
- Artifacts can be deployed to npm, a CDN, or reused by downstream jobs.
Key Takeaways
Section titled “Key Takeaways”- Development builds focus on speed and debuggability (
--dev, source maps, HMR). - Production builds optimize size and performance (
--release, LTO, compression). - Dual targets (web vs. nodejs) let you share logic across client and server.
- CI pipelines automate environment-specific builds, ensuring consistency and reducing manual errors.