Create a WebAssembly module from a Rust program

webassembly

The following outlines the steps for writing a simple Rust program and turning it into a WASM module using wasm-pack.

This guide assumes that you have already installed Rust on your system. In order for this to work, I needed to switch to the nightly channel by running the following.

$ rustup install nightly
$ rustup default nightly

You can confirm that you are on the nightly channel by checking the version of the compiler.

$ rustc -V
rustc 1.45.0-nightly (a74d1862d 2020-05-14)

Next, you'll need to install wasm-pack. Once it's installed, you should be able to run the following commands to generate a new project that contains all of the necessary boilerplate.

$ wasm-pack new hello-wasm
$ cd hello-wasm

If you take a peek in the src/lib.rs file, you'll see the source of the generated Rust program.

mod utils;

use wasm_bindgen::prelude::*;

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

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

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

You can then use wasm-pack to compile the source and output a WASM module. The outputted files will be placed in the pkg directory.

$ wasm-pack build --target web

From here, you can easily publish the newly created module to npm, but since we're just testing things out, let's create a simple test web page instead.

First, in the hello-wasm directory, create a JavaScript file, index.js, that imports the new module.

import init from "./pkg/hello_wasm.js";

const runWasm = async () => {
  const helloWorld = await init("./pkg/hello_wasm_bg.wasm");

  helloWorld.greet();
};

runWasm()

Next, create an HTML file, index.html, that embeds the new JavaScript file.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World - Rust</title>
    <script type="module" src="./index.js"></script>
  </head>
  <body></body>
</html>

Now, to test it out, you just need to host the new files. If you're using Python 2, you can launch a simple server using the following command:

$ python -m SimpleHTTPServer 8000

If you're using Python 3, the following can be used instead:

$ python -m http.server

You should now be able to visit http://0.0.0.0:8000/ and see an alert from the WASM module!

WASM module hello alert screenshot

more JavaScript posts