Why WebAssembly?

WebAssembly allows for high-performance computing in the browser, making it possible to run complex applications such as games, simulations, and multimedia editors without relying on plugins or native code. It also allows for code reuse across platforms and languages, making it easier to integrate existing codebases and libraries into web applications. And I want to use it in part to orchestrate some ML.

Install stuff

  1. brew install emscripten
  2. brew install cmake
  3. Add the WebAssembly extension to VSCode. This will let you view the WAT (WebAssembly Text) format instead of the binary. More details here [ref].

Verify your installation

I would just follow the Emscripten tutorial [ref] and make sure you can replicate, and it’s also a good learning exercise. Here’s what my repo looks like after following the tutorial. [ref]

What’s happening

emcscripten compiles your C code into a WASM project and a JavaScript module, also called “glue” code. [ref]

WASM + NextJS

But how to make it work with React?

The Emscripten tutorial is built to be loaded directly with HTML <script> tags. At compile time, Emscripten makes both a WASM binary and a JavaScript module, and you can see that in the tutorial, the HTML page is loading the glue, which is modifying a global Module variable. This won’t work with React.

A few things that are confusing:

  1. The tutorial doesn’t give examples of being able to call WASM **methods on the fly from within JavaScript. That lives here instead [ref].
  2. It doesn’t cover the native browser JavaScript API support for WebAssembly.

NextJS is a React framework. To make WASM work with NextJS, I got it working like this, which you can see in this repo [ref].

Project directory structure (simplified)

faster
├── public
│   └── wasm
│   │   └── multiplyMatrices.js
│   │   └── multiplyMatrices.wasm
├── src
│   └── app
│   │   └── useWasm.ts
├── wasm
│   └── multiplyMatrices.c
├── next.config.js
└── package.json