Install the latest nightly (2017-11-25 or later):
rustup toolchain install nightly
If you already installed nightly before, make sure it is up to date:
rustup update
Install the required target:
rustup target add wasm32-unknown-unknown --toolchain nightly
Compile your code to WebAssembly:
rustc +nightly --target wasm32-unknown-unknown -O hello.rs
(The +nightly part is a shortcut handled by rustup's wrappers around rustc and cargo)
You will end up with a hello.wasm. It will be quite big. To reduce size, first install wasm-gc:
cargo install --git https://github.com/alexcrichton/wasm-gc
Then run it to reduce the size of the WebAssembly module:
wasm-gc hello.wasm small-hello.wasm
You can also compile a project to WebAssembly using cargo.
First create the project:
cargo new myproject
Next, change the crate type to cdylib. Add this to your Cargo.toml:
[lib] path = "src/lib.rs" crate-type = ["cdylib"]
Finally, compile it:
cargo +nightly build --target wasm32-unknown-unknown --release