Notes on compiling Rust projects to WASM.

1 Setup

Make sure the wasm build target is installed. This can automatically be installed using the rust-toolchain.toml file detailed below. Otherwise it should be manually installed using:

rustup target install wasm32-unknown-unknown

We also need some way to generate the js bindings for interacting with the wasm file. The easiest way to do this is with wasm-bindgen

$ cargo install wasm-bindgen-cli

2 Build

Build the project

cargo build --release --target wasm32-unknown-unknown

3 Generate JS Bindings

We still need to generate the js bindings to load and interact with the wasm file. The easiest way to do this is using wasm-bindgen

wasm-bindgen [[wasm-file]] --out-dir [[bindings-dir]] --target web

4 Run

Load and run the project on the webpage.

wasm-bindgen produces a number of files in the output bindings dir, of which [[project name]]_bg.wasm and [[project name]].js are most important.

All we need to do is create a simple js module script to load and run the wasm file.


import init from "[[project name]].js";

init().finally(() => {
    console.log("wasm file loaded and running.");
});
        

The above process is only for executable crates. Library crates can be made to be expose specific functions using the wasm-bindgen crate.

5 Notes

4.1 rust-toolchain.toml

Its usually worth specifying a rust-toolchain.toml file pinning the channel to a specific version. This avoids future issues with wasm-bindgen and other crate compatibility. This file exists in the root of your rust project, in the same directory as Cargo.toml


[toolchain]
channel = "stable"
targets = ["wasm32-unknown-unknown"]