Skip to main content

Build WASM

Build for Browsers

wasm-pack

Building rust program to WebAssembly for browsers uses wasm-pack.
Run cargo install wasm-pack or installer is available at github releases or here.

Run this command to build WebAssembly.
More command line options can be found at wasm-pack build.

build for browsers
wasm-pack build --release --out-name prime --target web

This command generate prime.js , prime_bg.wasm in ./pkg directory.

info

Generated prime_bg.wasm can be run as standalone wasm.

wasm32-unknown-emscripten

When building wasm with emscripten targeting wasm32-unknown-emscripten.
wasm32-unknown-emscripten target have to be installed.

This command shows all of the targets supported by rust.
Check that wasm32-unknown-emscripten is installed.

list all targets
rustup target list
targets list ouput
// omit...
wasm32-unknown-emscripten (installed)
// omit...

Or, you can install target with

add target
rustup target add wasm32-unknown-emscripten

Additionally, emscripten have to be installed.
Then add link option in .cargo/config.toml (see Configuration - The Cargo Book).

This command build and generate prime.wasm.

build with targeting wasm32-unknown-emscripten
cargo build --release --target wasm32-unknown-emscripten

Build for Standalone

prime_bg.wasm which is generated by wasm-pack can be used as standalone wasm.
Here show the ways to build WebAssembly using cargo build.

Before building standalone wasm, we need to check the build targets installed.
This command shows all of the targets supported by rust.

list all targets
rustup target list
targets list ouput
// omit...
wasm32-unknown-unknown (installed)
wasm32-wasi (installed)
// omit...

These targets are briefly expalined here.
You can install target using rustup command.

add target
rustup target add wasm32-unknown-unknowns

Now, let's build standalone wasm.

First, we need to comment out or remove the wasm_bindgen attribute and unused import because wasm_bindgen adds or removes symbols for combining JavaScript.
More document on wasm_bindgen can be found at The wasm-bindgen Guide, wasm-bindgen - crates.io.

comment out or remove these 2 lines
use wasm_bindgen::prelude::*;

#[wasm_bindgen]

wasm32-unknown-unknown

This command build standalone wasm for WASI and generates prime_standalone.wasm
Then we can use .wasm standalone.

build with targeting wasm3-unknown-unknown
cargo build --release --target wasm32-unknown-unknown

wasm32-wasi

When targeting wasm32-wasi, it may requires wasi crate and may requires fixing source code.

build with targeting wasm3-wasi (sample program does not works on wasmer)
cargo build --release --target wasm32-wasi

This command generates prime_standalone.wasm.