Part I: C++ To WebAssembly With React From Scratch!

Nikhil Gupta
2 min readMay 24, 2020

--

Hey everyone,
Over the past year, I have seen several projects that required the integration of shared libraries written in C++ with React based web apps. However, it’s difficult to find some simple tutorials that explain the integration process end-to-end. So, this is a humble step in that direction. Without further ado, let’s get started!

Basic React App Setup

This section takes you through the steps to setup a basic react app. If you already know how to do that, please feel free to jump to the next section.

As expected, we need to first create a basic npm project like so.

mkdir sample
cd sample
npm init -y

Next, let’s install react and its dependencies.

npm install react react-dom

Next, let’s setup some basic html and js files.

index.html

index.js

Ok, let’s install webpack, babel and associated dependencies.

npm install -D webpack webpack-dev-server webpack-cli @babel/core babel-loader @babel/preset-react html-webpack-plugin

webpack.config.js

Finally, let’s add these commands to our scripts section in package.json

"start": "webpack serve"
"build": "webpack"

Now, you should be able to start a web app via

npm run start

Visit http://localhost:8080 to see your web app in action.

WebAssembly Setup

Ok, now let’s create a sample C++ file in that would expose just a function to add two numbers and return the result.

cpp/Sample.h

cpp/Sample.cpp

Next, we will create a binding that specifies how a function can be invoked from JS and its return semantics.

bindings/SampleBindings.cpp

Finally, we will use emscripten to compile this to WebAssembly. To do this, let’s first install emscripten and add it to our search path using the steps here.

Now, we can simply use em++ to compile our C++ file to a WASM module.

emcc --bind bindings/SampleBindings.cpp -Icpp/ cpp/*.cpp -s WASM=1 -s MODULARIZE=1 -o Sample.js

Integration of WASM with React

Ok, it’s time to put everything together. To load a wasm file into our react app, we need to install file-loader and update our webpack configuration to treat it as a resource file.

npm install -D file-loader

webpack.config.js

Next, we can load the JS file and point it to the wasm file’s URI.

Calling C++ Function from JS

Now, we are all set to add our two numbers in JS via our WASM module.

You should see “3” printed on the console. :)

If you liked this article, subscribe here to get the complete code:

If you are interested in using OpenGL via WebAssembly, check out Part II here.

--

--