...

/

Exports and Imports

Exports and Imports

Learn how to export and import in WebAssembly.

We'll cover the following...

A WebAssembly module consists of export and import sections. These sections are responsible for exporting functions out of and importing functions into the WebAssembly module.

Exports

In order to call the functions defined in a WebAssembly module from JavaScript, we need to export the functions from the WebAssembly module. The export section is where we’ll define all the functions that are exported out of the WebAssembly module.

Let’s go back to our classic add.wat example from the previous chapter:

Press + to interact
(module
(func $add (param $lhs i32) (param $rhs i32) (result i32)
get_local $lhs
get_local $rhs
i32.add
)
(export "add" (func $add))
)

Here, we’ve exported the add function using the (export "add" (func $add)) statement. To export a function, we’ve used the export keyword followed by the name of the function and then the pointer to the exported function itself.

Remember that WebAssembly is compact-sized. Thus, we can represent the export statement along with the function definition itself:

Press + to interact
(module
(func $add (export "add") (param $lhs i32) (param $rhs i32) (result i32)
get_local $lhs
get_local $rhs
i32.add
)
)

Let’s use WABT’s wat2wasm tool to convert the WebAssembly text format into a WebAssembly module with the following command:

Press + to interact
main.sh
add.wat
/path/to/build/directory/of/wabt/wat2wasm add.wat

Let’s analyze the generated byte code using the hexdump tool: ...