Skip to Content
defold-typescript
Get startedGuidesAPILibraries
CLI

Build

build transpiles every TypeScript file under src/1 to Lua and writes the result into the Defold project tree — a one-shot compile. For the incremental loop you run while editing, see watch.

bunx @defold-typescript/cli build

Tip

build regenerates the scene-address declaration before it transpiles, so a game object you added since the last build is already a completion on the addresses this compile checks against.

What it does

A file with an export default defineScript({...}) (or defineGuiScript/defineRenderScript) lifecycle factory becomes a Defold script component (src/main.ts -> src/main.ts.script); a plain module with no factory becomes a Lua module (src/util.ts -> src/util.lua) — a generated artifact you never edit or reference by hand, only ever the src/util.ts you author. Your import becomes a Lua require that resolves against that emitted module, so a shared module must be built before the script importing it will run. Open the project in the Defold editor (or run it headlessly, below) to play it.

build and watch skip every file bun test runs (*.test.ts, *_test.ts, *.spec.ts, *_spec.ts): it writes no Lua, joins no program the build type-checks, and gets no build diagnostic in the editor, so a test can sit next to the module it tests. Start such a test with /// <reference types="bun-types/test" /> so the project's own tsc --noEmit checks it against bun:test without Bun's globals reaching game code. A test that needs node:* or Bun goes under src/test/ instead. Test with Bun covers both places and how to write a test.

They also skip every file under src/test/, the folder init scaffolds for tests and helpers that need Bun's runtime: a module there writes no Lua and joins no program the build type-checks, so game code that imports one fails the build.

The declarations resolve installed behind the "extensions" and libraries@<cliVersion> entries on the tsconfig types list are part of the compile too, as type information only: a dependency's types check your code, and nothing under .defold-types/ is written as Lua.

A script component is a resource addressed by path from a .go file, never a module on Defold's require path, so a require aimed at one resolves to nothing at runtime. A script that also exports runtime values therefore builds into two outputs: the component, and a companion Lua module at the module-kind path (src/door.ts -> src/door.ts.script and src/door.lua) holding those exports and everything they reach. The component requires the companion instead of redeclaring it, so an exported object is one table for the script and for every importer — see script state. Two shapes cannot be split that way and are build errors instead: a binding the exports reassign while a lifecycle hook also reads it, and effectful top-level work above an exported declaration. Types cross freely in either direction — a type-only import is erased and emits no require at all.

The build checks every require it emits against the outputs it is about to write and fails with the offending file, the require path, and the source it names, so an import that cannot resolve is a build error rather than a load failure inside the editor. Under a configured outDir every emitted require carries the outDir-rooted path the build actually writes, so a cross-file import, a script's companion and the generated runtime files all load from there. A source whose name contains a dot is written to src/foo.bar.lua with the dot intact, while Lua reads a dot as a path separator, so the emitted require("src.foo_bar") looks for src/foo_bar.lua and finds nothing — rename the source to remove the dot. An outDir whose own name contains a dot has the same problem one level up and no require can spell it, so the build fails before writing anything — pick an outDir with no dot in it. A require with no TypeScript source behind it — a Lua module from a Defold library dependency, the lldebugger.debug module the debugging guide sets up, hand-authored Lua — is external and is left alone.

No two sources may write the same output path, and no generated file may land on hand-authored Lua. The build claims every path it is about to write and fails before touching anything when one is contested — naming the path, the source, and the exports it carries — so a companion never overwrites a .lua file you wrote yourself, and two sources collapsing onto one rel under a shared outDir is an error rather than whichever one happened to be written last. A rebuild under watch claims on behalf of the whole project, not just the files it recompiled, so editing one source into another's output path is reported and the rebuild rejected, instead of quietly replacing a module nothing touched. The existing file stays as it is, and the watch keeps running, picking the fix up on the next save.

The Lua the build writes for itself, in the runtime folder, is inside the same contract. A hand-authored file at one of its paths fails the build with its bytes intact, and must be renamed; so must a source of your own that compiles to one of those paths. A file an earlier build wrote carries the generated banner and is replaced as usual.

The build writes only inside the project folder. Before writing anything, it refuses an output or source-map path that is a symbolic link, and any path a folder link leads outside the project, and the failure names the path, the link and where the link points. The same rule covers the declarations the build keeps in .defold-types/ and its edits to .gitignore and tsconfig.json: a .defold-types folder link leading outside the project fails the build, and a .gitignore or tsconfig.json that is a link fails it only when the build must change that file. A folder link that stays inside the project is followed. outDir must be a folder inside the project: an absolute path, or one that climbs out with .., fails the build. It must also be a folder Defold loads: an outDir that is, or sits inside, build, builtins, .internal or .git at the project root, or a folder .defignore lists, fails the build, because the Defold editor never loads files there. These checks ignore letter case, since macOS and Windows treat Build and build as one folder. A source inside outDir fails build and watch as a failed file, because tsc leaves outDir out of the program and never type-checks it. setup-debug and scene-types refuse the same outDir and write nothing, while a project with no tsconfig.json still runs both on the src/ default. A backslash in outDir separates folders on every OS, so "out\\lua" and "out/lua" name the same folder.

If a Defold editor is open on this project, build names it on stderr (attached to Defold editor at http://localhost:<port>) and moves on. It is a one-shot command, so nothing is streamed and nothing is posted to the editor unless you pass --editor-compile or --editor-run; for the loop that surfaces the running game's runtime errors as they happen, see watch. With no editor open — the ordinary case in CI — build prints nothing extra and behaves exactly as before. The probe is time-bounded: an editor that does not answer promptly is treated as absent and the build carries on, so a stale port file can never hold it up.

When a source uses a runtime helper TypeScript-to-Lua provides (Object.keys, object spread, and similar), the build also writes lualib_bundle.lua to the runtime folder automatically, and the generated Lua requires it by the path it lands at — require("lib.defold_typescript.lualib_bundle") by default. Importing the timers module writes it too, because the timer runtime that import pulls in requires the bundle itself.

Because the output kind is the factory a source calls, adding or removing a factory switches the artifact (src/main.lua becomes src/main.ts.script, or the reverse). build and watch prune the stale alternative for you, so a kind switch never leaves the previous output behind. A script's companion is a live output, not a stale alternative: it survives the prune while the source still exports a value, and is deleted on the build after the last one goes. Adding a factory to a module that other sources import keeps its .lua at the same path, so every require that names it keeps resolving across the switch. Every generated file carries a trailing --# defold-typescript:generated marker; on a full build the tool warns, never deletes about any marked .lua or .ts.* output whose TypeScript source no longer exists, so a deleted or renamed source's orphaned Lua surfaces for you to remove (the warning names the file and the source to restore). Hand-authored Lua, which lacks the marker, is never flagged or touched.

A full build also warns when a .go/.collection component: references a mesh source asset (.gltf/.glb/.dae) directly. Those are imported into a .model component, not added as components — the editor rejects the direct form, but Bob's headless build accepts it and the game object fails at runtime. The warning names the scene file and the offending path; wrap the mesh in a .model (with a materials block) and point the component at the .model.

Every build, and every watch rebuild, also prints the transpiler's own warnings, each as <file>:<line>:<column>: <message>, or <file>: <message> when it has no position: a direct go.property call, and a top-level name that hides a Lua or Defold global, such as a helper named select or an enum go. Neither fails the build.

A full build also checks every address literal your code posts to — msg.post, go.get, go.animate and every other slot the toolchain classifies as an address — against the component ids your scenes declare, and warns when the #fragment names a component the addressed object does not have. Four things bound it:

  • It reports only the #fragment, never the path before it. A path is undecidable: factory.create can invent a game object at any path at runtime, but it can never invent a component.
  • What the fragment is checked against depends on the path in front of it. An absolute path the scene walk knows — "/player#sprite", or the world-qualified "mylevel:/player#sprite" — is checked against that object's components, so a fragment that names a component some other object has is still reported, and the warning says which ids the object does declare. A bare "#sprite", a relative or runtime-composed address, or a path the walk does not know is checked against the whole project instead: any component id declared anywhere satisfies it. An object whose prototype the walk could not read falls back the same way rather than reporting every fragment on it. So does every address in a project whose worlds the walk could not classify — a collection nothing reaches, a .collectionproxy it could not read, a game.project naming no bootstrap: a world it never placed can own the component the placed ones do not.
  • It never rejects a build or changes the exit code. Like the other two scans it warns and moves on.
  • It reports itself as suppressed whenever the component-id universe has a hole — an unparseable scene, or a dependency game.project declares that resolve has not materialized — naming the reasons. A reason for a dependency resolve has not materialized ends by telling you to run defold-typescript resolve, which fills the hole. A suppressed check found nothing because it did not run, which is not the same as finding nothing. A project with no scenes and no hole is silent: there is no address universe to check against. A project whose scenes are missing because its dependency is missing still reports the check as suppressed.

watch runs the same check on every rebuild, so an address you break is reported on the edit that broke it rather than at the next restart. The whole project is re-checked each time, not just the file you saved: a fragment can go bad because a scene changed, and one that is still broken keeps being reported until you fix it or declare the component. Saving a .go/.collection re-checks the whole project on the spot — no rebuild needed, so a component you remove is reported on that save. The very first build of a watch session is the exception — it runs before the scene walk, so the check starts from the first rebuild or scene save.

A full build also warns when an address names another world. Only msg.post and msg.url cross a collection proxy; every go.* call that resolves an instance or component handle stays in the world its own script runs in, so go.get_position("mylevel:/enemy") written from a script outside mylevel can never resolve. A socket counts however the rest of the address is written — mylevel:enemy, mylevel: and mylevel:#body are checked just like mylevel:/enemy. The warning names the socket the address claimed and the world the script actually runs in. It warns and moves on like the scans above, and stays silent wherever it cannot be sure: on the two cross-world slots, on an address that names no socket at all — a bare /path, a relative id or sub/id, a lone #fragment — and on any script whose world the scene walk could not resolve. watch reports it on every rebuild and on every .go/.collection save, exactly as it does the #fragment check. See which world an address resolves in.

build never narrows the API surface — it builds against whatever entrypoint your tsconfig names, the full @defold-typescript/types by default. Opt into per-directory narrowing with wall.

The everyday commands carry no version tag: inside an installed project bunx resolves the @defold-typescript/cli that init pinned, so the build runs the version locked alongside your @defold-typescript/types. Reserve @latest for init and the deliberate upgrade path (see code editor setup).

The runtime folder

The build writes its own Lua into one folder under the output root, and only the files your program uses:

FileWritten when a source
lib/defold_typescript/lualib_bundle.luauses a TypeScript runtime helper, or imports timers or hsm/async
lib/defold_typescript/timers.luaimports @defold-typescript/types/timers
lib/defold_typescript/hsm/<module>.luaimports that hsm module
lib/defold_typescript/ecs/<module>.luaimports @defold-typescript/types/ecs

A build with no errors deletes each of these files it did not write, with its map, and then any library folder that leaves empty. A file stays when it lacks the generated banner, when one of your sources or its companion compiles to that file, under any spelling your disk reads as the same file (on macOS and Windows, which ignore letter case by default, Timers.lua is timers.lua), or when a hand-written .lua, .script, .gui_script, .render_script or .editor_script file in the project names its require path in quotes, such as require "lib.defold_typescript.lualib_bundle"; a file kept for hand-written Lua also keeps every runtime file it requires. build prints the deleted files on a second line. A failing build deletes nothing, and so does a watch rebuild; watch deletes them only in its first build.

Under a configured outDir the folder sits inside it (out/lua/lib/defold_typescript/). Every generated require names the path its file lands at, so the requires are never yours to edit.

To put the folder somewhere else, set runtime-dir in package.json:

{
  "defold-typescript": {
    "defold-target": "stable",
    "runtime-dir": "vendor/rt"
  }
}

The value is a folder under the output root: folder names joined with /, with no leading slash, no .., no \ or :, and no dot in any folder name, because Lua reads a dot in a require name as a folder separator. A value that breaks a rule fails the build, naming the setting, before anything is written. A source whose own module name is one the build uses internally for these files (lualib_bundle, defold_typescript_timers, defold_typescript_hsm.<module>, defold_typescript_ecs.<module>) fails the build too, since an import of it would load the runtime file instead.

init and upgrade add /lib/defold_typescript/ (or /<runtime-dir>/) to .gitignore, and keep the lines an earlier version added.

A project built by an earlier version has lualib_bundle.lua, defold_typescript_timers.lua and defold_typescript_hsm/ at the output root. The next build or watch deletes each of those files that carries the generated banner and that no source of yours writes, then deletes defold_typescript_hsm/ once it is empty. A file without the banner, such as another toolchain's lualib_bundle.lua, stays. Hand-authored Lua that required the old names (require("lualib_bundle"), require("defold_typescript_timers"), require("defold_typescript_hsm.<module>")) must switch to the new paths, such as require("lib.defold_typescript.lualib_bundle").

Linked source folders

build and watch follow a symbolic link that an include pattern reaches, to a folder or to a file, and compile what it leads to as if it sat at the link's path. A project that shares code through a linked folder builds like any other:

repo/
  .git/
  factory-core/src/save.ts
  game/
    tsconfig.json        "outDir": "out"
    src/main.ts          import { save } from "./core/save";
    src/core  ->  ../../factory-core/src

src/core/save.ts compiles to out/core/save.lua, require("out.core.save") loads it, and its source map points at src/core/save.ts. No output names the link's target and nothing is written into it, so two projects that link one folder each compile their own copy. Discovery never follows a link inside node_modules or inside a folder whose name starts with a dot.

A pattern reaches a link only when it can match a path beneath it, so src/*.ts never looks inside src/assets. Through a link, a pattern matches as it does in a real folder, [...] classes and {a,b} lists included.

A link is followed only when its real target is inside the repository: the nearest folder at or above the project that holds .git, a folder in a plain checkout and a file in a worktree or submodule, or the project itself when there is none. To reach a folder outside it, list that folder in package.json, relative to the project:

{
  "defold-typescript": {
    "link-roots": ["../../shared"]
  }
}

Each entry must name an existing folder. A value that is not a list, an empty entry or a missing folder fails the build, naming the setting.

These fail the build, before anything is written:

  • A link whose target is outside the repository and every link-roots folder. The message names the link, what it points at, and link-roots.
  • One file reached under two paths, such as a link back into a folder include already covers, or a link that loops. The message names both paths.
  • A source under a linked folder in a project with no outDir: its output would land in the link's target. Set compilerOptions.outDir in tsconfig.json so linked sources compile under it.

watch follows edits inside linked folders, rebuilding at the path of every link that reaches the edited file, also after a folder holding a link is renamed, and hot-reloading as it does for any other source.

Flags

  • --editor-compile — after the Lua is written, ask the attached Defold 1.13.2+ editor to compile the project and fail the build on its errors. See Compile in the editor.
  • --editor-focus — with --editor-run, bring the game window to the front. Without --editor-run it does nothing.
  • --editor-run — after the Lua is written, ask the attached Defold 1.13.2+ editor to build and launch the game, print the running engine's URL, and fail the build on its errors. See Run in the editor.
  • --json — emit the build result as a single JSON object (including the warnings array, the lualibRequiredBy list of outputs that require lualib_bundle, the removed list of runtime files the build deleted, and, when either address check found any, a structured unreachableAddresses and crossWorldAddresses array) for agents and scripts. See Agent runbooks.

Compile in the editor

A clean build proves the TypeScript side only. A bad .collection, a missing resource, or a Lua error in the generated code still shows up only when the game runs. build --editor-compile closes that gap: once every output file is on disk it asks the open Defold editor to compile the project, without running it, and waits for the answer.

The editor compiles its own open copy of the project, not the files on disk. Before compiling it reloads every file that changed on disk, so the compile sees the Lua this build wrote and any .gui or .collection another tool saved. An edit made in the editor and not yet saved is compiled as it stands there.

bunx @defold-typescript/cli build --editor-compile

Each issue the editor reports is printed on stderr. An issue in a generated script points at the TypeScript line it came from, with the editor's own location kept beside it:

defold-typescript build: editor: src/player.ts:12:5 (/src/player.ts.script:40): error: attempt to call a nil value

The build exits 1 when the editor reports a failed compile, and 0 when it succeeds, warnings included. Three other answers are reported in one plain line and never fail the build: no editor is open, the editor is older than Defold 1.13.2 (it has no compile command), or the editor refused the request. Under --json the result carries an editorCompile object; see Agent runbooks.

The flag needs the editor open on this project. The compile has no time limit, since the editor answers only once it has finished.

Run in the editor

build --editor-run goes one step further than --editor-compile: once every output file is on disk it asks the open Defold editor to build and launch the game, and waits until the engine reports where it is running.

bunx @defold-typescript/cli build --editor-run

On success it prints the running engine's address on stderr, after any issue lines:

defold-typescript build: editor: running at http://127.0.0.1:57069

The game window opens behind your terminal; add --editor-focus to bring it to the front. Issues are printed and mapped to the TypeScript line exactly as for --editor-compile, and the build exits 1 when the editor reports a failed run. When the run succeeds but the engine never reported its address — it quit early or took too long — the editor's warning is printed with one line saying no target URL came back, and the build still exits 0. No editor, an editor older than Defold 1.13.2, or a refused request is reported in one plain line and never fails the build. Under --json the result carries an editorRun object; see Agent runbooks.

The run builds the project itself, so --editor-run together with --editor-compile posts only the run.

The --editor-* flags belong to build, apart from --editor-compile, which watch also takes. Every other command rejects them, and run starts the engine without the editor.

Headless builds (no editor)

build transpiles TypeScript to Lua; to compile and run the Defold project itself from the command line — no editor — drive Defold's headless build tool (bob) through the bob subcommand:

bunx @defold-typescript/cli bob resolve   # fetch library dependencies
bunx @defold-typescript/cli bob build     # debug build into build/default
bunx @defold-typescript/cli bob bundle    # bundle a platform target
bunx @defold-typescript/cli bob run       # debug build, then launch the game

The first run downloads a version-matched bob.jar into a cache dir ($DEFOLD_TYPESCRIPT_CACHE/bob when set, otherwise $XDG_CACHE_HOME/defold-typescript/bob, falling back to ~/.cache/defold-typescript/bob) and reuses it afterward. bob needs a JVM. It resolves one in order: the --java <path> flag (or DEFOLD_JAVA), then java on your PATH, then the JDK bundled inside an installed Defold editor — which honors DEFOLD_TYPESCRIPT_EDITOR for an install that is not at a conventional path (see pinning-defold-target). If none resolve, the command errors and names all three. Native-extension projects can pass --build-server <url>. bob's exit code propagates, so a failed build fails the command.

bob downloads the bob.jar matching the resolved --defold-target: a pinned version resolves to that version's artifact SHA, a channel (stable/beta/ alpha) resolves to the channel head. Under --json the result reports the resolved defoldVersion, defoldChannel (null for a pinned version), and defoldSha, so you can confirm which engine build bob ran against.

bob run is the convenience composite (Bob has no native run verb): it downloads the target-matched bob.jar, debug-builds into build/default, then launches the game — all pinned to the one resolved SHA, so bob, your typings, and the running engine agree. A native-extension build already produced build/<platform>/dmengine, so bob run launches that; a plain project has no build engine, so bob run fetches the stock engine for the resolved SHA into a sibling engine cache ($DEFOLD_TYPESCRIPT_CACHE/engine, else $XDG_CACHE_HOME/defold-typescript/engine, else ~/.cache/defold-typescript/engine) and records it so a later run reuses it. --java/--build-server thread into the build exactly as for bob build; a cache hit skips the engine download, and an offline download reports an actionable error. A project with an ext.manifest outside its ignored folders and no build engine stops with an error instead of launching the stock engine, which cannot run the extension. A failed build short-circuits with Bob's exit code and never launches. Under --json the composite emits one envelope:

{ "command": "bob", "subcommand": "run", "ok": true, "build": { "exitCode": 0 }, "launch": { "enginePath": "build/arm64-osx/dmengine", "exitCode": 0 } }

Run an existing build (no Bob)

Once build/default holds a compiled project (from bob build or bob run), run launches it directly — no transpile, no Bob, no engine download:

bunx @defold-typescript/cli run                  # launch ./build/default
bunx @defold-typescript/cli run path/to/project  # launch a project in another folder
bunx @defold-typescript/cli run -- --windowed    # pass engine args after --

run launches the native-extension build engine (build/<platform>/dmengine) when present, otherwise the stock engine a prior bob run cached. The game streams to your terminal; the engine's exit code becomes the command's exit code, and Ctrl-C (SIGINT/SIGTERM) forwards to the engine so it shuts down cleanly. Everything after -- passes through to the engine untouched. When no compiled project or engine is found, run errors and names the bob build / bob run command that would produce it.

Under --json the game still streams live to the terminal (a running game is not capturable); a single envelope prints on exit:

{ "command": "run", "ok": true, "enginePath": "build/arm64-osx/dmengine", "projectc": "build/default/game.projectc", "exitCode": 0 }

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. ↩

On this page