The simplest way to get started with WebAssembly

Step 1: setting up the environment

The first thing you should install (assuming you have Node set up already) is AssemblyScript, which is a subset of TypeScript, with the added (incredibly cool!) feature of being able to compile directly to WASM. So by adding a few extra annotations, a plain old JS function can be transformed into WASM using the AssemblyScript command line tool.

So just go ahead, run the following npm command:

 npm install -g assemblyscript
npm install -g http-server

Step 2: creating your first WebAssembly module

First of all, you’ll need to create a tsconfig.json file with the following contents:

asc fib.ts -o fib.wasm

Step 3: run your WASM file from a browser

To run the code in a browser, not too surprisingly, you’ll need a browser! I’ve tested this in Chrome 61.0, but any other browser should be all right, if it supports WASM (most of the modern ones do) and the fetch API.

> fib(5)<- 8> fib(6)<- 13> fib(7)<- 21

Bonus step: measure it!

One of the cool things about WebAssembly is that it should be faster than plain JS. Well, let’s test how our fib.wasm compares against a plain JS solution.
I’ve added a few extra functions to my test site:

timer(simpleFib, 10)
timer(fib, 10)

Final thoughts

WebAssembly is wickedly cool. Now, thanks to AssemblyScript it’s even more accessible, so in my book, no real case can be made against trying it out, and even using it to optimize the computation-heavy parts of your code. If you want to dive deeper, you should definitely read the AssemblyScript docs, since it has a few important details you’ll need, in a surprisingly concise form.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Benedek Gagyi

Benedek Gagyi

tinkering with javascript and css @ [code, basketball, tea, beer, trailrunning]