Skip to content

Build tool to use Rust code in Deno and the browser.

License

Notifications You must be signed in to change notification settings

denoland/wasmbuild

Repository files navigation

wasmbuild

A build tool to generate wasm-bindgen glue code for Deno and the browser.

Setup

Add a task to the deno.json file in your project:

{
  "tasks": {
    "wasmbuild": "deno run -A jsr:@deno/wasmbuild@VERSION_GOES_HERE"
  }
}

Scaffold project (Optional)

To create a starter Rust crate in an rs_lib subfolder of your project, run:

deno task wasmbuild new

Building

To build, invoke deno task wasmbuild in your project:

deno task wasmbuild

You can now try it out with deno run mod.js

Bindings will be generated at ./lib/<crate-name>.generated.js. Import the instantiate function and call it asynchronously to get the exports:

import { instantiate } from "./lib/rs_lib.generated.js";

const { add } = await instantiate();
console.log(add(1, 1));

Or instantiate and use the exports:

import { add, instantiate } from "./lib/rs_lib.generated.js";

await instantiate();
console.log(add(1, 1));

Compression

When instantiating, you might want to decompress Wasm bytes.

import { instantiate } from "./lib/rs_lib.generated.js";
import { decompress } from "https://deno.land/x/[email protected]/mod.ts";

await instantiate({
  decompress,
});

Note, however, wasmbuild CLI does not compress the Wasm file automatically.

Custom URL to .wasm file

A custom URL to the .wasm file may be provided by specifying the url option:

import { instantiate } from "./lib/rs_lib.generated.js";

await instantiate({
  url: new URL("./custom_path_to_url.wasm", import.meta.url),
});

Checking output is up-to-date

It may occur that someone updates the Rust code, but forgets to build when submitting a PR. To ensure that the output is up-to-date, you can use the --check flag:

deno task wasmbuild --check

For example, in a GitHub action:

- name: Check Wasm up-to-date
  run: deno task wasmbuild --check

CLI flags

  • --debug - Build without optimizations.
  • --project <crate_name> / -p <crate_name> - Specifies the crate to build when using a Cargo workspace.
  • --out <dir_path> - Specifies the output directory. Defaults to ./lib
  • --js-ext <ext_no_period> - Extension to use for the wasm-bindgen JS file. Defaults to js.
  • --all-features - Build the crate with all features.
  • --no-default-features - Build the crate with no default features.
  • --features - Specify the features to create. Specify multiple features quoted and with spaces (ex. --features "wasm serialization").
  • --sync - Generate a synchronous module that stores the Wasm module inline as base64 text.
  • --skip-opt - Skip running wasm-opt.
  • --check - Checks if the output is up-to-date.
  • --no-cache - Do not generate the code to cache the Wasm file locally.