In Rust, what does `#[wasm_bindgen]` generate for an exported function, and why can a browser not load the `.wasm` that `cargo build` produces directly?
answer
- the raw boundary takes numbers only
- a shim plus descriptor functions
- a second tool reads the descriptors
- wasm-pack runs cargo, then the CLI
basics
~20 s#[wasm_bindgen] wraps the function in an exported shim with a numeric signature (pointers and lengths), plus descriptor functions. The wasm-bindgen CLI, usually run by wasm-pack build, reads them, rewrites the module and writes the JavaScript glue a page imports.
solid answer
~40 sCore WebAssembly functions take and return numbers (plus opaque references with the `reference-types` feature), never strings or slices. So on `pub fn label(filter_name: &str) -> String` the macro generates an exported shim that takes a pointer and a length into linear memory, plus hidden `__wbindgen_describe_*` functions recording the real Rust signature. The crate is a `cdylib` built for `wasm32-unknown-unknown`, and that raw output still imports placeholder functions from a module named `__wbindgen_placeholder__`, which no browser provides. The `wasm-bindgen` CLI interprets the descriptors, rewrites the module and writes a `.js` file (and a `.d.ts`) whose `label` copies the string into memory, calls the shim and decodes the result. `wasm-pack build` runs `cargo build` and then that CLI, at the version `Cargo.lock` records for `wasm-bindgen`.
code
rust · 27 linesuse wasm_bindgen::prelude::*;
/// Turns RGBA pixels grey in place.
#[wasm_bindgen]
pub fn grayscale(pixels: &mut [u8]) {
for px in pixels.chunks_exact_mut(4) {
let y = ((px[0] as u32 * 77 + px[1] as u32 * 150 + px[2] as u32 * 29) >> 8) as u8;
px[..3].fill(y);
}
}
/// Describes a filter for the page's status line.
#[wasm_bindgen]
pub fn label(filter_name: &str) -> String {
format!("{filter_name}: {} bytes of UTF-8", filter_name.len())
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(message: &str);
}
#[wasm_bindgen]
pub fn announce(filter_name: &str) {
log(&label(filter_name));
}go deeper
Recall the two halves: the attribute generates shims and descriptions during compilation, and the CLI that wasm-pack runs turns the module into something JavaScript can import. Know that the browser target is wasm32-unknown-unknown.
Explain why a shim exists at all: the WebAssembly boundary carries numbers, so strings travel as a pointer and a length plus an allocator exported for the glue. Name what the CLI writes: a processed wasm, a JavaScript module and TypeScript declarations.
Show you have debugged the pipeline: a raw module failing on placeholder imports, a CLI and crate schema mismatch, a missing cdylib, and choosing the wasm-pack output target that matches how the page loads code.
Frame the build as a two-step toolchain the team must pin: the crate version in the lockfile drives the CLI version, so CI should build through one tool rather than hand-installed binaries.
## The boundary only speaks numbers A **core WebAssembly function** has a signature made of numeric types (`i32`, `i64`, `f32`, `f64`) and, with the `reference-types` proposal that Rust's wasm targets enable by default, opaque references. There is no string type, no slice type and no struct type at the boundary. A Rust function such as `label(filter_name: &str) -> String` therefore cannot be exported as it stands: JavaScript has a UTF-16 string in its own garbage-collected heap, and Rust can only read bytes in the module's **linear memory**. **wasm-bindgen** closes that gap in two halves: a procedural macro that runs while rustc compiles the crate, and a command-line tool that runs over the compiled `.wasm` afterwards. ## What the attribute expands to For an image-filter crate whose Cargo.toml sets `crate-type = ["cdylib", "rlib"]` and depends on `wasm-bindgen = "0.2"`: ```rust use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn grayscale(pixels: &mut [u8]) { /* ... */ } #[wasm_bindgen] pub fn label(filter_name: &str) -> String { format!("{filter_name}: {} bytes of UTF-8", filter_name.len()) } ``` `#[wasm_bindgen]` on each function generates: - an **exported shim** with a numeric signature, taking pointers, lengths and handles and converting them to `&str`, `&mut [u8]` or `String`; - a **descriptor function** per export (`__wbindgen_describe_label_...` in the compiled module) that encodes the full Rust signature for the CLI to read. The wasm-bindgen crate itself adds support exports used by the glue, such as `__wbindgen_malloc`, `__wbindgen_realloc` and `__wbindgen_free`, so JavaScript can allocate in linear memory. On an `extern "C"` block it does the reverse: `#[wasm_bindgen(js_namespace = console)] fn log(message: &str);` becomes an **import** that Rust calls like a function. ## Why the raw module will not load Built with `cargo build --target wasm32-unknown-unknown --release`, that crate's `.wasm` imports functions from a module named `__wbindgen_placeholder__` (and `__wbindgen_externref_xform__`). No browser supplies those names; they are holes for the second half to fill. A browser or Node instantiation of that raw file fails for want of those imports, and even with them it would only expose numeric shims. ## The second half: the wasm-bindgen CLI The **`wasm-bindgen` CLI** reads the descriptors, wires every import to real JavaScript, rewrites the module and writes: 1. a processed `_bg.wasm` file; 2. a JavaScript module whose `label(name)` encodes the string into linear memory, calls the shim and decodes the returned bytes into a new JavaScript string; 3. a TypeScript `.d.ts` declaring the exported functions with real types. The CLI and the crate must agree on an internal schema: wasm-bindgen-shared's source states that the crate and CLI must carry the same `SCHEMA_VERSION` to work together, which is why the CLI is installed at the crate's exact version. ## One call, end to end Once the CLI has run, a page call such as `label("Sepia")` goes through these steps: 1. the generated `label` function encodes the JavaScript string as UTF-8 into a buffer it allocates through `__wbindgen_malloc`; 2. it calls the numeric shim with that pointer and byte length; 3. the shim builds a `&str` over those bytes and calls the real Rust `label`; 4. Rust returns a `String`, and the shim hands back its pointer and length; 5. the glue decodes those bytes into a new JavaScript string, releases the Rust allocation and returns the string. None of this exists in the module that `cargo build` alone produces: steps 1 and 5 are JavaScript that only the CLI writes, and step 3 is Rust that only the macro writes. That division is the whole reason both halves are needed, and why a crate that compiles cleanly can still fail to load. ## wasm-pack runs both steps **wasm-pack** wraps the pipeline. `wasm-pack build` checks that the crate is a `cdylib`, runs `cargo build` for `wasm32-unknown-unknown`, downloads the CLI at the `wasm-bindgen` version in `Cargo.lock`, runs it, and writes an npm-style package to `pkg/`. With no profile flag it makes a **release** build and runs `wasm-opt -O`; `--dev` and `--profiling` pick the other profiles. Its `--target` flag chooses the shape of the glue: | `--target` | Output | |---|---| | not specified, or `bundler` | ES module for a bundler to consume | | `web` | ES module a browser imports natively; you instantiate the wasm yourself | | `nodejs` | CommonJS module loaded with `require` | | `no-modules` | script that sets a global, fewer wasm-bindgen features | | `deno` | ES module for Deno | ## First-day mistakes - Forgetting `crate-type = ["cdylib"]`: wasm-pack stops and asks for it, because only a `cdylib` produces a standalone module with exports. - Building for a WASI target: the browser build of a wasm-bindgen crate uses `wasm32-unknown-unknown`. - Expecting the macro to write the `.js` file: rustc produces only the `.wasm`; the glue comes from the CLI. - Hand-installing a CLI at a different version from the crate's in `Cargo.lock`.
- Why does the manifest list `crate-type = ["cdylib", "rlib"]` rather than only `cdylib`?A `cdylib` is what produces a standalone `.wasm` with the exported shims, and `wasm-pack build` refuses a crate without it. Adding `rlib` also builds the ordinary Rust library form, so integration tests, doctests and other Rust crates in the workspace can still link against the filter code. The manifest key itself is Cargo's subject; the point here is which artifact the WebAssembly pipeline needs.
- What happens if you install the wasm-bindgen CLI at a different version from the crate in Cargo.lock?The two must share an internal schema: wasm-bindgen-shared's source says the crate and the CLI need the exact same `SCHEMA_VERSION` to work together, and the schema can change in any release. A CLI with a different schema cannot process the module, and version numbers do not show when it moved, so pin the CLI to the `wasm-bindgen` version in `Cargo.lock`, or let `wasm-pack build` do it, since it reads that version from the lockfile and fetches the matching CLI.
- Which `wasm-pack build --target` suits a page that loads the filter with a plain `<script type="module">` and no bundler?`--target web`. It emits an ES module the browser imports natively, but the WebAssembly must be fetched and instantiated by calling the generated initialisation code before the exports are used. The default `bundler` output assumes a bundler resolves the `.wasm` import, and `no-modules` sets a global instead of exporting, with fewer wasm-bindgen features supported.
- Rust exports `&str` and `String` parameters straight into the WebAssembly function signature.
- The `.wasm` from `cargo build` can be fetched and instantiated by a page as it is.
- The `#[wasm_bindgen]` macro writes the JavaScript glue file while rustc compiles.
- Browser builds of a wasm-bindgen crate target `wasm32-wasip1`.
- Any wasm-bindgen CLI version works with any version of the crate.