Guide
- Setup a project with Cargo
cargo new myproject
cd myproject
cargo build
- We need wasm-bindgen and wasm-pack
cargo add wasm-bindgen
cargo install wasm-pack
- Create a file
src/lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add(a : i32, b : i32) -> i32 {
a+b
}
wasm-pack build --target web
- The exported WASM Module should be in
pkg/myfile.wasm
, and JS files should be created for loading
- Create a
index.html
with:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="style.css">
</head>
<body >
<script type="module">
import init, {add} from "./pkg/hello_wasm.js"
// setup glue code
await init()
console.log(add(1,2))
</script>
</body>
</html>
- Run with Python HTTP Server
python -m http.server