-
mkdir wat; cd wat
-
Empty module (
add.wat
):(module)
-
Basic add function:
(module (func (export "add") (param $a i32) (param $b i32) (result i32) local.get $a local.get $b i32.add ) )
-
Run:
wasmer add.wat -i add 2 3
-
Convert to binary:
wat2wasm add.wat
-
Run wasm:
wasmer add.wasm -i add 2 3
-
Dump:
wasm-objdump -x add.wasm
-
Convert back to text:
wasm2wat -o add2.wat add.wasm
(module (type (;0;) (func (param i32 i32) (result i32))) (func (;0;) (type 0) (param i32 i32) (result i32) local.get 0 local.get 1 i32.add) (export "add" (func 0)) )
-
Add a web page (
index.html
):<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Hello</title> </head> <body> <script> (async () => { var obj = await WebAssembly.instantiateStreaming( fetch("./add.wasm") ); alert(obj.instance.exports.add(3, 2)); })(); </script> </body> </html>
-
Run:
python3 -m http.server 10000
- Create new bin project:
cargo new hello
cd hello
- Build:
cargo build
- Run:
./target/debug/hello
ls -la ./target/debug/hello
file ./target/debug/hello
- Build for Wasm:
cargo build --target wasm32-unknown-unknown
ls -la ./target/wasm32-unknown-unknown/debug/hello.wasm
file ./target/wasm32-unknown-unknown/debug/hello.wasm
wasmer ./target/wasm32-unknown-unknown/debug/hello.wasm
— OhOh!
- Build for WASI:
cargo build --target wasm32-wasi
wasmer ./target/wasm32-wasi/debug/hello.wasm
wasmtime ./target/wasm32-wasi/debug/hello.wasm
wasm3 ./target/wasm32-wasi/debug/hello.wasm
wasmedge ./target/wasm32-wasi/debug/hello.wasm
-
Create new lib project:
cargo new --lib add
-
Test:
cargo test
-
Add
add
function:#[no_mangle] pub extern "C" fn add(a: i32, b: i32) -> i32 { a + b }
-
To Cargo.toml:
[lib] crate-type = ["cdylib"]
-
Build:
cargo build --target wasm32-unknown-unknown
-
Run:
wasm3 --func add ./target/wasm32-unknown-unknown/debug/add.wasm 2 3
-
Or:
wasmer ./target/wasm32-unknown-unknown/debug/add.wasm -i add 2 3
-
create lib project:
cargo new --lib hello-js
-
cd hello-js
-
in
Cargo.toml
:[dependencies] wasm-bindgen = "0.2.78" [lib] crate-type = ["cdylib"]
-
lib.js:
use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { fn alert(s: &str); } #[wasm_bindgen] pub fn hello(to: &str, from: &str) { alert(&format!("hello to {to} — from {from}")); }
-
build:
wasm-pack build --target web
-
add some html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Hello</title> </head> <body> <script src="./index.js" type="module"></script> </body> </html>
-
add some JS:
import init, { hello } from "./pkg/hello_js.js"; await init(); hello("We Create!", "JavaScript in the browser");