These are notes from me learning AssemblyScript.
AssemblyScript compiles a TypeScript-like language to WebAssembly.
For example, create a calc.ts file:
// calc.ts
export function len(a: string): i32 {
return a.length;
}npm install --save-dev assemblyscript
npx asc calc.ts --outFile calc.wasm --bindings esmThen, in your ESM code, you can import { len } from './calc.js'
WebAssembly can call browser JavaScript code via Host bindings.
For example, utils.js contains:
export function changeTitle(title) {
document.title = title;
}Then, in calc.ts, you can define changeTitle() like below and call it from AssemblyScript:
@external("./utils.js", "changeTitle")
declare function changeTitle(title: string): void;Note:
- JS functions must have one or more fixed signatures.
asyncis not supported.
- In
tsconfig.json, add"extends": "assemblyscript/std/assembly.json"to use AssemblyScript types. @externalis not valid TypeScript. Ignore via// @ts-ignoreon the line before. Ref
This uses WebAssembly.instantiateStreaming
which fetches, compiles, and instantiates a WASM.
export const { fn1, fn2, ... } = await WebAssembly.instantiateStreaming(fetch("file.wasm")).then((r) => r.instance.exports);WebAssembly does not natively support the following and AssemblyScript bridges some of these:
- Type conversion. Handled via Host bindings
- Garbage collection. AssemblyScript copies strings into WASM and garbage collects them later via
exports.__new(size, width). - Async operations are not currently supported
- DOM manipulation, Fetch, etc. are not possible.
- Exception handling is not supported.