Search code examples
javascriptemscriptenwebassembly

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?


Solution

  • 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.