JavaScript
JavaScript can be used as a Tier 1 guest language.
The tools used in this guide are:
@bytecodealliance/jco
- Convert Javascript to WASM Components@bytecodealliance/componentize-js
- JavaScript Componentization Tool
The easiest way to get started once the tooling is installed is to use the golem-cli new
command as described in the Quickstart.
View the available examples with:
golem-cli list-examples --language javascript
Then generate a new example project with:
golem-cli new --example js-actor-minimal --component-name js-component
Manual Installation
Here's the target project structure
- main.js
- main.wit
Add a package.json file
{
"type": "module",
"scripts": {
"build": "jco componentize -w wit -o out/component.wasm src/main.js"
},
"devDependencies": {
"@bytecodealliance/componentize-js": "0.8.3",
"@bytecodealliance/jco": "1.1.1"
}
}
Create a WIT File
Create a WIT file in the wit
directory, for example wit/main.wit
:
package golem:component;
interface api {
add: func(value: u64);
get: func() -> u64;
}
world demo {
export api;
}
Create a main.js file
Create an empty main.js
file in the src
directory:
Full file path from the root of the project: src/main.js
The exported object must have the same shape as the interface exported by your WIT world.
let state = 0
export const api = {
add(value) {
console.log(`Adding ${value} to the counter`)
state += Number(value)
},
get() {
console.log(`Returning the current counter value: ${state}`)
return BigInt(state)
},
}
Install Dependencies
npm install
Build the Component
npm run build
Produces a WASM file in the out
directory ready to be uploaded to Golem!
Using Additional WIT Files (Optional)
If needed you can put additional WIT files from golem-wit (opens in a new tab) to the wit/deps
directory in your project.
Then import them to your main interface definition.
For example if you wanted to use a wasi clock you would add the following to your main.wit
file:
package golem:component;
interface api {
add: func(value: u64);
get: func() -> u64;
}
world demo {
// Add the import!
import wasi:clocks/wall-clock@0.2.0;
export api;
}
Then you need to add the wasi deps to your wit/deps directory
.
We need both folders because
clocks
depends on theio
.
- main.wit
These wasi functions can be imported from your javascript like this:
import { now } from "wasi:clocks/wall-clock@0.2.0"
function useNow() {
let currentTimestamp = now()
console.log(`The current time is`, currentTimestamp)
}