wasm-pack, create a Rust library, and compile it into a WebAssembly module ready for the web. By the end, you’ll have a simple “Hello” function exposed to JavaScript.
1. Install Rust via Rustup
Rustup is the official toolchain manager for Rust that keeps your compiler and package manager up to date.PATH:
Make sure you run the installer in a secure environment. The
curl | sh pattern executes remote scripts directly, so verify the source URL before proceeding.2. Verify Rust Installation
After installation, confirm thatrustup, rustc, and cargo are available:
| Tool | Command | Sample Output |
|---|---|---|
| rustup | rustup --version | rustup 1.27.0 (abcdef123 2023-10-05) |
| rustc | rustc --version | rustc 1.74.0 (799716c9 2023-11-13) |
| cargo | cargo --version | cargo 1.74.0 (799716c9 2023-11-13) |
3. Install wasm-pack
wasm-pack streamlines building, testing, and publishing Rust-generated WebAssembly packages.
Ensure that
~/.cargo/bin is in your PATH. You can add this line to your shell profile (.bashrc, .zshrc, etc.):4. Create a New Rust Library Project
Generate a new library namedwasm-project and navigate into it:
5. Configure Cargo.toml for WebAssembly
EditCargo.toml and add a [lib] section to target a WebAssembly system library:
cdylib: instructs Cargo to produce a.wasmsystem library.wasm-bindgen: facilitates seamless interaction between Rust and JavaScript.
6. Write the Rust Code
Opensrc/lib.rs and implement a simple greeting function:
#[wasm_bindgen]exposesgreetto JavaScript.- The test module ensures your function behaves as expected.
7. Build the WASM Package
Compile your project for the web target:pkg/ directory with:
wasm_project_bg.wasm— the compiled WebAssembly binary- JavaScript glue code (
wasm_project.js) to load and call your module package.jsonfor easy NPM integration