Skip to main content
In this tutorial, you’ll learn how to set up Rust, install 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.
During the interactive installer, select option 1 to proceed with the default installation. Once complete, reload your shell to enable Cargo and Rust in your 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 that rustup, rustc, and cargo are available: If any of these commands fail, revisit the installer instructions or consult the Rust installation guide.

3. Install wasm-pack

wasm-pack streamlines building, testing, and publishing Rust-generated WebAssembly packages.
Wait for compilation to finish; you should see:
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 named wasm-project and navigate into it:
Your directory layout should look like this:

5. Configure Cargo.toml for WebAssembly

Edit Cargo.toml and add a [lib] section to target a WebAssembly system library:
  • cdylib: instructs Cargo to produce a .wasm system library.
  • wasm-bindgen: facilitates seamless interaction between Rust and JavaScript.

6. Write the Rust Code

Open src/lib.rs and implement a simple greeting function:
  • #[wasm_bindgen] exposes greet to JavaScript.
  • The test module ensures your function behaves as expected.

7. Build the WASM Package

Compile your project for the web target:
This creates a pkg/ directory with:
  • wasm_project_bg.wasm — the compiled WebAssembly binary
  • JavaScript glue code (wasm_project.js) to load and call your module
  • package.json for easy NPM integration

8. Inspect the Output

Open your project in an editor (e.g., VS Code). You should see:
In the generated JavaScript, note the import:
You’ve now successfully written Rust code and compiled it into a reusable WebAssembly module!

References

Watch Video

Practice Lab