Rust WebAssembly first steps
-
Install
wasm-pack
, the high-level build tool for Rust WebAssembly projects.cargo install wasm-pack
-
Create a new project with a library create. Here, we are using
cargo new
, but for more sophisticated Wasm project you may want to usewasm-pack new
.cargo new --lib wasm_add
-
Add
wasm-bindgen
as a dependecy.cd wasm_add cargo add wasm-bindgen
-
Open the project in your code editor and modify
Cargo.toml
to change the librarycrate-type
tocdylib
:... [lib] crate-type = ["cdylib"] ...
-
Change the initial
src/lib.rs
code:use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn add(a: i32, b: i32) -> i32 { a + b }
-
Build the project with
wasm-pack
(web
target, ES6 module)wasm-pack build --target web
-
Add
index.html
file to the project root with the following contents:<!doctype html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Wasm Add</title> </head> <body> <script type="module"> import init, { add } from "./pkg/wasm_add.js"; init().then(() => { const a = 7; const b = 13; const x = add(a, b); document.body.textContent = `${a} + ${b} = ${x}`; }); </script> </body> </html>
-
Install a simple web server (Host These Things Please), and serve the project root folder, than visit the local page
cargo install cargo install https http