astwerk core

Scripts

A node with CompileFrom compiles a scripts directory into the output. That is a build feature, not a client runtime: core astwerk never ships JavaScript to a page on its own.

Compiling scripts

CompileFrom runs ssg.CompileScripts. A Go file with the wasm build constraint becomes a .wasm module, a subdirectory with such a file becomes NAME.wasm, and .ts files are handed to tsc in one batch.

go
//go:build js && wasm

package main

import "syscall/js"

func main() {
	doc := js.Global().Get("document")
	doc.Call("querySelector", "#toggle").Call("addEventListener", "click",
		js.FuncOf(func(js.Value, []js.Value) any {
			doc.Call("querySelector", "#nav").Get("classList").Call("toggle", "open")
			return nil
		}))

	select {} // keep the module alive for the handler
}

// "scripts": {CompileFrom: "scripts"}  →  build/scripts/nav.wasm + wasm_exec.js

See Scripts & WebAssembly to learn about the build constraints, the produced files and the size trade-off.

Loading a module

The output is an ordinary file; loading it is an ordinary script tag. starter/wasm/wasm_script.templ ships the loader ready to copy:

templ
templ WasmScript(c ssg.Ctx, name string) {
	<script src={ c.Asset("scripts/wasm_exec.js") }></script>
	<script data-wasm={ c.Asset("scripts/" + name + ".wasm") }>
		(() => {
			const src = document.currentScript.dataset.wasm;
			const go = new Go();
			WebAssembly.instantiateStreaming(fetch(src), go.importObject)
				.then(res => go.run(res.instance));
		})();
	</script>
}

For compiled markup, signals or a full client-side runtime, see the optional astwerk-live extensions. The note there matters: that side of the project is still in heavy redesign.