This example demonstrates how to integrate Rust and WebAssembly into a simple web page, perform a dynamic calculation (
doubling a user-input number), and log information directly to the browser console using console_log
and
wasm-bindgen
.
- Rust→Wasm Compilation: Compile Rust into WebAssembly for performance and type safety.
- Browser Integration: Use JavaScript (ES modules) to load and call exported Rust/Wasm functions.
- Logging: Set up a logger in Rust that prints directly to the browser’s console (
info!
,warn!
, etc.). - User Interaction: Let a user enter a number and display the doubled result.
-
Rust and Cargo:
Install via Rustup. -
wasm-pack:
Install with:cargo install wasm-pack
-
Local Dev Server:
You’ll need a simple HTTP server to serve the files. Python’s built-in server works:python3 -m http.server
Alternatively, you can use serve from npm or another static file server.
.
├─ Cargo.toml
├─ src/
│ └─ lib.rs
├─ index.html
└─ pkg/ (generated by wasm-pack)
- src/lib.rs: Rust code for the Wasm module.
- index.html: Web page integrating the Wasm code.
- pkg/: Generated after building with
wasm-pack
. It contains*.wasm
and JavaScript bindings.
Add the following to your Cargo.toml
:
[package]
name = "dynamic_wasm"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
console_log = "0.2"
log = "0.4"
-
Build the Wasm Module:
wasm-pack build --target web
This command creates the
pkg/
directory containing the WebAssembly.wasm
file and JavaScript bindings. -
Serve the Files:
python3 -m http.server
Or use another static server of your choice.
-
Open the Example in Your Browser: Open
http://localhost:8000
(or the port shown in your terminal).You should see the input field and "Calculate" button. Enter a number and click "Calculate" to see the doubled result.
Open your browser’s Developer Tools (e.g., press F12) and navigate to the "Console" tab. You will see logs like:
Logger initialized!
Received input: 5
Computed result: 10
Each time you click "Calculate," new logs appear corresponding to the input and computed result.