unwasm allows you to import .wasm files as if they were standard ES modules. It parses the module at build time to discover imports and exports and generates bindings tailored to your environment.
There are two main types of bindings:
- Static bindings: Used when the environment supports top-level
await and the module requires no imports (or unwasm can resolve them). The .wasm file behaves like a regular ESM import. - Lazy bindings: Used when top-level
await is unavailable, the module requires an imports object, or you explicitly set the lazy plugin option. unwasm exports a Proxy that you call as a function to instantiate the module with your own imports.
If you use static import syntax, named exports are proxied until the module is initialized. Calling a named export before initialization triggers an automatic initialization without imports, returning a Promise that resolves with the result.
// Static import
import { sum } from "sum.wasm";
// Dynamic import
const { sum } = await import("sum.wasm");
// Dynamic import with an imports object
const { rand } = await import("rand.wasm").then((r) =>
r.default({
env: {
seed: () => () => Math.random() * Date.now(),
},
}),
);
// Static import with an imports object
import initRand, { rand } from "rand.wasm";
await initRand({
env: {
seed: () => () => Math.random() * Date.now(),
},
});