Compile Rust to WebAssembly with wasm-pack
Advanced15 minTrending
Build Rust libraries as WebAssembly modules for use in browsers and Node.js with wasm-pack and wasm-bindgen.
Prerequisites
- -Rust toolchain installed via rustup
- -wasm-pack installed
- -Node.js installed (for testing)
Steps
1
Install wasm-pack
Install the tool that builds, tests, and publishes Rust-generated WebAssembly.
$ cargo install wasm-pack
2
Create a new wasm library project
Initialize a library crate configured for WebAssembly output.
$ cargo new --lib my-wasm-lib && cd my-wasm-lib && cargo add wasm-bindgen
3
Configure the crate type
Set the crate type to cdylib in Cargo.toml for WebAssembly compilation.
$ cat >> Cargo.toml << 'EOF'
[lib]
crate-type = ["cdylib", "rlib"]
EOF
4
Write a wasm-bindgen function
Create an exported function that can be called from JavaScript.
$ cat > src/lib.rs << 'EOF'
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
#[wasm_bindgen]
pub fn fibonacci(n: u32) -> u64 {
match n {
0 => 0,
1 => 1,
_ => {
let mut a: u64 = 0;
let mut b: u64 = 1;
for _ in 2..=n {
let temp = b;
b = a + b;
a = temp;
}
b
}
}
}
EOF
5
Build the WebAssembly package
Compile the library to WebAssembly and generate JavaScript bindings.
$ wasm-pack build --target web
Use --target bundler for webpack/Vite projects, --target nodejs for Node.js, or --target web for direct browser use.
Full Script
FAQ
Discussion
Loading comments...