Minimal WASM example

Rust and WASM

This experiment follows the first couple pages of the Rust and WebAssembly book, to get Rust working in the browser.

The Rust code is just:

lib.rs
#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);
}

#[wasm_bindgen]
pub fn greet(name: &str) {
    alert(&*format!("Hello, {}!", name));
}

#[wasm_bindgen]
pub fn multiply(a: i32, b: i32) -> i32 {
    a * b
}

This code declares the alert function as external, which we can call to show an alert on the browser. It also exposes the greet function, which will call alert with Hello, ${name}!.

Now, from the JavaScript side, all we have to do is add "wasm-minimal-example": "file:./wasm/wasm-minimal-example/pkg"1 to dependencies in package.json and add the following code:

import * as wasm from "wasm-minimal-example";
wasm.greet(this.name);

const result = wasm.multiply(3, 2);

With this example, we're passing data from JavaScript into Rust, and then Rust calls the window.alert function. So cool!

There's really no point in this example, because we could directly call alert from JavaScript, but this opens the door to many other cool things we'll be able to do.


  1. I created a folder called wasm as a sibling to package.json. Then, with cargo-generate installed, I ran cargo generate --git https://github.com/rustwasm/wasm-pack-template inside this wasm folder. When it prompted for a name, I entered wasm-minimal-example. Finally I run npm install. If you set up your Rust project in a different path, you should change where you import it from in package.json.

© 2020 Guillem Caballero Coll