WebAssembly with React.js Example

We are going to create a simple React.js application with WebAssembly. As per Mozilla's definition of WebAssembly, it is a new type of code that can be run in modern web browsers — it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as C/C++, C# and Rust with a compilation target so that they can run on the web.

If you prefer video explanation then you can watch on YouTube (in Hindi). 

We'll write code in TypeScript which can be compiled to WebAssembly, to do that we will use AssemblyScript.

Let's create a project 'exploring-wasm' using create-react-app. We would be installing assemblyscript dependencies.

  npm i @assemblyscript/loader --save
  npm i assemblyscript --save-dev

We are going to store TypeScript files in a folder outside 'src' folder, I'll name it as 'tsFiles'. WebAssembly files will be store in public/wasm folder. To compile ts files, we will write a bash file which will loop through the files inside 'tsFiles' folder and create wasm files using 'asc' - the AssemblyScript executable. Let's create wasmCompiler.sh like below in the root folder:

#! /bin/bash
cd tsFiles
for f in * ; do
  filename="${f%%.*}.wasm";
  ../node_modules/.bin/asc $f -b ../public/wasm/$filename;
  echo "$filename created"
done

We are going to write a method which will add two numbers. Create a file named as mathUtils.ts with below code:

export function add(ai32bi32): i32 {
    return a + b;
  }

Compile it using wasmCompiler.sh and that will create and store wasm files in public/wasm folder. If we run the react application then we can get those files on http://localhost:3000/wasm/mathUtils.wasm.

It's time to create a js file in src folder and fetch the WebAssembly method(s). To get add method, we are going to use 'fetch' and it will return response of buffer array, then we would instantiate the WebAssembly on the browser, so that we can get 'add' method. Create a method in the js file to call 'add' method of wasm like below:

const addNumbers = async () => {
    const response = await fetch('wasm/mathUtils.wasm');
    const buffer = await response.arrayBuffer();
    const wasmModule = await WebAssembly.instantiate(buffer, {
      env: {
        abort: () => console.log('Abort!'),
      },
    });

    const addResult = wasmModule.instance.exports.add(2410);
console.log('addResult'addResult);
  };

We can write code for WebAssembly in C, C++ using Emscripten and Rust using wasm-pack. WebAssembly is going to revolutionize web application development. It will stay with JavaScript side-by-side, so don't worry about JavaScript. It will improve performance of web application, such as Video editing, graphics and many more high-performance apps.

Comments

Popular Posts