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.
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:
We are going to write a method which will add two numbers. Create a file named as mathUtils.ts with below code:
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:
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
Post a Comment