Use cases · WebAssembly
WebAssembly with Tern
Add --target wasm to run a program under wasmtime or Node, or --lib to get a module JavaScript can import, with TypeScript types.
curl -fsSL https://ternlang.dev/install.sh | sh
tern new myapp && cd myappA library for JavaScript
export fn word_count(text: str) int:
n = 0
for w in text.split(" "):
if w.trim() != "":
n += 1
return ntern build --lib --target wasm lib.tn # lib.wasm (41 KB), lib.mjs, lib.d.tsimport { load } from "./lib.mjs";
const lib = await load();
console.log(lib.word_count("to be or not to be")); // 6nThe loader works in Node and the browser, and runtime errors arrive as a JavaScript TernError. The WebAssembly guide covers how values cross over.
Benchmarks
| binary-trees | Tern | Rust + mimalloc |
|---|---|---|
| 14 threads | 482 ms | 630 ms |
| one thread | 3.75 s | 2.84 s |
Rust still wins single-threaded allocation-heavy wasm; we show it. --target wasm-threads runs parallel code on Web Workers.
In production
ternTS, our TypeScript transpiler, is Tern compiled to a 2 MB wasm module. You can run it on a whole project in your browser.
Questions
Can Tern compile to WebAssembly?
Yes. --target wasm builds a WASI program; --lib --target wasm builds a module with a JavaScript loader and TypeScript types; --target wasm-threads adds threads.
What doesn't work on wasm?
sqlite and http.serve, and with plain --target wasm, parallel code runs one task after another.
More about Tern
Tern (ternlang) is an early release: the language will change, and so will these numbers. Benchmarks run on an Apple M4 Pro; the full tables, losses included, are on the home page.