Mohammed
Mohammed

Reputation: 323

What is the proper way to import webassembly module in javascript

In webassembly.org, JS API page, the way to import WebAssembly in javascript is

fetch('example.wasm').then(response => response.arrayBuffer())
.then(bytes => instantiate(bytes, importObject))
.then(instance => instance.exports.e());

The js file emitted by emcc seems to do that.

But when I use wasm-pack for Rust's Cargo, the javascript file simply does import * as wasm from './example.wasm'

What's the difference between these two? Is direct import a newly supported feature? and when using the direct import how would I access WebAssembly's memory from javascript since I didn't pass them to the WebAssembly module as I would do if I used the first method?

Upvotes: 2

Views: 8779

Answers (2)

The Wayward Developer
The Wayward Developer

Reputation: 491

The declarative import of WebAssembly modules is not yet standardized. I assume wasm-pack targets the experimental import feature of Node.js: http://web.archive.org/web/20220528033110/https://www.joyent.com/blog/improved-wasm-support-coming-to-node#importing-webassembly-modules

How to access the memory depends on the module: if it exports it, you can access it as a member, if it imports it, it has to be available as a member of an ES6 module under the names you would use in the import object.

Upvotes: 3

Asanka
Asanka

Reputation: 618

Depending on the platform, if wasm module is running in a web browser, fetch and instantiate as mention in question. WASI has enabled to provide even files system sandboxing also when running WASM in nodejs. which can read the file from disk using node Fs in instantiate using WASI

    const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
    const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));
    const instance = await WebAssembly.instantiate(wasm, importObject);
    wasi.start(instance);

link: https://nodejs.org/api/wasi.html

Upvotes: 0

Related Questions