Skip to content
ImagineWorld

Bundler Integrations

node_idnode-book_rust-wasm-fusion_chapter-05-bundler-integrations
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleBundler Integrations
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

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.


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.


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 -->
bash
npm init vite@latest my-app -- --template vanilla
cd my-app
npm install
npm install rust-wasm-demo

Vite already handles ES modules and static assets. If you hit dependency-prebuilding errors, add:

vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
optimizeDeps: {
include: ['rust-wasm-demo']
}
});
src/main.js
import init, { greet } from 'rust-wasm-demo';
async function run() {
await init();
console.log(greet('Vite'));
}
run();
Terminal window
npm run dev

Vite’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.

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
bash
npm install --save-dev webpack webpack-cli html-webpack-plugin @wasm-tool/wasm-pack-plugin
npm install rust-wasm-demo
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 },
};
src/index.js
import init, { greet } from '../pkg/rust_wasm_demo.js';
(async () => {
await init();
console.log(greet('Webpack'));
})();
<!-- page: 056 -->
# 4. Build & Serve
bash
npx webpack serve --mode development
npx webpack --mode production

Webpack compiles your Rust crate on the fly via WasmPackPlugin, bundles the results alongside your JS, and serves with HMR if in dev mode.

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.


Rollup produces lean bundles by default, ideal for small widgets.

Terminal window
npm install --save-dev rollup @rollup/plugin-node-resolve rollup-plugin-wasm
npm install rust-wasm-demo
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'],
}),
],
};
  1. Import in your entry
src/main.js
import init, { greet } from 'rust-wasm-demo';
init().then(() => {
console.log(greet('Rollup'));
});
  1. Bundle
Terminal window
npx rollup -c

The 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.


  • 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.

When you run:

Terminal window
wasm-pack build --target bundler --out-dir pkg

by default, wasm-pack emits:

  • your_crate.js – the JS glue
  • your_crate_bg.wasm – the Wasm binary
  • your_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"
}
  • types tells TS where to find declarations.
  • files restricts the published files to only what’s needed.

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 } }

  • skipLibCheck prevents your build from breaking if .d.ts come from different TS versions.
  • allowSyntheticDefaultImports lets you import Wasm packages smoothly when they default-export an init function.

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"]
}
  1. 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 } };

  1. 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

  1. 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’ }) ] };

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.


  • Keep .d.ts in sync: Whenever you add or remove exports in Rust, rebuild with wasm-pack to 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.ts to verify function signatures match your Rust code.

  • wasm-pack emits .d.ts automatically—just configure your package.json.
  • A well-tuned tsconfig.json and 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.

Different deployment targets—development, production, or even Node.js—have distinct requirements for performance, debugging, and packaging.


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]


Terminal window
wasm-pack build --dev --target bundler --out-dir pkg
npm run dev # Vite/webpack-dev-server/Rollup
watch
  • Fast iterations: skips heavy optimizations
  • Source maps: automatically available if your bundler is configured to serve them

Terminal window
wasm-pack build --release --target bundler --out-dir pkg
# then
npm run build # Vite/webpack/rollup production
mode
  • 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:

  1. Build for Node
Terminal window
wasm-pack build --release --target nodejs --out-dir pkg-node
  1. Consume in Node.js
server.js
const wasm = require('./pkg-node/your_crate.js');
(async () => {
await wasm.default();
console.log(wasm.some_exported_function());
})();
  1. Use in SSR frameworks (Next.js, SvelteKit) by importing the Node build in server-only routes.
flowchart TB
A[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.


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.
  1. Development builds focus on speed and debuggability (--dev, source maps, HMR).
  2. Production builds optimize size and performance (--release, LTO, compression).
  3. Dual targets (web vs. nodejs) let you share logic across client and server.
  4. CI pipelines automate environment-specific builds, ensuring consistency and reducing manual errors.