One command, wasm-pack build, and your Rust code comes out as a pkg/ folder you can import from JavaScript. wasm-pack compiles Rust to .wasm, runs wasm-bindgen to generate the JavaScript in between (the glue code) and TypeScript type files, shrinks the .wasm with wasm-opt, then writes a package.json.
The process is like mountain fruit preserves, a classic souvenir. The fruit is cooked into preserves, put into a bottle with a label and serving instructions, sealed tight, then packed in a shop-labelled box so it is ready for the shelf. The fruit is the Rust code, the bottle and its label are the JavaScript glue code, the tight seal is wasm-opt, the box is the package.json. wasm-pack is the factory that does all of it with one command.
Set up the toolchain
You need Rust (through rustup), the wasm32-unknown-unknown target, and wasm-pack:
rustup target add wasm32-unknown-unknown
curl https://wasm-bindgen.github.io/wasm-pack/installer/init.sh -sSf | sh
wasm-pack --version
# wasm-pack 0.15.0
- Other ways to install wasm-pack:
npm install -g wasm-pack(a ready-made binary) orcargo install wasm-pack(compiled from source, slow). wasm32-unknown-unknownmeans: 32-bit Wasm, with no operating system underneath. This is the target for browsers.- This lesson uses rustc 1.99.0, wasm-pack 0.15.0 and wasm-bindgen 0.2.129.
- The first build takes longer: wasm-pack installs
wasm-bindgen-cliat exactly the version of the wasm-bindgen crate in your project. On this laptop that took about 2 minutes; later builds take under 1 second.
Other options besides wasm-pack:
| Way | When to pick it |
|---|---|
wasm-pack build |
The default in this lesson: one command for compiling, glue code, wasm-opt and package.json. Good for a package used from JavaScript. |
cargo build --target wasm32-unknown-unknown --release, then wasm-bindgen target/wasm32-unknown-unknown/release/mist_homestay.wasm --out-dir pkg --target web, then wasm-opt if needed |
You want to control each step yourself, for example in an existing build script. The wasm-bindgen-cli version must exactly match the wasm-bindgen crate in your project. If they differ, the CLI refuses with the message "different bindgen format". |
Trunk (trunk serve) |
A web app written entirely in Rust. Trunk builds from one source HTML file and has a dev server that reloads the browser by itself. |
The project: mist-homestay
Create the project with cargo new --lib mist-homestay, then change Cargo.toml to this:
[package]
name = "mist-homestay"
version = "0.1.0"
edition = "2024"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
Then src/lib.rs holds the two functions of this track, the price of a stay and the room photo grayscale:
use wasm_bindgen::prelude::*;
/// Cost of a stay at Mist Homestay: nights × price per night (cents).
#[wasm_bindgen(js_name = stayPrice)]
pub fn stay_price(nights: i32, price_per_night: i32) -> i32 {
nights * price_per_night
}
/// Turns a room photo grey, in place in its array (RGBA, 4 bytes per pixel).
#[wasm_bindgen]
pub fn grayscale(pixels: &mut [u8]) {
for px in pixels.chunks_exact_mut(4) {
let gray = ((px[0] as u32 * 77 + px[1] as u32 * 150 + px[2] as u32 * 29) >> 8) as u8;
px[0] = gray;
px[1] = gray;
px[2] = gray;
}
}
crate-type = ["cdylib"]asks Rust for a library other languages can load. Without it no.wasmcomes out.#[wasm_bindgen]marks a function exported to JavaScript.js_name = stayPricechanges its name on the JS side, because Rust style isstay_priceand JS style isstayPrice.i32in Rust becomes anumberin JS, just likei32in WAT.&mut [u8]becomes aUint8Arrayin JS. Its content is copied into Wasm memory, changed, then copied back into the original array.chunks_exact_mut(4)walks 4 bytes at a time, one pixel. The formula is the same as in the JS and WAT versions, so the result is the same byte for byte.
Build with wasm-pack
$ wasm-pack build --target web
[INFO]: 🎯 Checking for the Wasm target...
[INFO]: 🌀 Compiling to Wasm...
Compiling mist-homestay v0.1.0 (/Users/sri/mist-homestay)
Finished `release` profile [optimized] target(s) in 0.48s
[INFO]: ⬇️ Installing wasm-bindgen...
[INFO]: Optimizing wasm binaries with `wasm-opt`...
[INFO]: Optional fields missing from Cargo.toml: 'description', 'repository', and 'license'. These are not necessary, but recommended
[INFO]: ✨ Done in 0.98s
[INFO]: 📦 Your wasm pkg is ready to publish at /Users/sri/mist-homestay/pkg.
(The folder path on your laptop will differ.) The result lands in the pkg/ folder:
| File | Size | What it holds |
|---|---|---|
mist_homestay_bg.wasm |
14,896 bytes | the Rust code, now Wasm |
mist_homestay.js |
5,313 bytes | the glue code: JS functions that call Wasm, and init() |
mist_homestay.d.ts |
1,650 bytes | TypeScript types for stayPrice and grayscale |
package.json |
274 bytes | so this folder can be an npm package |
This is a piece of the glue code wasm-bindgen generated:
export function stayPrice(nights, price_per_night) {
const ret = wasm.stayPrice(nights, price_per_night);
return ret;
}
export function grayscale(pixels) {
var ptr0 = passArray8ToWasm0(pixels, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
wasm.grayscale(ptr0, len0, pixels);
}
stayPricejust passes two numbers on. Nothing needs copying.grayscalereserves room in Wasm memory through__wbindgen_malloc, copies theUint8Arraythere, then calls Wasm. When it is done, Rust copies the result back into the original array through an import wasm-bindgen also generated. The copying cost from the previous lesson is still there, it is just done for you now.
Besides build, wasm-pack also has wasm-pack test (runs tests in Node or a headless browser), wasm-pack pack (makes the package's .tgz file) and wasm-pack publish (uploads it to npm).
Use it in the browser
<script type="module">
import init, { stayPrice, grayscale } from './pkg/mist_homestay.js';
await init(); // download and instantiate mist_homestay_bg.wasm
console.log(stayPrice(2, 3500)); // 7000
const px = new Uint8Array([200, 120, 40, 255]);
grayscale(px);
console.log(px); // Uint8Array(4) [135, 135, 135, 255]
</script>
init()looks formist_homestay_bg.wasmnext to its JS file, then loads it withinstantiateStreaming(falling back toinstantiatewhen the Content-Type is wrong).awaitis allowed directly in a<script type="module">.- Open the page through a local server. From
file://, the browser will not fetch the.wasmfile.
target web, bundler, nodejs
The .wasm file is exactly the same for all three targets (14,896 bytes). Only the glue code differs:
| Target | How the .wasm is loaded |
How you use it |
|---|---|---|
web |
init() fetches it with fetch |
import init, { stayPrice } from './pkg/mist_homestay.js', then await init() |
bundler (the default when --target is left out) |
import * as wasm from "./mist_homestay_bg.wasm", handled by the bundler |
import { stayPrice } from 'mist-homestay' |
nodejs |
require('fs').readFileSync, then new WebAssembly.Module (CommonJS) |
const { stayPrice } = require('./pkg/mist_homestay.js') |
The bundler target needs a bundler that can import .wasm directly, such as webpack 5 with experiments.asyncWebAssembly. In Vite, use a plugin such as vite-plugin-wasm, or use the web target.
File size
| Build | .wasm size |
|---|---|
price.wat through wat2wasm |
47 bytes |
Rust without wasm-bindgen (#[unsafe(no_mangle)] pub extern "C" fn), cargo build --release |
338 bytes, 68 bytes after wasm-strip |
wasm-pack --release, stayPrice only |
13,588 bytes |
wasm-pack --release, stayPrice + grayscale |
14,896 bytes (6,764 bytes with gzip level 9) |
wasm-pack --dev, stayPrice + grayscale |
64,731 bytes |
The function that is 47 bytes in WAT becomes about 14 KB through wasm-pack, while the multiplication itself is still a few bytes. The rest is wasm-bindgen's kit that always comes along: a memory allocator (dlmalloc), a table that holds JS objects, and panic handling. That cost is paid once; adding grayscale only adds 1.3 KB. --dev is bigger because it carries debug info and is not shrunk by wasm-opt.
That is also why Rust is popular for Wasm: Rust needs no garbage collector, so there is no GC runtime to ship, the binary is small, and its tooling (wasm-pack, wasm-bindgen, web-sys) is mature.
📌 The state of wasm-pack and wasm-bindgen since 2025
- July 2025: the Inside Rust blog announced "Sunsetting the rustwasm GitHub org". The Rust and WebAssembly working group had been archived since 2024, and the
rustwasmGitHub organisation was archived in September 2025. - wasm-bindgen (with web-sys and js-sys) moved to a new organisation,
wasm-bindgen, with new additional maintainers. It is active. Used in this lesson: 0.2.129 (as of October 2026). - wasm-pack was first handed to its long-time maintainer, Jesper Håkansson (drager), and 0.14.0 (January 2026) was released from
drager/wasm-pack. The repository then moved again into thewasm-bindgenorganisation: 0.15.0 (May 2026) was released fromgithub.com/wasm-bindgen/wasm-pack, with its docs atwasm-bindgen.github.io/wasm-pack. - Other
rustwasmrepositories, such as gloo and twiggy, were archived or handed to their own maintainers.
⚠️ What stops your Rust package from working
- Forgetting
crate-type = ["cdylib"]. wasm-pack stops withError: crate-type must be cdylib to compile to WebAssembly. Add the following to your Cargo.toml file:and then suggests[lib]andcrate-type = ["cdylib", "rlib"]. - Calling a function before
await init(). The glue code has no Wasm module yet. In Chrome:TypeError: Cannot read properties of undefined (reading 'stayPrice'). - Overflow differs between
--devand--release.stayPrice(700000, 3500)in a--releasebuild silently becomes-1844967296. In a--devbuild, Rust checks for overflow and panics, which reaches JS asRuntimeError: unreachable. For big numbers, usei64orchecked_mul. - Opening the page through
file://.init()needsfetch, so the page has to be opened through a server.
TL;DR: wasm-pack turns a Rust crate into a package for JavaScript: cargo builds for wasm32-unknown-unknown, wasm-bindgen generates the JS glue code and .d.ts, wasm-opt shrinks the .wasm, and a package.json is written. You need crate-type = ["cdylib"] and the wasm-bindgen dependency; exported functions get #[wasm_bindgen] (js_name renames them). wasm-pack build --target web is used with import init, { stayPrice } from './pkg/mist_homestay.js' and await init(); the bundler target (the default) is for bundlers, nodejs for require in Node. A &mut [u8] is copied in and out for you. Sizes: stayPrice + grayscale is 14,896 bytes with --release and 64,731 bytes with --dev, mostly wasm-bindgen's kit. wasm-pack also has test, pack and publish. Since 2025 the rustwasm organisation is archived; wasm-bindgen, and now wasm-pack, are maintained in the wasm-bindgen organisation.
⚡ One command, one package
Write:
$ wasm-pack build --target web
Meaning: wasm-pack compiles Rust to .wasm, runs wasm-bindgen to generate the JavaScript glue code and TypeScript type files, shrinks the .wasm with wasm-opt, then writes a package.json into the pkg/ folder. Besides build, it also has test, pack and publish.
⚡ Mark the function for JavaScript
Write:
#[wasm_bindgen(js_name = stayPrice)]
pub fn stay_price(nights: i32, price_per_night: i32) -> i32 {
nights * price_per_night
}
Meaning: #[wasm_bindgen] exports the function to JavaScript, and js_name changes its name on the JS side. Cargo.toml must have crate-type = ["cdylib"], or no .wasm comes out.
⚡ Wait for init first
Write:
<script type="module">
import init, { stayPrice, grayscale } from './pkg/mist_homestay.js';
await init(); // download and instantiate mist_homestay_bg.wasm
console.log(stayPrice(2, 3500)); // 7000
</script>
Guess first: what happens if the await before init() is removed?
stayPrice is called before the glue code has a Wasm module, and Chrome throws TypeError: Cannot read properties of undefined (reading 'stayPrice').
Meaning: The web target has an init() that fetches the .wasm, so the page has to be opened through a server, not from file://.
⚡ 47 bytes become about 14 KB
Guess first: the multiplication is only 47 bytes in WAT. How big is it through wasm-pack --release?
14,896 bytes for stayPrice + grayscale. Most of it is wasm-bindgen's kit: a memory allocator, a table for JS objects and panic handling.
Meaning: That cost is paid once: adding grayscale only adds 1.3 KB. Rust needs no garbage collector, so the binary stays small.