WebAssembly with Rust and React (Using create-react-app)

lokesh007

Lokesh Prabakaran

Posted on June 30, 2020

WebAssembly with Rust and React (Using create-react-app)

WebAssembly looks quite promising in bringing high performance, near-native speed to frontend applications, all from within the browser.

This opens up entirely new fronts/avenues for frontend application which was previously inaccessible. There are numerous articles and writings on webassembly out there, and this article's scope is not about the workings of WebAssembly but instead about setting it up with Rust and React, so one can use this boilerplate code to build useful applications.

The reason I chose Rust is that Rust as a language is really good and is well suited for systems programming and also I have been exploring Rust for close to a month for another side project of mine but that is for another day.

Create a new app using create-react-app

npx create-react-app my-app

create-react-app is the defacto tool to create a react app which takes care of setting up all the initial configuration and scripts, so developers can focus more on creating applications rather than configuring them

sudo npm i -g wasm-pack --unsafe-perm=true

We will be using this to create a native rust package that is configured to compile to wasm. One can think of it as a create-react-app equivalent for the Rust module.

wasm-pack new <your-native-module-name>

This will create a native rust module

Now, you can restructure the app the way you want, just make a note of the relative path of the native module from the project's root.

Create-react-app takes care of all the configuration, but it does come at a price. We can't modify configurations to suit our needs, because that is the job of create-react-app. But for adding our rust module and WebAssembly into our build, we need to update webpack config.

We don't need to eject create-react-app, there is a way we can do this without ejecting create-react-app; using ‘react-app-rewired’

npm install react-app-rewired @wasm-tool/wasm-pack-plugin --save-dev

add config-overrides.js

Rewrite your scripts config in your package.json file

"scripts": {
   "start": "react-app-rewired start",
   "build": "react-app-rewired build",
   "test": "react-app-rewired test",
   "eject": "react-scripts eject"
 },

Done, you are all set for creating something useful with react and rust.

Please refer to the github repo below for reference,

GitHub logo lokesh-007 / wasm-react-rust

WebAssembly with Rust and React (Using create-react-app)

💖 💪 🙅 🚩
lokesh007
Lokesh Prabakaran

Posted on June 30, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related