[!WARNING] How long does it take to measure π?
A simple demo of a WebAssembly app together with a WebAssembly worker using Leptos, rust_i18n, Tailwind 4 and web-sys, i.e. a full Rust WebAssembly stack. See it in action!
It stupidly calculates Pi using the Leibniz formula and shows the result in a modal. It does so by sending messages to the worker and receiving intermediate results and the final result.
This application builds Rust code into WebAssembly. It demonstrates:
The app uses a WebAssembly worker to do the heavy lifting of calculating Pi. After the worker is created it is passed a closure that handles messages from the worker. The worker sends messages back to the main thread, the main thread receives these messages and updates the UI accordingly. That's why the UI keeps responsive while the worker is doing the heavy lifting. Without the worker the UI would be blocked. The WASM worker itself is loaded using a separate JS file.
cargo install trunk
)rustup target add wasm32-unknown-unknown
cargo install trunk
cargo install wasm-pack
cargo install wasm-bindgen-cli
trunk serve --open
# or
make server
[!TIP] For optimal performance, run with the release flag:
sh trunk serve --open --release
trunk build --release
# or
make build
The compiled assets will be available in the dist
directory and will look similar to this (doing a ls -1
):
index.html
rusty-pi-cake-2ac9daeecafecafe_bg.wasm
rusty-pi-cake-2ac9daeecafecafe.js
style-5ef594c3beefbeef.css
WebAssembly_Logo.svg
worker_bg.wasm
worker_loader.js
worker.js
This project includes a Makefile with useful commands:
make server
- Start the development servermake build
- Build for productionmake debug
- Build in debug modemake docs
- Generate documentationmake test
- Run testsmake clean
- Clean all generated filesGenerate documentation with:
cargo doc --document-private-items --open
# or
make docs
MIT
Thanks to Steve Klabnik, Carol Nichols, Chris Krycho and the Rust Community for the Rust Book.