To export exported JavaScript functions, you can pass a .wit
file and wit
world
when running javy build
.
Only ESM exports are supported (that is, Node.js/CommonJS exports are not supported). For each exported JavaScript function, Javy will add an additional function export to the WebAssembly module. Exported functions with arguments and generators are not supported. Return values will also be dropped and not returned. The Wasm module generated is a core Wasm module, not a Wasm component.
An example looks like:
index.js
:
export function foo() {
console.log("Hello from foo!");
}
console.log("Hello world!");
index.wit
:
package local:main;
world index-world {
export foo: func();
}
Run:
$ javy build index.js -C wit=index.wit -C wit-world=index-world -o index.wasm
$ wasmtime run --invoke foo index.wasm
Hello world!
Hello from foo!
The wit
package name and wit
world name do not matter as long as they are
present and syntactically correct (that is, it needs to be two names
separated by a :
). The name of the wit
world (that is, the value after world
and before {
) must be passed via -C wit-world
argument. The -C wit-world
argument
identifies the wit
world in the wit
file for the Wasm module generated by javy build
.
Exported function names with multiple words have to written in kebab-case in the
.wit
file (a restriction imposed by wit
), they are exported from the Wasm
module as kebab-case to match the WIT, and Javy will match the WIT export to
a JavaScript export with the same name but in camel-case.
index.js
:
export function fooBar() {
console.log("In foo-bar");
}
index.wit
:
package local:main;
world index {
export foo-bar: func();
}
Run:
$ javy build index.js -C wit=index.wit -C wit-world=index -o index.wasm
$ wasmtime run --invoke foo-bar index.wasm
In foo-bar
Exporting a function named default
in the WIT world exports a function named
default
on the Wasm module and corresponds to either an exported default
function or exported default arrow function in JS.
index.js
:
export default function () {
console.log("In default");
}
index.wit
:
package local:main;
world index {
export default: func();
}
In the terminal:
$ javy build index.js -C wit=index.wit -C wit-world=index -o index.wasm
$ wasmtime run --invoke default index.wasm
In default
You can also export a default function by writing:
export default () => {
console.log("default");
}