Compiling Rust to your Browser

Rust Belt Rust, 2016-10-27

The following is the material used for the Rust Belt Rust workshop "Hire me for the JS, keep me for the Rust".


Some bigger examples of Rust code compiled to JavaScript or WebAssembly. Code will be made published soon (but is more or less the default example with some JavaScript wrappers).

Pre-built compiler

To get a `rustc` with Emscripten support, you can install a nigthly compiler using rustup. Follow these steps:

$ rustup toolchain add nightly
$ rustup target add asmjs-unknown-emscripten --toolchain nightly
$ rustup target add wasm32-unknown-emscripten --toolchain nightly

You still need the Emscripten SDK, see how to download and install it in detail or follow the simplified steps below (please refer to the official documentation for requirements and installation on Windows):

$ wget
$ tar -xvf emsdk-portable.tar.gz
$ cd emsdk_portable
$ ./emsdk update
$ ./emsdk install sdk-incoming-64bit

Once everything is set up, you can compile with Emscripten:

$ rustc --target asmjs-unknown-emscripten

You can also compile to WebAssembly instead:

$ rustc --target wasm32-unknown-emscripten


To test it live in the browser, you can use a custom version of the playground:

Caution: It is slow and might fail.

Build it yourself

With recent merges to upstream rustc, it became easier to build it yourself. Follow these steps:

curl -O
tar -xzf emsdk-portable.tar.gz
source emsdk_portable/
emsdk update
emsdk install sdk-incoming-64bit
emsdk activate sdk-incoming-64bit
git clone && cd rust
./configure --enable-rustbuild --target=asmjs-unknown-emscripten,wasm32-unknown-emscripten
python2 src/bootstrap/
echo 'fn main() { println!("Hello, Emscripten!"); }' >
build/x86_64-unknown-linux-gnu/stage2/bin/rustc --target=asmjs-unknown-emscripten
node hello.js