WASM deployment for Webworker

wasm-bindgen is Rust tool for WebAssembly apps.

Basic Usage

wasm-bindgen requires 3 tools as bellows:

  • Install wasm target to Rust toolchain. rustup target add wasm32-unknown-unknown
  • Add wasm-bindgen to Cargo.toml. cargo add wasm-bindgen
  • Install additional CLI tool. -f flag is for upgrade option. cargo install [-f] wasm-bindgen-cli

Typical Cargo.toml looks like following:

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "=0.2.84"
serde = { version = "1.0", features = ["derive"] }
serde_derive = "1.0"
# You can choose another serializer.
serde-wasm-bindgen = "0.4"

wasm-bindgen and wasm-bindgen-cli require the same version as each other.

In most cases, serde family is required for interfacing between JS objects and Rust types.
serde-wasm-bindgen is optional. It respects native JS object format instead of JSON serializer.

Building wasm takes 2 steps as bellows:

# build wasm
$ cargo build --target wasm32-unknown-unknown --release
# generate Javascript/Typescript wrapper
$ wasm-bindgen target/wasm32-unknown-unknown/release/output.wasm --out-dir dist/

After build, you’ll have generated .js glue code.
Read the .js, and import each function from your main Javascript.

Generated .js will be typically bundled into main code. Wasm should be deployed to the same directory as js.

You can refer The wasm-bindgen Guide for more details.

Web Worker

WebAssembly can be invoked from Web Worker.
Web Worker deployment is mostly same as normal browser build. But there’re several restrictions:

  1. “Classic” worker doesn’t have export
    • You can avoid export statement with building option of output format iife.
    • For example, esbuild has format option including iife
  2. “Classic” worker doesn’t have import.meta
    • If you specify the path arg like await init('./somemod_bg.wasm'), import.meta is not called.

Web Worker has 2 modes of “Classic” and “Module”. wasm-bindgen is assuming “Module” one.
Worker() has {type: 'module'} option, but Safari and Firefox doesn’t support yet.

You can resolve output format issue utilizing JS build tool.
This is all about JS glue, and wasm itself is not different from ordinal build.

Testing

Testing WebAssembly or Web Worker may not work on some configurations.
I confirmed Selenium with Chrome can test with WebAssembly through Web Worker configuration.

⁋ Jul 6, 2022↻ Dec 18, 2024
中馬崇尋
Chuma Takahiro