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.
Previous
How do you implement a custom global allocator in Rust?
Next
What are Rust performance optimization techniques?
More Rust Questions
View all →- Advanced What are zero-cost abstractions and monomorphization in Rust?
- Advanced What are Pin<T> and Unpin in Rust async programming?
- Advanced How does the async runtime work internally in Rust (Waker, Poll, Executor)?
- Advanced What are the rules for writing correct unsafe Rust?
- Advanced How does Rust FFI (Foreign Function Interface) work with C?