Technical Documentation: wasm-bindgen/wasm-pack
โน๏ธ Provenance: Hybrid Fusion:
wasm-bindgen/wasm-pack(README + 10 In-Tree Chapters) ยท CodeWiki Reference ยท Recency: Active (< 180 days)
1. Project Overview & Quickstart (wasm-bindgen/wasm-pack)
About
This tool seeks to be a one-stop shop for building and working with rust-
generated WebAssembly that you would like to interop with JavaScript, in the
browser or with Node.js. wasm-pack helps you build rust-generated
WebAssembly packages that you could publish to the npm registry, or otherwise use
alongside any javascript packages in workflows that you already use, such as webpack.
๐ฎ Prerequisites
This project requires Rust 1.30.0 or later.
โก Quickstart Guide
Visit the quickstart guide in our documentation.
๐๏ธ Commands
new: Generate a new RustWasm project using a templatebuild: Generate an npm wasm pkg from a rustwasm cratetest: Run browser testspackandpublish: Create a tarball of your rustwasm pkg and/or publish to a registry
๐ Logging
wasm-pack uses env_logger to produce logs when wasm-pack runs.
To configure your log level, use the RUST_LOG environment variable. For example:
RUST_LOG=info wasm-pack build๐ฏ Contributing
Read our guide on getting up and running for developing wasm-pack, and
check out our contribution policy.
๐คนโโ๏ธ Governance
This project was started by ashleygwilliams and is maintained by drager.
2. In-Tree Documentation Chapters (wasm-bindgen/wasm-pack)
File: README.md
About
This tool seeks to be a one-stop shop for building and working with rust-
generated WebAssembly that you would like to interop with JavaScript, in the
browser or with Node.js. wasm-pack helps you build rust-generated
WebAssembly packages that you could publish to the npm registry, or otherwise use
alongside any javascript packages in workflows that you already use, such as webpack.
๐ฎ Prerequisites
This project requires Rust 1.30.0 or later.
โก Quickstart Guide
Visit the quickstart guide in our documentation.
๐๏ธ Commands
new: Generate a new RustWasm project using a templatebuild: Generate an npm wasm pkg from a rustwasm cratetest: Run browser testspackandpublish: Create a tarball of your rustwasm pkg and/or publish to a registry
๐ Logging
wasm-pack uses env_logger to produce logs when wasm-pack runs.
To configure your log level, use the RUST_LOG environment variable. For example:
RUST_LOG=info wasm-pack build๐ฏ Contributing
Read our guide on getting up and running for developing wasm-pack, and
check out our contribution policy.
๐คนโโ๏ธ Governance
This project was started by ashleygwilliams and is maintained by drager.
File: docs/src/commands/build.md
wasm-pack build
The wasm-pack build command creates the files necessary for JavaScript
interoperability and for publishing a package to npm. This involves compiling
your code to wasm and generating a pkg folder. This pkg folder will contain the
wasm binary, a JS wrapper file, your README, and a package.json file.
The pkg directory is automatically .gitignored by default, since it contains
build artifacts which are not intended to be checked into version
control.0 You can disable this with the--no-gitignore flag.
Path
The wasm-pack build command can be given an optional path argument, e.g.:
wasm-pack build examples/js-hello-worldThis path should point to a directory that contains a Cargo.toml file. If no
path is given, the build command will run in the current directory.
Output Directory
By default, wasm-pack will generate a directory for its build output called pkg.
If you'd like to customize this you can use the --out-dir flag.
wasm-pack build --out-dir outThe above command will put your build artifacts in a directory called out, instead
of the default pkg.
Generated file names
Flag --out-name sets the prefix for output file names. If not provided, package name is used instead.
Usage examples, assuming our crate is named dom:
wasm-pack build
# will produce files
# dom.d.ts dom.js dom_bg.d.ts dom_bg.wasm package.json README.md
wasm-pack build --out-name index
# will produce files
# index.d.ts index.js index_bg.d.ts index_bg.wasm package.json README.mdProfile
The build command accepts an optional profile argument: one of --dev,--profiling, or --release. If none is supplied, then --release is used.
This controls whether debug assertions are enabled, debug info is generated, and
which (if any) optimizations are enabled.
| Profile | Debug Assertions | Debug Info | Optimizations | Notes |
|---|---|---|---|---|
--dev |
Yes | Yes | No | Useful for development and debugging. |
--profiling |
No | Yes | Yes | Useful when profiling and investigating performance issues. |
--release |
No | No | Yes | Useful for shipping to production. |
The --dev profile will build the output package using cargo's default
non-release profile. Building this way is
faster but applies few optimizations to the output, and enables debug assertions
and other runtime correctness checks. The --profiling and --release profiles
use cargo's release profile, but the former enables debug info as well, which
helps when investigating performance issues in a profiler.
The exact meaning of the profile flags may evolve as the platform matures.
Target
The build command accepts a --target argument. This will customize the JS
that is emitted and how the WebAssembly files are instantiated and loaded. For
more documentation on the various strategies here, see the documentation on
using the compiled output.
wasm-pack build --target nodejs| Option | Usage | Description |
|---|---|---|
not specified or bundler |
Bundler | Outputs JS that is suitable for interoperation with a Bundler like Webpack. You'll import the JS and the module key is specified in package.json. sideEffects: false is by default. |
nodejs |
Node.js | Outputs JS that uses CommonJS modules, for use with a require statement. main key in package.json. |
web |
Native in browser | Outputs JS that can be natively imported as an ES module in a browser, but the WebAssembly must be manually instantiated and loaded. |
no-modules |
Native in browser | Same as web, except the JS is included on a page and modifies global state, and doesn't support as many wasm-bindgen features as web |
deno |
Deno | Outputs JS that can be natively imported as an ES module in deno. |
Scope
The build command also accepts an optional --scope argument. This will scope
your package name, which is useful if your package name might conflict with
something in the public registry. For example:
wasm-pack build examples/js-hello-world --scope testThis command would create a package.json file for a package called@test/js-hello-world. For more information about scoping, you can refer to
the npm documentation here.
Mode
The build command accepts an optional --mode argument.
wasm-pack build examples/js-hello-world --mode no-install| Option | Description |
|---|---|
no-install |
wasm-pack build implicitly and create wasm binding without installing wasm-bindgen. |
normal |
do all the stuffs of no-install with installed wasm-bindgen. |
Extra options
The build command can pass extra options straight to cargo build even if
they are not supported in wasm-pack. To use them simply add the extra arguments
at the very end of your command, just as you would for cargo build. For
example, to build the previous example using cargo's offline feature:
wasm-pack build examples/js-hello-world --mode no-install -- --offlineSkip .gitignore
By default, wasm-pack creates a .gitignore file in the output directory
containing *, which prevents the build artifacts from being checked into
version control. If you want to commit the pkg directory to your repository
(e.g. for GitHub Pages, Deno packages, or monorepo setups), you can use the--no-gitignore flag to skip generating the .gitignore file:
wasm-pack build --no-gitignoreThis is also available with --target web and other targets.
Panic strategy
By default, Rust panics in WebAssembly compile with panic=abort, which aborts
the WebAssembly instance on panic. The --panic-unwind flag changes this so
panics can be caught at FFI boundaries and converted to JavaScript exceptions
by tools like wasm-bindgen's catch-unwind support.
wasm-pack build --panic-unwindThis flag:
- Invokes
cargowith the nightly toolchain (cargo +nightly build). - Adds
-Z build-std=std,panic_unwindto rebuildstdwith unwinding
support. - Sets
RUSTFLAGS=-Cpanic=unwind(preserving any user-providedRUSTFLAGS). - Passes
--enable-exception-handlingtowasm-optso the optimiser accepts
the exception-handling instructions unwinding compiles to.
The first time you use --panic-unwind, wasm-pack will install any missing
prerequisites via rustup:
- The nightly toolchain
- The
rust-srccomponent for nightly - The
wasm32-unknown-unknowntarget for nightly
If you are not using rustup you must install these prerequisites manually.
See Non-rustup setups.
Note:
wasm-packonly handles producing the.wasm. The actual
"panic = recoverable JavaScript exception" behaviour requires runtime glue
from your bindings layer (e.g.wasm-bindgen's catch-unwind feature). With
just--panic-unwindand no runtime glue, panics still terminate the
instance โ they are merely unwound rather than aborted.
--panic-unwind is also available for wasm-pack test.
64-bit WebAssembly (`wasm64-unknown-unknown`)
The cargo target triple is the source of truth for which WebAssembly ABIwasm-pack builds. To produce a memory64 binary, declare the target the
cargo-native way โ either in .cargo/config.toml:
# .cargo/config.toml
[build]
target = "wasm64-unknown-unknown"or as an extra cargo argument:
wasm-pack build -- --target wasm64-unknown-unknownor via CARGO_BUILD_TARGET=wasm64-unknown-unknown in the environment.
wasm64-unknown-unknown is a tier-3 Rust target, so rustup
has no prebuilt artifacts for it. You need to provide two pieces yourself
via cargo's native config:
A nightly toolchain โ
rust-toolchain.tomlis the cargo-native
way to pin one to your project:toml# rust-toolchain.toml [toolchain] channel = "nightly" components = ["rust-src"]Or set
RUSTUP_TOOLCHAIN=nightlyfor one-off invocations.-Z build-stdto buildstdfrom source, since there is no
prebuilt one. Add to your.cargo/config.toml:toml[unstable] build-std = ["std", "panic_abort"]Or pass
-Z build-std=std,panic_abortas an extra cargo argument.
wasm-pack itself stays out of the cargo invocation โ it does not inject+nightly or -Z build-std (those would override your toolchain pin or
surprise users who hadn't intended a nightly build). What it does do when
it sees a wasm64-* triple:
- Verifies the active toolchain is nightly, with a helpful error pointing
at the config above if it isn't. - Installs the
rust-srccomponent for the active toolchain viarustup
if missing. - Does not attempt
rustup target add wasm64-*(which would always
fail for a tier-3 target). - Passes
--enable-memory64towasm-optso the optimiser accepts
64-bit memories and tables.
0 If you need to include additional assets in the pkg
directory and your NPM package, we intend to have a solution for your use case
soon. You can use --no-gitignore to omit the .gitignore file in the
meantime. โฉ
File: docs/src/commands/index.md
Commands
wasm-pack has several commands to help you during the process of building
a Rust-generated WebAssembly project.
new: This command generates a new project for you using a template. Learn morebuild: This command builds apkgdirectory for you with compiled wasm and generated JS. Learn morepackandpublish: These commands will create a tarball, and optionally publish it to a registry, such as npm. Learn more
Deprecated Commands
init: This command has been deprecated in favor ofbuild.
Log levels
By default wasm-pack displays a lot of useful information.
You can cause it to display even more information by using --verbose, or you can silence all stdout by using --quiet.
You can also use --log-level to have fine-grained control over wasm-pack's log output:
--log-level infois the default, it causes all messages to be logged.--log-level warncauses warnings and errors to be displayed, but not info.--log-level errorcauses only errors to be displayed.
These flags are global flags, so they can be used with every command, and they must come before the command:
wasm-pack --log-level error build
wasm-pack --quiet build
wasm-pack --verbose buildFile: docs/src/commands/init.md
wasm-pack init (DEPRECATED)
This command has been deprecated in favor of build, which does the same thing, but is
a much more representative name for the command. Read the docs for build.
File: docs/src/commands/new.md
wasm-pack new
The wasm-pack new command creates a new RustWasm project for you,
using cargo-generate under the hood.
It takes 3 parameters, name, template, and mode:
wasm-pack new <name> --template <template> --mode <normal|noinstall|force>The default template is wasm-bindgen/wasm-pack,
which includes the wasm-pack-template cargo-generate template.
Name
The wasm-pack new command must be given a name argument, e.g.:
wasm-pack new myprojectTemplate
The wasm-pack new command can be given an optional template argument, e.g.:
wasm-pack new myproject --template https://github.com/wasm-bindgen/wasm-packThe template can be an address to a git repo that contains a cargo-generate
template.
Mode
The wasm-pack new command can be given an optional mode argument, e.g.:
wasm-pack new myproject --mode noinstallThe mode passed can be either "normal", "noinstall", or "force". "normal" is passed by
default.
noinstall means that wasm-pack should not attempt to install any underlying tools.
If a necessary tool cannot be found, the command will error.
force means that wasm-pack should not check the local Rust version. If a local Rust
is an unacceptable Rust version, the command will error.
File: docs/src/commands/pack-and-publish.md
pack and publish
The publish and pack commands interact with the pkg directory that's
created when you run wasm-pack build. The pack command creates a tarball
from the pkg directory and the publish command creates a tarball from the
pkg directory and publishes it to the NPM registry.
Underneath, these commands use npm pack and npm publish. You can read
more about these in the NPM documentation:
Both these commands take the path to the pkg directory as the first argument.
You can either set the argument directly to the pkg directory or to the parent
of the pkg directory:
$ wasm-pack pack myproject/pkg
| ๐ packed up your package!
$ wasm-pack pack myproject
| ๐ packed up your package!If you try to call pack or publish on another directory, you get an error:
$ wasm-pack pack myproject/src/
Unable to find the pkg directory at path 'myproject/src/', or in a child directory of 'myproject/src/'If you don't set a path, they use the current directory as the path.
Publishing tagged releases
You can also publish tagged releases with the optional --tag argument, e.g.
wasm-pack publish --tag nextBy default, the latest tag is used to identify the current version of a package,
and npm install \ (without any @<version> or @<tag> specifier) installs the latest tag.
You can read more about distribution tags on NPM.
File: docs/src/commands/test.md
wasm-pack test
The wasm-pack test command wraps the wasm-bindgen-test-runner
CLI allowing you to run wasm tests in different browsers without needing to install the different
webdrivers yourself.
wasm-pack test --helpPath
The wasm-pack test command can be given an optional path argument.
This path should point to a directory that contains a Cargo.toml file. If no
path is given, the test command will run in the current directory.
# Run tests for the current directory's crate
wasm-pack test
# Run tests for a specified crate
wasm-pack test crates/crate-in-my-workspaceProfile
The test command accepts an optional profile argument: --release.
If none is supplied, then a debug test build will be used.
Test environment
Choose where to run your tests by passing in any combination of testing environment flags.
--headless is useful for running browser tests in a headless browser as part of a CI process.
wasm-pack test --node --firefox --chrome --safari --headlessPanic strategy
The test command accepts the --panic-unwind flag, which builds the test
binary with panic=unwind via the nightly toolchain and -Z build-std. See
the build command's documentation for details.
wasm-pack test --node --panic-unwindExtra options
The test command can pass extra options straight to cargo test even if they are not
supported in wasm-pack.
To use them simply add the extra arguments at the very end of your command, just
as you would for cargo test.
cargo test -h for a list of all options that you can pass through.
Running only some tests
When debugging a specific issue, you may find yourself wanting to run a subset of tests, instead of your entire suite of tests.
Here are a few examples of how to run a subset of your tests:
# Example directory structure
$ tree crates/foo
โโโ Cargo.toml
โโโ README.md
โโโ src
โย ย โโโ diff
โย ย โย ย โโโ diff_test_case.rs
โย ย โย ย โโโ mod.rs
โย ย โโโ lib.rs
โโโ tests
โโโ diff_patch.rs
ย ย โโโ node.rs# Run all tests in tests/diff_patch.rs in Firefox
wasm-pack test crates/foo --firefox --headless --test diff_patch
# Run all tests in tests/diff_patch.rs that contain the word "replace"
wasm-pack test crates/foo --firefox --headless --test diff_patch replace
# Run all tests inside of a `tests` module inside of src/lib/diff.rs
wasm-pack test crates/foo --firefox --headless --lib diff::tests
# Same as the above, but only if they contain the word replace
wasm-pack test crates/foo --firefox --headless --lib diff::tests::replaceNote that you can also filter tests by location in which they're supposed to
run. For example:
# Run all tests which are intended to execute in Node.js
wasm-pack test --node
# Run all tests which are intended to be executed in a browser
wasm-pack test --firefox --headlessFile: docs/src/prerequisites/considerations.md
nodejs
Currently, wasm-pack generated npm modules require you to have the fetch polyfill in your node project.
If there is a module from wasm-pack build --target nodejs you may encounter some errors regarding global Headers, Request, Response and fetch Web APIs.
Common errors:
ReqwestError(reqwest::Error { kind: Builder, source: "JsValue(ReferenceError: Headers is not defined
ReqwestError(reqwest::Error { kind: Builder, source: "JsValue(ReferenceError: Request is not defined
var ret = getObject(arg0) instanceof Response;
ReferenceError: Response is not definedWorkaround
Import or declare fetch and objects: Headers, Request, Response
// CommonJS
const fetch = require('node-fetch');
// ES Module
import fetch from 'node-fetch';
// @ts-ignore
global.fetch = fetch;
// @ts-ignore
global.Headers = fetch.Headers;
// @ts-ignore
global.Request = fetch.Request;
// @ts-ignore
global.Response = fetch.Response;File: docs/src/prerequisites/index.md
Prerequisites
First you'll want to install the wasm-pack CLI, and wasm-pack -V should print the version that you just installed.
Next, since wasm-pack is a build tool, you'll want to make sure you have
Rust installed. Make sure rustc -V prints out at least 1.30.0.
Finally, if you're using wasm-pack to publish to NPM, you'll want
to install and configure npm. In the future, we intend to rewrite the
npm registry client bits so that the need for a Node runtime is eliminated. If
you're excited about that work- you should reach out to the maintainers and get
involved!
Using a non-rustup setup? Learn how to configure it for wasm-pack here.
File: docs/src/prerequisites/non-rustup-setups.md
Non-Rustup setups
wasm-pack compiles your code using the wasm32-unknown-unknown target. wasm-pack will automatically add this target for Rustup setups if you don't already have it installed by doing rustup target add wasm32-unknown-unknown. However, if you're not using Rustup, then we won't be able to do this automatically, and you'll have to do this yourself.
Manually add wasm32-unknown-unknown
Disclaimer: This is not guaranteed to work for every setup. These instructions below are specific for setups that match the exact rustc release, which means that the downloaded wasm32 target can be incompatible.
To manually add the wasm32-unknown-unknown target you will need to download it from the rust-lang website and put the contents in the correct folder.
All the targets for all the different rustc versions are not presented in a human way on a website (yet) for you to just select the one you want and download it, one reason for this is that Rustup handles all of this for you and the packaging of targets was mainly built for tools. However, the following steps will walk through how to do this.
First, check what version of rustc you're using by running rustc --version. This should display something like: rustc 1.33.0 (2aa4c46cf 2019-02-28). Then you need to download the correct wasm32 target for your rustc version. The rustc version is part of the url, which means for rustc 1.33.0 the url will look like this: https://static.rust-lang.org/dist/rust-std-1.33.0-wasm32-unknown-unknown.tar.gz.
Here's some examples of urls for different rustc versions:
- Nightly https://static.rust-lang.org/dist/rust-std-nightly-wasm32-unknown-unknown.tar.gz
- Specific date nightly (2019-03-10) https://static.rust-lang.org/dist/2019-03-10/rust-std-nightly-wasm32-unknown-unknown.tar.gz
- Beta https://static.rust-lang.org/dist/rust-std-beta-wasm32-unknown-unknown.tar.gz
You should be able to download this either by doing wget https://static.rust-lang.org/dist/rust-std-1.33.0-wasm32-unknown-unknown.tar.gz or by just visiting the url in a web browser.
After you have downloaded this tarball at a location of your choice, you should unpack it. This should result in a folder named rust-std-1.33.0-wasm32-unknown-unknown that contains some folders and files, but the interesting one is a folder called rust-std-wasm32-unknown-unknown which contains a lib and that should contain a rustlib folder and in that, a folder called wasm32-unknown-unknown. This is the folder we want to move.
Here's how the structure should look like for rustc 1.33.0:
rust-std-1.33.0-wasm32-unknown-unknown
โโโ components
โโโ install.sh
โโโ rust-installer-version
โโโ rust-std-wasm32-unknown-unknown
โโโ lib
โย ย โโโ rustlib
โย ย โโโ wasm32-unknown-unknownTo know where we should move this wasm32-unknown-unknown folder we need to run rustc --print sysroot which should print a path that looks something like this (this will vary on different operating systems): /home/user/rust/rust-1.33.0-2019-02-28-2aa4c46cf. That folder should contain a lib folder that contains a rustlib folder. We should move the wasm32-unknown-unknown to this folder.
On unix-like operating systems we can do that with the following command:mv rust-std-1.33.0-wasm32-unknown-unknown/rust-std-wasm32-unknown-unknown/lib/rustlib/wasm32-unknown-unknown /home/user/rust/rust-1.33.0-2019-02-28-2aa4c46cf/lib/rustlib/ and that should be it!
--- METRICS ---
- Files Extracted: 11
- Estimated Token Budget: ~7242 tokens
- Recency Window: Active (< 180 days)
- Canonical Reference: https://codewiki.google/github.com/wasm-bindgen/wasm-pack