This is a personal experiment in getting Rust code working in a web project (React + Vite) via WebAssembly. The purpose is to try writing business logic once in the form of a Rust library, and then sharing it across multiple frontends (e.g. cli tools, web apps).
In this particular project, a simple calculator library is shared by a cli app and a React web app. This whole thing is a Cargo workspace with 3 packages:
calculator: the shareable librarycalculator_cli: a cli app consuming the librarycalculator_web: a Wasm wrapper around the library + a React web app (insidewww)
The 3 major components to getting the web app working are:
wasm-bindgen, for doing Rust -> Wasmwasm-pack, for building the Wasm package consumed by the web app, andvite-plugin-wasm, which supports Wasm ESM integration in Vite projects
Prerequisite: you'd need a stable Rust toolchain installed.
To test out the cli app:
# Clone the repo and navigate to the cli package dir
$ git clone https://github.com/tornarus1/rust-wasm-vite.git
$ cd rust-wasm-vite/calculator_cli/
# Will print out "10 / 2 is 5"
$ cargo run --release 10 2
# Will print out an error
$ cargo run --release 10 0Prerequisites:
- you'd need an installation of Node.js and
npm - you'd also need
wasm-packto handle the Wasm package and glue code generation
To run the web app locally in your browser:
$ cd rust-wasm-vite/calculator_web/
# Generate the `pkg/` dir containing the Wasm package
$ wasm-pack build
# Install dependencies of the React app (including the Wasm package generated above!)
$ cd www && npm install
# Spin up a local server, which you can open with your browser
$ npm run devP.S. The error message you see on the web app when doing division by 0 comes from the Rust lib!
Licensed under the MIT license.