Wasm from Rust (wasm-pack) — WebAssembly

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…

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 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;
    }
}

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);
}

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>

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

⚠️ What stops your Rust package from working

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.

What you will learn