Tutorial: Compiling Rust to Wasm
I’ve paying increasing attention to the accelerated adoption of WebAssembly. Only a few months ago, shipping a WASM app to production seemed like a pipe dream. Now, just look at this browser support!
Building sophisticated yet performant client-side web applications is the goal of most front end organizations these days. WebAssembly allows compiled languages a new standardized target, bringing near-native performance to the web. You hear that, Mom? C++ in your browser!
Recently, Rust incorporated a native WASM target into their nightly toolchain. Providing a developer-friendly pipeline for compiling Rust into WASM should significantly raise Rust’s profile. If they continue at this pace, I think we’ll see a surge of new Rust developers this year.
I’ve been trying to get a fully-functional WebAssembly example up and working for a few weeks now. However, the landscape lacks much useful instruction. One Emscripten tutorial I tried required your environment to use Node.js version 4! Yikes!
So, I’ve put together a step-by-step tutorial of how to compile a simple web app. It uses the TodoMVC example in the stdweb cargo crate. If you’re new to Rust, don’t worry about what that means. Just follow the steps below and poke around. Here goes!
1. Install rust &
$ curl https://sh.rustup.rs -sSf | sh
Select the following option at the prompt (“1” then “Enter”):
1) Proceed with installation (default)
Restart your shell/terminal.
1a. Install the nightly toolchain
This step will hopefully disappear soon, when native WebAssembly compilation enters the stable toolchain!
$ rustup install nightly
$ rustup default nightly
2. Add the native WebAssembly Rust compilation target
rustup target add wasm32-unknown-unknown
3. Install Cargo Web
cargo install -f cargo-web
4. Download & run the example TodoMVC
$ git clone https://github.com/koute/stdweb
$ cd stdweb/examples/todomvc
cargo web start --target wasm32-unknown-unknown
5. Open the app
Open http://localhost:8000 in your browser!
Bam! You’ve got a full-blown web app, written entirely in Rust, running in your browser. What’s next? I’d suggest heading over to rust-lang.org and checking out what else Rust has to offer. Specifically, I’d encourage you to read the fantastic book, Rust: The Programming Language (second edition). It reads like an effortless refresher (or intro) to computer science.