Creating a WebAssembly Package With Rust

Matthew MacFarquhar
2 min readJul 20, 2022

--

WebAssembly is the hot new thing that is taking the web dev world by storm! The main promise of WebAssembly is that it allows you to use pre-compiled code in a web environment (as opposed to js which is just in time compilation). This gives us the ability to run native apps written in things like C and Rust in a js environment so that we don’t need to re-code our C library into js 🤢. WebAssembly is also much faster than js! Depending on the environment, WASM can produce code that runs 1.5–11 times faster!

Now that we have a good understanding of why WASM is so useful, let’s dive into the How.

Rust

Before we run some compiled code in the browser, we first have to create said code. I like Rust as it is the newest kid on the block in the low level code neighborhood and has better memory management than C++ leading to (in my opinion) better applications and a faster dev cycle.

first we are going to need our wasm-pack crate to turn the compiled code into something that can be run on the web.

cargo install wasm-pack

next lets edit our lib.rs file to look like this

The wasm_bindgen header allows communication between rust and js for these functions.

The extern block tells rust about a function js has so that we can reference it in our code (in this case we tell rust about js’s alert function which takes in a string).

We then create two functions. One that alerts a greeting and one that adds some numbers and alerts the sum. As you can see, since we told rust about js alert, we can use it in the rust functions.

Next, we will need to update our Cargo.toml file to instruct rust to use the wasm-bindgen as a dependency.

Finally, we can compile the rust code to a web target using

wasm-pack build --target web

This will generate a pkg folder with everything we need to call our wasm code from js.

HTML & JS

Now we can create an index.html file and call our wasm code!

You can see here that we import init (made by the compiler) as well as our functions greet and add from our packaged js file.

We call init and after the wasm has loaded, we can call our functions directly via js. If you open the html file in your browser, you will now be able to see your rust code in action on the web 😀🤯.

--

--

Matthew MacFarquhar
Matthew MacFarquhar

Written by Matthew MacFarquhar

I am a software engineer working for Amazon living in SF/NYC.

No responses yet