WebAssembly
Imports and Exports
Exchange functions, memory, and globals.
By EZ4Code Team
importexportinterop
Code
// Imports provided to a WASM module
const importObject = {
env: {
consoleLog: (value) => console.log("from wasm:", value),
now: () => Date.now(),
memory: new WebAssembly.Memory({ initial: 1 }),
},
};
const { instance } = await WebAssembly.instantiate(bytes, importObject);
// Exports can be functions, memory, tables, or globals
const { add, multiply, memory, __heap_base } = instance.exports;
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
console.log("heap starts at", __heap_base);Explanation
Imports are host-provided functions, memory, tables, or globals grouped under module names that the WASM module references. Exports are the module's public surface, exposed as properties of instance.exports. This two-way bridge is how WASM calls into JS and how JS invokes compiled functions.