What is WebAssembly?
Which languages can I use it with?
Creating a Hello World in WebAssembly
If you’ve never used Rust before, you need to install the standart Rust tool chain.You can find it here.
After you’ve installed the Rust tool chain, you need to install the wasm-pack and
cargo-generate which lets you make a Rust project quickly by using a pre-existing git repository as a template.
cargo-generate with this command:
cargo install cargo-generate
Creating the Project
First, we need to clone a project template with this command:
cargo generate --git https://github.com/rustwasm/wasm-pack-template
Now let’s have a look at some of the files.
greet Rust function, which alerts a greeting message
Now, we need to compile our application to webassembly to be able to use it in our project. We do that by running
Using WebAssembly with React
first, we start with creating a react app.
npx create-react-app webassembly-react
Out of the box, create-react-app will not support WebAssembly. We have to make some changes to the underlying webpack config that powers the app. Unfortunately, create-react-app doesn’t expose the webpack config file. So, we’ll need to pull in some dev dependencies to help us out.
react-app-rewired is going to allow us to modify the webpack without ejecting, and
wasm-load will help webpack handle WebAssembly.
yarn add react-app-rewired wasm-loader --dev
Once this is done, you should have a fully functioning app, now we can make some tweaks to our webpack.
We need to add a
config-overrides.js file to the root of our app. This file will allow us to make changes to our webpack file without rewriting it.
At this point, if you run
yarn start, you will not be using the webpack config changes, since we need to modify the package scripts. We need to make some changes to
package.json in order to take advantage of the changes we just made.
Put this in your config.json:
If you’ve done everything correctly, you should be able to run
yarn start and the app should load.
Importing a WebAssembly module into the app
Now that we have set up our React app and built the webassembly file, we need to import it. We need to do that asynchronously.
Once that is done, we can access webassembly in our app through state. Note that you need to
await the module each time you call a function.
In this app, I’ve created two simple functions. One functions calculates the factorial of 200 and the other one calculates the factorials of the first 40 numbers in the Fibonacci sequence. You can try pressing the buttons for yourself, a graph is going to show you the time it took for the process to complete.
Using WebAssembly in your web application is really useful if you need to make CPU-heavy or time heavy calculations fast. Getting it up and running is quite tedious and hard, since the language is pretty new and there haven’t yet been created any libraries or templates that make this process easier.