patterntypescriptModerate
Compiling Rust to WebAssembly with wasm-pack
Viewed 0 times
wasm-packrust wasmwasm-bindgencompile rust to wasmnpm wasm package
rustwasmbrowser
Error Messages
Problem
Compiling a Rust crate to WebAssembly and making it consumable as an npm package for web projects.
Solution
Install wasm-pack. Add wasm-bindgen as a dependency. Use #[wasm_bindgen] to annotate exported functions. Run wasm-pack build --target web (or bundler/nodejs). The output is a JS+WASM package importable by npm.
Why
wasm-pack automates the entire toolchain: rustup target add wasm32-unknown-unknown, wasm-bindgen-cli, and package.json generation.
Gotchas
- wasm-pack build target matters: 'web' for direct browser use, 'bundler' for webpack/vite, 'nodejs' for Node.js
- wasm-bindgen only supports a subset of Rust types at the boundary — complex types need serialization
- The generated .wasm file must be served; import paths depend on the bundler config
- Rust compile times are long — use sccache or cache ~/.cargo and target/ in CI
Code Snippets
Simple wasm-bindgen export
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Build command
wasm-pack build --target bundlerRevisions (0)
No revisions yet.