🦀 Rust Advanced

How do you compile Rust to WebAssembly?

Answer

Rust is one of the best-supported languages for WebAssembly (Wasm). Add the wasm32-unknown-unknown target with rustup target add wasm32-unknown-unknown and build with cargo build --target wasm32-unknown-unknown --release. The wasm-bindgen crate is the key tool: it generates JavaScript glue code enabling Rust functions to call browser APIs and vice versa. Annotate functions with #[wasm_bindgen] to expose them to JavaScript. Use the web-sys crate for browser Web APIs (DOM, fetch, canvas) and js-sys for JavaScript built-ins. wasm-pack orchestrates the build pipeline: it compiles Rust to Wasm, runs wasm-bindgen, and packages the result as an npm module. Use cases include compute-intensive browser tasks (image processing, cryptography, parsers), Rust on Cloudflare Workers, and portable plugin systems.