Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Calling Between JS and Wasm

Importing JavaScript Functions

Learn how WebAssembly modules import JavaScript functions: the import object, console.log and Math imports, callbacks, LinkError, re-entrancy and exceptions across the boundary.

A module on its own is a closed box. It cannot print, draw, fetch or read the clock. Everything beyond pure computation comes from imports: functions (and memories, tables and globals) that the host supplies when it creates the instance. Imports are how a Wasm program logs to the console, calls Math.sin, reads the DOM through a helper, or reports a result back to your page.

The import object

A module declares each import with two names, a module name and a field name, plus a type. Together they say "I need a function called log from a module called env". When you instantiate, you pass an object whose structure mirrors that:

JavaScript
const importObject = {
  env: {
    log: (n) => console.log(n),
    sin: Math.sin,
  },
};
const { instance } = await WebAssembly.instantiate(bytes, importObject);

The module name env is just a convention (Emscripten and Rust use it), and you can use any name. Several imports can come from different "modules" such as math and ui. Use WebAssembly.Module.imports(module) to find out what a module needs.

In the binary, the Import section (id 2) holds entries of the form module-name, field-name, kind, type. Remember that imported functions take the first function indexes, ahead of the module's own functions.

Calling imports from Wasm

From inside the module an import is called like any function: push the arguments and call its index. The text format names them:

WAT
(module
  (import "env" "log" (func $log (param i32)))
  (import "env" "sin" (func $sin (param f64) (result f64)))
  (import "env" "rand" (func $rand (result f64)))

  (func (export "hello")
    (call $log (i32.const 1))
    (call $log (i32.const 2))
    (call $log (i32.const 3)))
  (func (export "sinOf") (param $x f64) (result f64)
    (call $sin (local.get $x)))
  (func (export "roll") (result f64)
    (call $rand)))

JavaScript receives the arguments converted to numbers (i32 as a signed number, i64 as a BigInt, floats as numbers), and whatever it returns is converted to the declared result type with the same rules you saw for exports.

Node.js Import console.log, Math.sin and a random source

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Wasm called straight into Math.sin: the imported function can be any callable, including a built-in. The module and JavaScript share the work: Wasm provides the structure, the host provides the capabilities.

Callbacks, errors and re-entrancy

Imports let a module call back into your code, for example to report progress or to ask the host for a decision. Three behaviours are worth knowing before you build on them:

  1. Exceptions pass through. If the JavaScript import throws, the exception travels out through the Wasm frames and out of the exported call that started it, unchanged. Wasm does not catch it (unless it uses the exception-handling proposal).
  2. Re-entrancy works. An import may call exports of the same instance. The module's state (memory, globals) is shared, so a half-finished update may be visible to the callback.
  3. Return values are converted. Returning a string for an i32 result gives ToInt32 of the string; returning nothing gives 0 for a number result.
Node.js Errors, exceptions and re-entrancy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

All four link failures happen before any module code runs. Missing the object or the module key is a TypeError; a missing or wrongly typed field is a LinkError. These are errors you can fix by comparing your object with WebAssembly.Module.imports(module).

Other kinds of import

Functions are the most common import, but the same mechanism supplies:

Kind Declared as You pass
Memory (import "env" "mem" (memory 1 4)) A WebAssembly.Memory with compatible limits
Table (import "env" "table" (table 4 funcref)) A WebAssembly.Table
Global (import "env" "base" (global i32)) A WebAssembly.Global, or (for immutable) a plain number or BigInt

Importing a memory instead of declaring one lets the host choose its size and share it with other modules, and is how Emscripten and Rust output often start. A bonus: an immutable imported global can be given as a plain number, so { env: { base: 1024 } } works for (global i32).

Design tips

  • Keep imports few and simple. Each one is something the host must implement in every environment (browser, Node, WASI).
  • Pass pointers, not objects. An import that takes a pointer and length can read a string out of memory. Objects can go through externref (a later lesson) but crossing costs more.
  • Document the import contract. A module's imports are its requirements, just like function parameters.
  • Do not trust the callback's timing. The host may run it at any point in the middle of Wasm's work.

An imported function that calls back into an export while the module is in the middle of using memory can see (and change) memory in an inconsistent state, for example while a buffer is half filled. Treat callbacks as re-entrant and keep invariants true at every call.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function index does the first imported function get?

    Imports always come first in the function index space, so the first import is function 0.
  2. 2. What error is thrown when the import object lacks the field a module needs?

    A missing or mismatched import is reported as a WebAssembly.LinkError at instantiation (a missing module object gives a TypeError).
  3. 3. An imported JavaScript function throws. What does the caller of the export see?

    Exceptions propagate through Wasm frames to the host caller unchanged.
  4. 4. How do you find out what a module imports?

    Module.imports returns each import's module, name and kind.

Summary

  • Imports are how a module reaches the outside world: functions, memories, tables and globals supplied in the import object.
  • The import object mirrors the declared module and field names; mismatches fail at instantiation with LinkError or TypeError.
  • Imported functions get the first function indexes; JavaScript receives converted arguments and its result is converted back.
  • Exceptions pass through Wasm; callbacks can re-enter exports, so keep state consistent.
  • Keep the import surface small and well documented.

Next: Passing Strings and Arrays