🌐
Rust → WASM — Running Rust in the Browser
Calling Rust from JS with wasm-pack + wasm-bindgen
We covered why Tooscut (browser video editor) uses Rust/WASM earlier. Here's how to actually compile Rust to WASM.
Basic Flow
wasm-pack build— compiles Rust to.wasm+ JS bindings- Creates npm-publishable package
- Call from JS:
import { my_function } from './pkg'
wasm-bindgen
Rust's String and JS's string have different memory layouts. wasm-bindgen auto-generates conversions.
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {name}!")
}
Performance
WASM achieves 90-95% native performance. 5-50x faster than JS for CPU-intensive work (image processing, crypto, parsing). DOM manipulation is better in JS — WASM DOM API calls have overhead.
Key Points
1
rustup target add wasm32-unknown-unknown
2
cargo install wasm-pack
3
Mark functions to expose to JS with #[wasm_bindgen]
4
Build with wasm-pack build --target web
5
Import and call from JS (use like npm package)
Pros
- ✓ 5-50x faster than JS for CPU-intensive tasks
- ✓ Rust's memory safety maintained in the browser
Cons
- ✗ DOM manipulation better in JS — WASM↔JS call overhead
- ✗ .wasm binary size can be large (needs wasm-opt optimization)
Use Cases
Browser video editing (Tooscut) — GPU compositing engine as WASM
Browser games — Bevy engine WASM target