First Rust→Wasm Module
local graph
Chapter 3 — First Rust→Wasm Module
Section titled “Chapter 3 — First Rust→Wasm Module”Chapter 3 – First Rust→Wasm Module
Section titled “Chapter 3 – First Rust→Wasm Module”In this chapter, we’ll build, bind, and bundle your very first Rust→Wasm component. You’ll see interop in action with a minimal “Hello, Browser!” example, dive into the generated JS glue via wasm-bindgen, and wrap everything up as a local npm package for seamless import.
3.1: “Hello, Browser!” Walkthrough
Section titled “3.1: “Hello, Browser!” Walkthrough”You’ll learn each step—from scaffolding the crate to wiring up the HTML page—with clear code examples, a simple flowchart, and a personal tip to keep you cruising.
A. High-Level Flow
Section titled “A. High-Level Flow”flowchart TD
A[Scaffold Rust Crate] —> B[Write greet Function]
B —> C[Build & Bind with wasm-pack]
C —> D[Inspect pkg/ Artifacts]
D —> E[Import & Invoke in index.js]
E —> F[Serve and Interact]
---
### B. Step 1: Scaffold the Library
#### 1. Create a new library crate
```bashcargo new hello_browser --libcd hello_browser2. Configure Cargo.toml
Section titled “2. Configure Cargo.toml”[package]name = "hello_browser"version = "0.1.0"edition = "2021"
[lib]crate-type = [“cdylib”] # Emit a C-compatible dynamic library for Wasm
[dependencies] wasm-bindgen = “0.2” # JS/Rust interop helpers
Insight: Using cdylib ensures the compiler produces a .wasm suitable for wasm-bindgen’s bindings.
C. Step 2: Write the Greet Function
In src/lib.rs, expose a simple Rust function to JavaScript:
rust use wasm_bindgen::prelude::*;
/// Greets the user by name. /// Returns: “Hello, {name}! Welcome to Rust-Wasm.” #[wasm_bindgen] pub fn greet(name: &str) -> String { format!(“Hello, {}! Welcome to Rust-Wasm.”, name) }
- #[wasm_bindgen] marks it for export.- We return a String, showing how to marshal Rust’s heap-allocated data back into JS.
---
D. Step 3: Build & Bind with wasm-pack
From the crate root:
```bashwasm-pack build --target web --out-dir ../www/pkg--target web: Generates ES modules for browsers.--out-dir ../www/pkg: Places artifacts in your www folder for hosting.
Artifacts in www/pkg/:
- hello_browser_bg.wasm
<!-- page: 031 -->
- hello_browser.js (glue code)- hello_browser.d.ts (TypeScript types)
**Expert Commentary:**
wasm-pack runs cargo build, then pipes the .wasm through wasm-bindgen-cli, and finally scaffolds an npm package in one shot—no manual wiring required.
---
### E. Step 4: Inspect the Generated Glue
Open www/pkg/hello_browser.js and locate the exported wrapper:
```javascriptexport function greet(name) { const ptr = passStringToWasm(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); const len = WASM_VECTOR_LEN; const retPtr = wasm.greet(ptr, len); const result = getStringFromWasm(retPtr, WASM_VECTOR_LEN); wasm.__wbindgen_free(retPtr, WASM_VECTOR_LEN); return result;}passStringToWasm: Encodes JS string → UTF-8 bytes in Wasm memory.wasm.greet(ptr, len): Calls the low-level Rust function.getStringFromWasm: Reads back the returned UTF-8 bytes → JS string.__wbindgen_free: Cleans up Wasm memory to prevent leaks.
F. Step 5: Wire Up the Frontend
Section titled “F. Step 5: Wire Up the Frontend”- Create www/index.html
<!DOCTYPE html><html> <body> <input id="name" placeholder="Enter your name" /> <button id="btn">Greet</button> <p id="msg">Waiting...</p> <script type="module" src="./index.js"></script> </body></html>- Implement www/index.js
import init, { greet } from ”./pkg/hello_browser.js”;
async function main() { await init(); // Load and instantiate the Wasm module
document.getElementById("btn").onclick = () => { const name = document.getElementById("name").value || "stranger"; const message = greet(name); document.getElementById("msg").textContent = message;};}
main();
G. Step 6: Serve and Interact
From the www/ directory, run a static server:
npx serve
- Navigate to http://localhost:5000 (or as indicated).
- Type your name, click Greet, and watch Rust code deliver your personalized message almost instantly.
Case Study: In an early prototype of a chat widget, swapping a JavaScript formatter for a Rust→Wasm version cut response lag by 40 ms per message—enough to make the interface feel snappier under heavy load.
Key Takeaways
- Scaffold a library crate with cdylib crate type.
- Export functions via #[wasm_bindgen] for seamless JS calls.
- Build and bind with a single wasm-pack command.
- Inspect the glue to understand data marshaling.
- Integrate on the frontend with standard ES module imports.
3.2: Generating JS Glue with wasm-bindgen
Section titled “3.2: Generating JS Glue with wasm-bindgen”When you compile Rust to WebAssembly, you get a raw .wasm binary—but browsers can’t magically call arbitrary functions in that binary without some “glue” to marshal data and manage memory. That’s where wasm-bindgen comes in
A. Why JS Glue Is Necessary
Section titled “A. Why JS Glue Is Necessary”-
Data Representation Differences
Rust’sString,Vec<T>, and complex structs live in Wasm linear memory. JavaScript needs helpers to copy data in and out. -
Memory Management
Wasm has no garbage collector; glue code must allocate and free memory explicitly. -
Function Indexing
Exports in Wasm are identified by numeric indices; glue code maps human-readable names to those indices.
B. How wasm-bindgen Works
Section titled “B. How wasm-bindgen Works”flowchart TB
RustSource[Rust source code] —>|cargo build| WasmBinary[.wasm]
WasmBinary —>|wasm-bindgen| GlueJS[.js wrappers + .d.ts]
GlueJS & WasmBinary —>|package| npmPackage
npmPackage —> JavaScriptApp[Import and use in JS]
- Compile your crate to
wasm32-unknown-unknown. - Run
wasm-bindgenon the.wasmto generate JS/TS bindings. - Bundle the resulting files into an npm-style package.
- Import and call exported functions naturally from JavaScript.
C. Manual Invocation vs. wasm-pack
| Step | Manual Commands | wasm-pack Equivalent |
|---|---|---|
| Compile to Wasm | cargo build --target wasm32-unknown-unknown --release | Implicit in wasm-pack build |
| Generate JS glue | wasm-bindgen target/.../your_crate.wasm --outdir pkg --target web | Implicit in wasm-pack build |
| Bundle for npm | Manual cp + package.json edits | Handled by wasm-pack build |
| Run tests in browser | n/a | wasm-pack test --headless --chrome |
Pro Tip: When you need fine-grained control—custom memory allocators, non-standard targets—run wasm-bindgen manually. For day-to-day work, let wasm-pack handle the plumbing.
D. Anatomy of the Generated Glue Code
Let’s look at a snippet from pkg/your_crate.js after running:
js
wasm-bindgen target/wasm32-unknown-unknown/release/your_crate.wasm
—outdir pkg —target web
import * as wasm from ”./your_crate_bg.wasm”;
const cachedTextDecoder = new TextDecoder(“utf-8”, { ignoreBOM: true, fatal: true }); let cachegetUint8Memory0 = null; function getUint8Memory0() { if (cachegetUint8Memory0 === null) { cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer); } return cachegetUint8Memory0; }
function getStringFromWasm(ptr, len) {
<!-- page: 035 -->
returncachedTextDecoder.decode(getUint8Memory0().subarray(ptr,ptr + len));}
export function greet(name) {// 1. Encode JS string into Wasm memoryconst buf = cachedTextEncoder.encode(name);const ptr = wasm.__wbindgen_malloc(buf.length);getUint8Memory0().set(buf, ptr);
// 2. Call the Rust functionconst len = buf.length;const retPtr = wasm.greet(ptr, len);
// 3. Decode the returned stringconst result = getStringFromWasm(retPtr,WASM_VECTOR_LEN);
// 4. Free Wasm memorywasm.__wbindgen_free(retPtr, WASM_VECTOR_LEN);
return result;}
- TextEncoder / TextDecoder handle UTF-8 conversions.- Memory Caches (getUint8Memory0) avoid recreating views on every call.- __wbindgen_malloc / __wbindgen_free come from the Rust side, ensuring aligned allocation.- WASM_VECTOR_LEN is a helper that tracks the length of the last pass-through buffer.
---
E. Advanced Patterns
1. Passing Numeric Arrays
#[wasm_bindgen]pub fn sum_array(numbers: &[i32]) -> i32 { numbers.iter().sum()}
Glue snippet:
export function sum_array(ptr, len) {
<!-- page: 036 -->
const nums = new Int32Array(wasm.memory.buffer, ptr, len);return wasm.sum_array(ptr, len);}
2. Callbacks from Rust to JS
#[wasm_bindgen]extern "C" { #[wasm_bindgen(js_namespace = console)] fn log(s: &str);}
#[wasm_bindgen]pub fn process_and_log(x: i32) { log(&format!("Processing value: {}", x));}
3. Complex Structs
#[wasm_bindgen]pub struct Point { x: f64, y: f64 }
#[wasm_bindgen]impl Point { #[wasm_bindgen(constructor)] pub fn new(x: f64, y: f64) -> Point { Point { x, y } } #[wasm_bindgen] pub fn magnitude(&self) -> f64 { (self.x.powi(2) + self.y.powi(2)).sqrt() }}
The glue code creates a JS class `Point` that wraps the necessary pointers and methods.
**Case Study:** In a data-visualization tool, exporting a Rust struct representing geometry eliminated thousands of lines of manual parsing in JS—wasm-bindgen’s automated class wrappers made the API intuitive and type-safe.
<!-- page: 037 -->
F. Personal Insight & Tips
- Keep exports focused. Only annotate functions and types you actually need in JS—excess exports bloat your glue code.- Watch your bundle size. Inspect `pkg/`—if it feels large, enable Link Time Optimization (LTO) and size-oriented profiles in `Cargo.toml`.- Read the glue. Even if you don’t tweak it, understanding how strings and memory move between realms is invaluable for debugging.
---
Summary
- wasm-bindgen transforms raw Wasm into a developer-friendly JS API.- Manual vs. automated flows trade control for convenience.- The generated glue handles UTF-8, memory, and function indexing seamlessly.- Advanced patterns let you pass arrays, callbacks, and structs as first-class citizens.
---
3.3: Publishing a Local npm Package
When you’ve built and bound your Rust→Wasm module, it often makes sense to treat it like any other npm library—especially during development. Publishing locally via `npm link` lets you iterate on your Rust code and immediately consume updates in your frontend app without bumping versions or pushing to a registry. Let’s walk through a concise, reliable workflow.
A. Why Local Publishing Matters
- Instant feedback loop: Make a change in Rust, rebuild, and see it in your UI without republishing.
<!-- page: 038 -->
- **No version churn**: Avoid repeatedly incrementing `package.json` versions for every tweak.- **Real-world simulation**: You work with the package exactly as a consumer would, surfacing any integration issues early.
---
### B. Workflow Overview
**flowchart LR**A[Build Wasm Package] —> B[Add package.json to pkg/]
B —> C[npm link (in pkg/)]
C —> D[npm link
---
### C. Step-by-Step Guide
#### 1. Build Your Wasm Package
From your crate root:
```bash2. wasm-pack build --target bundler --out-dir www/pkg--target bundlerproduces a package suitable for bundlers (Webpack, Rollup, Vite).www/pkg/now contains.wasm, JS glue, and.d.ts.
3. Create a package.json Stub
Section titled “3. Create a package.json Stub”In www/pkg/, add a minimal package.json so npm recognizes it:
{ "name": "rust-wasm-demo", "version": "0.1.0", "main": "hello_browser.js", "files": [ "hello_browser.js", "hello_browser_bg.wasm", "hello_browser.d.ts" ], "type": "module"}- name: The npm import path your app will use.
- main: Entry point JS file.
- files: Whitelist only the essential artifacts.
4. Link the Package Locally
Section titled “4. Link the Package Locally”| cd www/pkg| npm link |
This makes rust-wasm-demo available globally on your machine as a symlink.
5. Consume in Your Frontend App
Section titled “5. Consume in Your Frontend App”In your main project directory:
npm link rust-wasm-demo
Now you can import:
import init, { greet } from "rust-wasm-demo";7. Iterate Quickly
Section titled “7. Iterate Quickly”- Rebuild your Rust code:
cd path/to/hello_browserwasm-pack build --target bundler --out-dir www/pkg
- Your frontend automatically picks up updated artifacts via the symlink.
8. Cleanup When Finished
Section titled “8. Cleanup When Finished”# In your frontend appnpm unlink rust-wasm-demo
# In pkg foldernpm unlinkThis restores your npm environment to its pre-linked state.
D. Case Study: Zero-Downtime Dev Loop
Section titled “D. Case Study: Zero-Downtime Dev Loop”In one project, I was optimizing a core data transformation function in Rust. By using npm link, I avoided the tedious cycle of publishing to a private registry, updating version numbers, and reinstalling. Instead, I ran wasm-pack build five times in an afternoon—and each change reflected instantly in the browser. This workflow shaved hours off my development time.
E. Tips & Troubleshooting
Section titled “E. Tips & Troubleshooting”- Ensure clean builds: Sometimes stale files linger in
pkg/. Runrm -rf pkg/*before rebuilding. - Version consistency: Keep the
versionfield inpackage.jsonaligned with your crate’sCargo.tomlto avoid confusion. - Symlink quirks on Windows: Use an elevated command prompt or Git Bash to ensure
npm linksucceeds without permission errors.
Key Takeaways
Section titled “Key Takeaways”npm linkbridges your local Wasm package and frontend, delivering an instant feedback loop.- A minimal
package.jsoninpkg/makes your Wasm artifacts behave like any npm module. - Clean up with
npm unlinkwhen you’re done to restore your environment.
With this local-publishing setup, you’re now ready to develop your Rust→Wasm library as if it were any other JavaScript dependency.