Exports and Imports
Learn how to export and import in WebAssembly.
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:
(module(func $add (param $lhs i32) (param $rhs i32) (result i32)get_local $lhsget_local $rhsi32.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:
(module(func $add (export "add") (param $lhs i32) (param $rhs i32) (result i32)get_local $lhsget_local $rhsi32.add))
Let’s use WABT’s wat2wasm
tool to convert the WebAssembly text format into a WebAssembly module with the following command:
/path/to/build/directory/of/wabt/wat2wasm add.wat
Let’s analyze the generated byte code using the hexdump
tool: ...