Skip to content

WebAssembly

wasm-pack helps in building and working with rust generated WebAssembly

Install

sh
cargo install wasm-pack

Create a new project

sh
cargo new wasm-pack-test

Add lib section in Cargo.toml

toml
[lib]
crate-type = ["cdylib", "rlib"]

Add a dependency in Cargo.toml

toml
wasm-bindgen = "0.2.81"

Add a lib.rs to src folder

rust
use wasm_bindgen::prelude::wasm_bindgen;

#[wasm_bindgen]
extern {
    fn alert(s: &str);
}

#[wasm_bindgen]
pub fn greet() {
    alert("Hello, wasm-pack-test!");
}

Build a web target

sh
wasm-pack build --target web

Add an index.html near Cargo.toml file

html
<html>
<script type="module">
  import init from './pkg/wasm_pack_test.js';
  var res = await init();
  res.greet();
</script>
</html>

Start a http server, you can install a very tiny binary crate called serve

sh
cargo install serve
serve

Now, test in browser at localhost:8080