Skip to content
defold-typescriptPublic

About

TypeScript toolchain for the Defold game engine: typings, Lua transpiler, and CLI. Agent-friendly, with a migration path from ts-defold

Resources

Stars

4 stars

Watchers

2 watching

Forks

Repository files navigation

defold-typescript

defold-typescript logo

npm Changelog GitHub repo CI Docs

Build your Defold game in TypeScript and get VSCode's full editor experience — autocomplete, inline type errors, and safe refactors — across the whole Defold API, while still shipping the plain Lua the engine runs.

Defold versions supported: 1.12.4, 1.13.0, 1.13.1, 1.13.2, 1.14.0, 1.14.1

Note

Want to help shape v1.0? Nothing is locked in yet, and the project ships often — see the changelog. Use it on a real project and open an issue about whatever you hit: a missing or mistyped API, a rough edge in the tooling, docs that left your coding agent guessing, or what you would want built next. Pull requests stay closed until the release.

  • The full Defold API, typed — every module and namespace is typed from the official reference, so go, gui, vmath, msg, and the rest autocomplete and type-check as you write, with the reference documentation rendered into the hover text.
  • Compiles to plain Lua — your TypeScript runs through the battle-tested TypeScriptToLua (TSTL) compiler down to the Lua Defold already runs: no engine fork, no proprietary runtime, no lock-in.
  • Typed scripts end to end — self, on_message, and on_input payloads are typed through defineScript, defineGuiScript, and defineRenderScript, and an editor property declared in defineScript's properties field lands on self with its own type while the toolchain emits the go.property registration for you; defineEditorScript types the editor extensions themselves.
  • The editor completes what your project declares — game-object paths, component ids, node ids, animation ids, resource paths, game.project config keys, and input action ids are read from your own project files and offered inside the string that needs them.
  • Pin the API to the engine you ship — lock a project to a Defold release so the types match the runtime you build against, and wall a directory to one script kind so its files see only the surface that kind really has.
  • Community libraries, typed on demand — declare a supported library as a dependency and resolve materializes its types; each one is maintained here against a pinned upstream rather than scraped at install time.
  • Hierarchical state machines, built in — hsm is a typed Hierarchical State Machine library that ships with the toolchain, with no separate install: nested states, timers, history, and parallel regions drive game flow and per-object behavior, while events, their payloads, the context, and every state path are checked at compile time and the editor suggests paths and event types as you type; a hands-on tutorial starts from zero, and view runs a machine from source in your browser.
  • Entity systems, built in — ecs is a typed port of tiny-ecs that ships with the toolchain and compiles to plain Lua with no lualib_bundle: systems run one loop over every entity whose components match their filter, the compiler knows which components each system's entities have, a bridge to hsm lets a state's hooks move an entity in and out of systems, and a hands-on tutorial starts from zero.
  • Fits new and existing projects — scaffold from scratch, or add the TypeScript surface to a project that already has game.project and adopt type safety gradually, one script at a time alongside your existing Lua.
    • Preserves your project layout — TypeScript blends into the existing project structure without creating a wrapper folder.
  • Built for the real loop — watch recompiles beside the Defold editor, live transpile diagnostics surface errors inline, and source maps let you set breakpoints in your .ts; --hot-reload pushes each successful rebuild into the running game, whose runtime errors arrive in your terminal naming the .ts line that threw.

This guide shows how to scaffold a project, write TypeScript that the toolchain compiles to Lua, and look up the language-and-toolchain quirks you will hit along the way.

The sections below mirror the top navigation; each lists the pages in its left-sidebar order. The repository README.md is generated from this file so the GitHub landing page and docs homepage stay aligned.

Get started

  • Getting started — install Bun, scaffold a new project with bunx @defold-typescript/cli@latest init path/to/project, add TypeScript to an existing Defold project with init ., write a one-screen script, and build to Lua with bunx @defold-typescript/cli build.
  • Editor setup — open the project in VSCode, use the generated tsconfig.json, and run bunx @defold-typescript/cli watch beside the Defold editor.
  • Defold editor — install Defold, open the generated project folder, attach a compiled script (.ts.script, .ts.gui_script, or .ts.render_script) to its game object, GUI scene, or render pipeline, and run the game (TypeScript is transpiled to Lua by the CLI, not the editor).

Guides

Tutorials

  • Build Tetris — build a complete Tetris game from scratch: write TypeScript, compile it to Lua, and wire the scene in the Defold editor, seeing the whole workflow end to end.
  • Vectors and rotations — the math behind movement, one game problem at a time: positions, vectors, speed, dt, rotation, the dot product, and local versus world space, ending with a ship that drifts through space.
  • State machines, one click at a time — a hands-on first look at hsm for readers who have never used a state machine: one robot buddy machine grows lesson by lesson, each change shown as a diff, with live diagrams you drive with buttons, from two states through every hsm feature to a second machine on its own game object.
  • Entity systems, one system at a time — a hands-on first look at ecs for readers who have never used an entity system: one night garden of fireflies grows lesson by lesson, each change shown as a diff, from a first world through every ecs feature to a state machine in each firefly.

TypeScript

  • TypeScript vs Lua — the Lua-developer on-ramp: a cheat sheet that translates syntax, tables, modules, and the standard library from Lua to the TypeScript the toolchain expects.
  • TypeScript gotchas — the canonical catalog of TS / TypeScriptToLua (TSTL) / Defold sharp edges: what each symptom looks like, why the toolchain behaves that way, and the workaround to reach for — from unary minus on a vector silently producing number to npm packages not resolving at all.
  • Data structures — what's built in for Defold: Array, tuple, Map, Set, WeakMap, WeakSet, object record, and class, each with its Lua lowering and lualib cost, plus the not-available list (regex, BigInt, LinkedList) and what to reach for instead.
  • Lua table constructs — how to write a table the engine reads by constant key, such as render.clear's buffer table: why the object literal doesn't compile, the checked LuaMap route and the inline cast, and the mapped type that looks like the fix but silently accepts a wrong key.

Core concepts

  • Script lifecycle — type self, on_message, and on_input payloads with defineScript, defineGuiScript, and defineRenderScript.
  • Messages — the BuiltinMessages catalog, msg.post send-side payload narrowing, and the isMessage / onMessage receive-side helpers.
  • Where script state lives — the four state tiers — per-instance self, a shared module local, a cross-script module singleton, and VM-global declare global — each grounded in the emitted Lua.
  • Vector math — the method-form arithmetic surface (add, sub, mul, div, unm) on Vector3, Vector4, Quaternion, and Matrix4, plus why you cannot write v3 + v3.
  • Editor scripts — extend the Defold editor with defineEditorScript; the <name>.ts.editor_script artifact, auto-load discovery, and the EditorCommand shape.
  • State machines — import the typed hsm library from @defold-typescript/types/hsm, learn how its events, transitions and timers run, define machines in plain modules, run one instance per object on self, and turn Defold messages and engine callbacks into typed events.
  • Entity systems — import the typed ecs library from @defold-typescript/types/ecs: entities as plain tables, filters that narrow components, the four system factories, the order one world update runs in, and running a world from a script.
  • ecs and hsm together — one table as both an entity and a machine's ctx: member, join, leave and tickMachines move entities in and out of systems from state hooks, and when a membership change shows.

CLI

  • init — scaffold a new Defold project with a TypeScript surface, or add TypeScript to an existing project; the two modes, the --template / --force flags, and the starter templates.
  • init-agents — write the agent contract (AGENTS.md + CLAUDE.md) into a project that has none, or restore a managed block you edited away; what the block carries, why re-runs never clobber your own notes, and how it differs from the contract init and upgrade already keep current.
  • upgrade — move the project to the latest toolchain with one verb (bunx @defold-typescript/cli@latest upgrade, or its update synonym): what it re-scaffolds, why it never clobbers your own scripts, what it does to an existing defold-target pin, and the --json envelope to read.
  • set-target — write the defold-target pin: a fixed version, a release channel (stable/beta/alpha), or --detected to sync it to the detected Defold editor, with the typo caught at write time rather than at build time.
  • watch — the incremental rebuild loop: recompile Lua on every save beside the Defold editor, push each successful rebuild into the running game with --hot-reload, and re-resolve the extension surface on game.project changes.
  • reload — push one reload into the running game and read the editor console for a bounded window, so a script learns whether an error surfaced there instead of trusting the editor's "queued" response.
  • build — one-shot transpile of every src/1 TypeScript file to Lua, plus the headless defold subcommand that drives bob to build and bundle the project.
  • run — launch the compiled project from build/default (or a native-extension dmengine) with no transpile and no Bob, forwarding engine args after -- and propagating the engine exit code.
  • bob — drive Defold's headless bob.jar build tool: the resolve/build/bundle/status/run subcommands, the sha-keyed jar cache, Java resolution, and target selection.
  • wall — opt-in per-directory API walls that narrow a single-kind source directory to its script-kind surface, in interactive and flag forms.
  • resolve — generate importable TypeScript modules from your game.project native-extension dependencies, with pin/drift detection and a --frozen lockfile mode.
  • scene-types — generate the scene-address declaration from your .collection/.go files so game-object paths and component ids complete in the editor; how build and watch keep it current, how init and upgrade wire it into your program, and why it can never reject an address.
  • view — run a file's state machines and entity worlds in a local browser viewer from source: active states highlighted in the code, systems with their entities and timings, events, Play and Step, an editable ctx, a log, and live reload on every save.
  • library — check a directory of library data the way this CLI reads it: the reader, the print of every module, and one compile of the printed declarations, native declarations and usage examples against this CLI's engine types, with one <library>: <check>: <message> line per problem and a non-zero exit.

Toolchain & workflow

  • Transpile diagnostics — the scaffolded @defold-typescript/tstl-plugin language-service plugin that surfaces TypeScript-to-Lua transpile errors live in the editor, advisory-only and never blocking tsc --noEmit.
  • Debugging — step through .ts source with breakpoints via the Local Lua Debugger and the scaffolded Bun launch path (no shell, Windows-native), resolving through the emitted <name>.ts.script.map.
  • Agent runbooks — harness-neutral procedures for driving the CLI from an automated agent: scaffold a project, install the agent contract, regenerate extension types, add and attach a script (build, wire the compiled component, verify), and fix the Lua output over the --json envelope, gating on ok.
  • Helper scripts — where build, codegen, and maintenance scripts live: a project-root /scripts folder run with Bun, typed by their own scripts/tsconfig.json, kept off the Lua build path and out of the Defold-typed src/ surface.
  • Test with Bun — where a test goes (next to its module, or in src/test/ when it needs Bun's runtime), how to write and type-check it, and how to test game logic without the engine.
  • Terminal output — how failure lines read (defold-typescript <command>: error: <message>), when the error word is colored, and how --no-color, NO_COLOR, TERM=dumb, and --json turn color off.

Project configuration

  • Pinning the Defold target — keep the default latest surface, or pin a fixed version or release channel (stable/beta/alpha) whose API surface is generated on the fly and materialized into a project-local .defold-types/<version>@<toolchain>/.
  • Upgrading the toolchain — move the project to the latest toolchain with one verb (bunx @defold-typescript/cli@latest upgrade, or its update synonym): what it re-scaffolds, why it never clobbers your own scripts, what it does to an existing defold-target pin.
  • Upgrading Defold versions — move a project between pinned surfaces, with a section per release.
  • Native extensions — declare an extension in game.project [dependencies], then run resolve to generate a @globalTable module per .script_api into a gitignored .defold-types/extensions/ surface, and import it by its namespace.
  • Shipping types with a library — for library authors: put .d.ts files in a root types/ folder, use @defold-typescript/types names, choose the module or global form, check the result with resolve, which installs them ahead of every other surface, and start from the curated types with export-types.
  • Adding a library to the library data: the library docs site covers LuaLS library types, forked library types and refreshing library pins.

Migration

  • API docs vs ts-defold-types — a factual, dimension-by-dimension comparison of the JSDoc that @defold-typescript/types and ts-defold-types emit (Markdown conversion, dash params, grid-aligned multi-line docs, branded constants, the @example trade-off), with a picker for which surface fits your project.
  • Migrating from ts-defold — move a project off the @ts-defold/* stack: the package/tooling map, the step-by-step port via init add-TypeScript mode and a tsconfig.json reconcile, and the type-surface differences you will hit.

Releases

  • Changelog — what changed in each published toolchain version (vX.Y.Z tag), reverse-chronological with Added / Improved / Fixed and a Breaking lead line where behavior changed incompatibly; the latest releases per-patch, older ones rolled up per minor.

Reference

  • API — the generated @defold-typescript/types reference: every documented Defold namespace, grouped alphabetically as cards (site-only; built from the typed surface the toolchain ships).
  • Lua standard library — the pure-Lua / LuaJIT reference category (base, bit, …). Types are owned by the lua-types dependency the lua-stdlib-globals goal adopted; @defold-typescript/types does not re-emit them as generated namespaces.
  • For AI agents — machine-readable docs per llmstxt.org:
    • llms.txt is the map (start here)
    • llms-full.txt is the full corpus (grep it, never read it whole). The same pair ships into a consumer's node_modules/@defold-typescript/docs/ on install.
    • init-agents wires them up — it writes the managed AGENTS.md / CLAUDE.md block that points your agent at both files and at the runbooks, so a fresh session orients from the project's own documentation instead of from training-data recall.

Credits

Language and platform logos come from Devicon, MIT License, Copyright (c) 2015 konpa (license). Other interface icons come from Phosphor Icons, MIT License, Copyright (c) 2023 Phosphor Icons (license). Logos are trademarks of their respective owners and indicate compatibility only.

Footnotes

  1. src/ is this guide's shorthand and the scaffold's default, not a fixed location. Your source roots are the include globs in tsconfig.json — ["src/**/*.ts"] out of the box, and any list of folders you set; build and watch compile exactly what those globs match, and ignore exclude. ↩

About

TypeScript toolchain for the Defold game engine: typings, Lua transpiler, and CLI. Agent-friendly, with a migration path from ts-defold

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages