We live in a world where JavaScript code is run literally everywhere. We have it in the browser, as well as in the backend with Node.js,  in desktop apps (Electron) and even on MCUs (low.js anyone?).

JavaScript has somewhat delivered the long standing promise (no pun intended) of “write once, run anywhere” that many have tried (and failed) to accomplish in the past. Unfortunately this is far from ideal, mostly because JavaScript was not designed with this goal in mind.

Several revisions of the ECMAScript standard were released to improve the language and address its limitations. Furthermore new and more expressive languages (yes TypeScript, we hear you) were released to add missing features while maintaining the complete compatibility with existing runtime engines. All this has led to the fragmented ecosystem we are all fighting everyday, making the development of large projects very challenging.

On top of that, JavaScript is slow. Even on heavily optimized runtimes JavaScript code is always slower than native code (yes V8, I’m talking about you and your speculative optimization). If this is surprising for you, please follow these steps:

  1. Leave the cave you are currently living in;
  2. Download the ECMAScript specification and count how many steps are required to perform just an OrdinaryGetOwnProperty;

Therefore, when in need of native performance, developers had to turn to native code (plug-ins, NPAPI, etc.) with frequently disastrous consequences in terms of security.

So why WebAssembly?

Here is where WebAssembly comes to the rescue.

If you have never heard about WebAssembly, don’t miss the talk Diwanshi Pandey, software engineer at Red Hat, will give at Codemotion Milan 2019tickets are still available!

WebAssembly, or wasm for brevity, is essentially a portable binary code format designed to run on an isolated virtual stack machine. It is not a replacement for JavaScript, but rather a companion tool which offers better performance where needed.

WebAssembly is a compilation target for C, C++, Go, Rust and others. Developers can code in any of those languages and then compile their source into wasm binaries which will then run alongside JS code in their applications.

There are many obvious reasons why WebAssembly is faster than JavaScript. First of all, binary wasm is smaller and easier to parse than JS code – even when minified. More importantly, wasm is a compilation target for statically typed languages. That implies there is less overhead when accessing variables or evaluating expressions (there is no  OrdinaryGetOwnProperty madness).

However, these are not the reasons why WebAssembly is so special. After all, on a purely technical level binary wasm is not very different from Java’s bytecode or .NET Common Intermediate Language. But WebAssembly is an open standard and it is already implemented in all the major browsers. That means you don’t need a native plug-in to run wasm code in your browser, no matter what platform, OS or device you are using. And this is pretty unique.

… and why Rust?

There are many things to consider when choosing the technologies and the languages to use for a project. To use WebAssembly we must use a language which can be compiled into wasm. Transitioning from JavaScript to C or C++ can be challenging to say the least.

Go would be a better alternative in this case, as it is concise and easy to read. However, there is always a trade-off between performance and readability. Go’s runtime offers a lot of features but these come at the cost of the binary size:  the smallest wasm file compiled from Go is around 2 MB, while 10 MB is the most typical size. That is huge compared to the files compiled from C++ and Rust, which are typically just a few KB.

Rust is as powerful as C++ when it comes to performance but it is safer, especially when dealing with memory management. Moreover, Rust’s support for WebAssembly is mature and complete, offering tools and bindings to integrate it into existing JavaScript projects.

Getting started: setup

To begin working with Rust and WebAssembly, one must obviously have the Rust toolchain installed. Nowadays the best (and recommended) way to manage the Rust toolchain is via the rustup tool.

Installing rustup is as easy as launching a Bash script (the rustup-init.sh script to be precise) with this one-line command:

# curl https://sh.rustup.rs -sSf | sh

If you are running Windows, luckily we leave in Nadella’s era and thus we have plenty of options to get Bash up and running: the Windows Subsystem for Linux, Git for Windows own Bash, Cygwin, just to name a few. If you don’t want to use Bash at all, there is a .exe version of rustup-init as well as standalone installers available for download from Rust language project website.

The script will download and compile all the required tools including rustc (the Rust compiler) and cargo (Rust’s package manager).

By default, the toolchain will be installed in $HOME/.cargo so be sure to add the $HOME/.cargo/bin to your PATH environment variable, or simply run the command:

# source $HOME/.cargo/env

when opening a new shell.

Once the Rust toolchain is installed, we can proceed installing wasm-pack. Wasm-pack is an all in one tool to build, test and publish Rust-generated wasm modules. To install it, simply type this command in your Bash prompt:

# curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

or again, download the .exe file if you are on Windows from the official website.
Another useful tool to install is cargo-generate, which allows to create new projects based on existing templates. Since the Rust toolchain is already installed, we can use cargo itself to download, compile and install cargo-generate, with this command:

# cargo install cargo-generate

In case you do not have those installed, we recommend to install git, node and npm as these may come in handy pretty soon.

Our first WebAssembly module

Let’s now dive in and build our first Hello World project in Rust/WebAssembly: a web page that shows an alert!

First of all, we will create a new project using cargo generate, using a git repository as a template:

# cargo generate --git https://github.com/rustwasm/wasm-pack-template

When prompted for the project’s name, just type the name “hello”. The script will create the directory “hello” and populate it with the files shipped with the template:

  • Cargo.toml – which specifies dependencies and metadata for cargo (a sort of Rust’s equivalent of package.json);
  • src/lib.rs – which contains the code of our wasm module;
  • src/utils.rs – which provides common utilities to debug wasm code;

Let’s have a look at the lib.rs code in detail:

We obviously import the utils module, and then proceed using the wasm_bindgen, which is used to provide interoperation between our Rust and JavaScript code.

In this simple example, wasm_bindgen is used to import the browser’s alert() function, so our Rust code can call it and display the “Hello, hello!” message. That’s because the string created by cargo generate is “Hello, <project_name>!” and our project is named “hello”. Feel free to change this message according to your preference.

At the same time we also export the greet() function, so that the JavaScript code using our wasm module can call it.

When targeting wasm, the wee_alloc allocator is the preferred choice, as it was explicitly designed for smaller code size, although it can be a bit slower than other allocators.

Now that our code is ready, we can proceed building the project. To do that we will use the wasm-pack utility, which performs some sanity checks (ensuring we have the correct Rust version), compiles our code to wasm, download and compile all the dependencies and finally invoke wasm-bindgen to generate the JavaScript API bindings. All that with just one command:

# wasm-pack build

Once finished, the compiled artifacts are available in the pkg/ directory. This directory should contain these files:

  • hello_bg.wasm – our WebAssembly binary, which exports the greet() function;
  • hello.js – the JavaScript glue that implements interoperation layer between JS and wasm;
  • hello.d.ts – the TypeScript declarations for the JavaScript glue;
  • package.json – the metadata about this generated WebAssembly package;

Calling WebAssembly from a web page

The Rust project offers an npm init template to generate a web application that will call our WebAssembly module. Simply type the command:

# npm init wasm-app www

This will generate the web application inside the www/ directory, including a package.json file, a configuration file for webpack, an empty index.html and an empty JavaScript entrypoint index.js.

To use our WebAssembly package here, we simply must add it as a dependency in the package.json file, by adding the following line under the “devDependencies” node:

"hello": "file:../pkg"

Then, install the dependencies with the well known command:

# npm install

Once the installation is finished, modify the index.js file to call our WebAssembly greet() function, with this code:

import * as wasm from "hello"; 

This code imports our WebAssembly module using the JavaScript glue code in hello.js and calls the greet()  function.

Since we have Webpack and its local server installed, we can run the application with the command:

# npm run start

Now point your browser to http://localhost:8080/ to be greeted with the message from our Rust code.

Congratulations, you have created your first Rust/WebAssembly project!


There is a lot more to cover about Rust and WebAssembly, considering best practices, optimization and interoperation between Rust and JavaScript (look up js-sys and web-sys).

Again, if you want to learn more about Rust and WebAssembly, don’t miss the talk Diwanshi Pandey, software engineer at Red Hat, will give at Codemotion Milan 2019tickets are still available!

Diwanshi will address more advanced topics and show some interesting demos. More info about the talk are available at this link.