Lesson 4 of 9 · 25m
Compiling Rust to WebAssembly
The Rust wasm target, wasm-bindgen, wasm-pack, release profiles, panic behavior, and the practical path from Rust crate to browser module.
Rust is the smoothest serious language for browser Wasm because the ecosystem invested in bindings early. That doesn't mean it's effortless. The difference between a demo crate and a production module is panic behavior, binary size, allocation ownership, and whether the generated JavaScript glue fits your bundler instead of fighting it.
Start with the right target
rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown --releaseThe bare target produces a .wasm file, but browser interop usually wants wasm-bindgen. A minimal crate looks like:
[package]
name = "image_kernel"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
[profile.release]
lto = true
opt-level = "z"
codegen-units = 1
panic = "abort"And the export:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn sharpen_luma(input: &[u8], width: usize, height: usize) -> Vec<u8> {
let mut out = input.to_vec();
// operate on out in place or return transformed bytes
out
}wasm-pack build --target web generates JS glue plus TypeScript definitions. --target web is often the right choice for modern ESM applications; bundler-specific targets can become weird when your build pipeline changes.
Understand what the glue does
Generated bindings allocate memory, copy slices, decode strings, and free buffers. Read them once. If you see passArray8ToWasm0 and getUint8Memory0, those aren't implementation trivia — they're the boundary protocol. They also reveal copying. Returning a Vec<u8> generally copies data out of Wasm memory into a JavaScript-owned typed array.
Size is a feature
panic = "abort", lto = true, opt-level = "z", and wasm-opt -Oz can collapse a multi-megabyte debug artifact into something shippable. Measure:
ls -lh pkg/image_kernel_bg.wasm
wasm-opt -Oz image_kernel_bg.wasm -o image_kernel_bg.opt.wasmDo not ship a debug build to production because 'it works on my machine.' Debug symbols, formatting machinery, and panic paths are huge.
Field notes
wasm32-unknown-unknownhas no standard library OS access; filesystem, threads, and sockets don't magically exist.console.logfrom Rust goes through imported glue and can dominate hot loops.- Keep Rust APIs byte-oriented. Complex object graphs belong in serialization, not wishful thinking.
- Pin toolchain versions in CI. Wasm output size and ABI details can shift with compiler releases.
Was this lesson helpful?