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-bindgenas a dependecy.cd wasm_add cargo add wasm-bindgenOpen the project in your code editor and modify
Cargo.tomlto change the librarycrate-typetocdylib:... [lib] crate-type = ["cdylib"] ...
Change the initial
src/lib.rscode:use wasm_bindgen::prelude::*;#[wasm_bindgen]pubfnadd(a:i32,b:i32) -> i32{ a + b }
Build the project with
wasm-pack(webtarget, ES6 module)wasm-pack build --target web
Add
index.htmlfile to the project root with the following contents:<!doctype html><htmllang="en-US"><head><metacharset="utf-8" /><title>Wasm Add</title></head><body><scripttype="module">importinit,{add}from"./pkg/wasm_add.js";init().then(()=>{consta=7;constb=13;constx=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