Debugging TypeScript in Defold
Set a breakpoint in a .ts file, press F5, and step through your own source while Defold runs the transpiled Lua.
This works because every build already emits what a debugger needs: a <name>.ts.script.map source map beside each chunk, and a --# sourceMappingURL= trailer pointing at it. The Local Lua Debugger extension reads those maps, so a breakpoint resolves to the right generated line with no extra wiring.
Quick start
-
Wire the project. From the project root:
bunx @defold-typescript/cli setup-debugThis writes the whole debug path, and is safe to re-run.
-
Do the two steps it cannot. Both are reported when the command finishes:
- Install the Local Lua Debugger extension in VS Code (
tomblind.local-lua-debugger-vscode). - Run Project -> Fetch Libraries in the Defold editor, so the
lldebuggermodule is downloaded.
- Install the Local Lua Debugger extension in VS Code (
-
Build, then launch. Transpile, compile the Defold project, then pick Defold: Debug (TypeScript) in VS Code and press F5.
Each part is covered below. If you would rather wire things by hand, the manual setup section walks the same path step by step.
What setup-debug writes
Six files — three in your project, three under .vscode/:
game.project— thelldebuggerlibrary dependency, at the next freedependencies#Nindex. Skipped if it is already there.resolvelists it aslldebugger.debug <- <url> (debugger, declared by setup-debug).- your entry script — a gated
lldebugger.start()bootstrap, inside a managedBEGIN/ENDblock. lldebugger.debug.d.ts— the ambient@noResolution declare module, written next to the entry script so the sameinclude1 pattern covers both..vscode/launch.json— alua-localconfiguration named Defold: Debug (TypeScript) whoseprogram.commandisbun..vscode/defold-debug.ts— a self-contained Bun launcher that downloads and runs the engine with its stdio inherited, the pipe Local Lua Debugger attaches over. Nobashand no Git Bash, unlike the upstreamlua-localtemplate..vscode/extensions.json— recommendstomblind.local-lua-debugger-vscode, the one third-party extension debugging requires. (Defold Kit is no longer recommended; sumneko Lua is an optional aid for reading generated Lua. See editor setup.)
The same command is available as the defold-typescript:setup-debug mise task.
Where breakpoints bind
Two fields in the launch configuration decide this, and both are derived from your include1 and outDir:
scriptFilescovers scripts, gui scripts, render scripts and plain.luamodules, at the paths the build actually writes them. Editor scripts are excluded — they are not game chunks.scriptRootsnames both the output side and the source side, so the chunk path Defold runs and the map's baresourcesentry each resolve back to a file on disk.
Local Lua Debugger (0.3.0 and later) pre-scans scriptFiles for the emitted --# sourceMappingURL= trailers before the session starts. If no pattern covers an output, no source-mapped breakpoint in it will bind — which is why these two fields track your tsconfig.json instead of being fixed.
Picking the entry script
setup-debug follows the Defold boot path rather than guessing:
- It starts at
game.project's[bootstrap] main_collection, walks the referenced.collectionfiles (including nestedcollection:references), and collects every.ts.scriptcomponent, mapping each back to its source.ts. - A single boot-path script is wired automatically. With several, pass
--script <path>, or run interactively (without--json) to pick from a prompt;--jsonerrors and names the candidates. - If the boot path reaches no
.ts.script— or there is no[bootstrap]— it falls back to scanning your configured sources (everyinclude1 pattern,src/**/*.tsout of the box) for a lifecycle-factory call:defineScript,defineGuiScriptordefineRenderScript.
The target must be a configured production source, not merely a path an include pattern happens to match. A declaration file, or a file under a generated or dependency tree such as build, node_modules or .defold-types, is refused by name and cause. So is a boot-path .ts.script component that no configured source builds — rather than falling back to the factory-call scan and wiring an unrelated script.
The bootstrap stays in exactly one script: a stale managed block in any other configured source is stripped on each run.
The entry script may export runtime values like any other script. The component runs the block's gated lldebugger.start() before it loads the module those exports compile into, so the debugger is attached before any of them is built.
Re-running it
setup-debug is idempotent, and every .vscode file merges additively into what you already have — your own launch configurations, recommendations and an edited defold-debug.ts all survive.
- A managed block whose wording has drifted is refreshed in place, and a legacy single-marker block from an older version is upgraded.
- The ambient declaration is regenerated whole, or skipped when already current. A copy an older version left at
src/lldebugger.debug.d.tsis removed, unless you have edited it.
upgrade and init . --force also refresh the launch configuration when include or outDir moves — see init for what else that flag re-syncs. Either one rewrites scriptFiles and scriptRoots in place on a configuration that is already there, creates none where there is none, and leaves every other key alone. Plain init refuses an already-scaffolded project rather than refreshing it.
Those two forced routes also refresh an existing .vscode/defold-debug.ts when its checksum proves it is generated. This includes launchers from older releases and files whose line endings became CRLF on Windows. An absent launcher stays absent. A customized launcher is preserved, and a warning names the skipped path and checksum mismatch; delete it and run setup-debug to install the current generated launcher.
On all three routes, a run with nothing to change does not rewrite launch.json at all, so your JSONC comments and hand formatting survive untouched. A run that does have a change to make reserializes the file, and comments in it are lost.
When it refuses
setup-debug is all-or-nothing: a project it cannot wire is left byte-identical. It stops, naming the file and the reason, when
.vscode/launch.jsonis not valid JSON or JSONC, so the configuration cannot be merged into it, or- the entry script cannot be resolved, for any of the reasons above.
Otherwise the plain output names the script it added to, any scripts the block was removed from, and the boot-path trace behind the choice. --json emits a machine-readable {command, ok, written, actions, manualSteps, addedTo, removedFrom, bootPath} result.
Launching a debug session
The launcher runs whatever already sits under build/; it does not compile the Defold project itself. The CLI build loop produces both artifacts headlessly, with no editor:
-
Transpile, so the
.ts.scriptand.ts.script.mapfiles are current —bunx @defold-typescript/cli build, or keepwatchrunning. -
Compile the Defold project, so
build/default/game.projectcexists:bunx @defold-typescript/cli bob resolve # first time / after editing dependencies bunx @defold-typescript/cli bob build # debug build into build/defaultbob buildruns Defold's headlessbobtool — see Build for the JVM and cache details. Native-extension projects must add--build-server <url>sobobcan compile the engine remotely. -
Launch. In VS Code, select the Defold: Debug (TypeScript) configuration and start it (F5). The Bun launcher resolves the engine, then runs
build/default/game.projectc. Breakpoints in your.tsfiles resolve through the emitted<name>.ts.script.map.
To debug-build and launch in one step, outside the editor debugger, bunx @defold-typescript/cli bob run composes the build with an engine launch, pinning bob, typings and the running engine to one resolved SHA.
Which engine the launcher runs
It prefers the native-extension build engine at build/<platform>/dmengine when that exists; on macOS that folder is bob's <arch>-osx, such as build/arm64-osx/dmengine. Otherwise it downloads a stock engine from d.defold.com next to the launcher, at .vscode/dmengine. The download is a one-time fetch per platform, and the scaffolded .gitignore keeps the binary out of version control. 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.
setup-debug never overwrites an existing .vscode/defold-debug.ts. Each launcher it creates carries a checksum of its generated body, which lets upgrade refresh an unmodified copy without treating an edited one as tool-owned. To reset a customized launcher, delete the file and run setup-debug again.
Native-extension runtime libraries
On a build-engine run the launcher checks each supported native extension's declared runtime libraries and warns-and-continues if any are missing. It never fetches them, because no extension has a fetchable source yet.
OpenAL on Windows is currently the only declared extension: native-extension builds need OpenAL32.dll and wrap_oal.dll placed by hand next to the build engine, in build/x86_64-win32/. The Defold build server does not ship these runtime DLLs and no Defold-hosted archive serves them, so the launcher cannot fetch them; the copy fix is tracked upstream at defold/defold#11860. When they are missing on a Windows build-engine run you get a one-line reminder, and the run continues.
macOS and Linux declare no native-extension runtime libraries and resolve OpenAL from the system, so nothing needs placing.
Building from the editor instead
The CLI build loop above is the primary path and needs no editor. If you prefer, you can still produce build/default/game.projectc (and any native-extension engine) by building from the Defold editor before launching from VS Code.
Either way, the launcher never builds for you. It stops when build/default/game.projectc does not exist yet. When a generated script, a generated .lua module or game.project is newer than its compiled copy under build/default, it names up to three of them, warns that the game runs the old code so breakpoints may not bind, and launches anyway.
Manual setup
setup-debug automates exactly the steps below; follow them to wire a project by hand, or to see what the command did.
-
Install the recommended extension. Open the project in VS Code and accept the Local Lua Debugger recommendation, or install
tomblind.local-lua-debugger-vscodedirectly. -
Add the
lldebuggerlibrary to Defold. Ingame.project, add the dependency:https://github.com/defold-typescript/toolchain/releases/download/lldebugger-v1/lldebugger.zipThis is our vendored, MIT-licensed snapshot of
ts-defold/defold-lldebugger, hosted from this repo's releases — that is why the URL differs from the upstream docs. Then run Project -> Fetch Libraries in the Defold editor so thelldebuggerLua module is available torequire. -
Declare the module. Create an ambient declaration named
lldebugger.debug.d.tsnext to your entry script —src/lldebugger.debug.d.tsin the scaffold's layout — so it sits under the sameinclude1 pattern:/** @noResolution */ declare module "lldebugger.debug" { export function start(): void; }It has to be a
.d.ts, not an inlinedeclare modulein a.ts: undermoduleResolution: "Bundler"an inline augmentation that the entry script also imports fails to type-check. With the declaration here, TypeScript leaves the module unresolved and TypeScriptToLua (TSTL) keeps the literal path, so the emitted Lua isrequire("lldebugger.debug")followed bylldebugger.start(). -
Start the debugger from your entry script. Add the entry near the top, gated so it only runs in a debug build:
// defold-typescript:setup-debug BEGIN — managed block, do not edit import * as lldebugger from "lldebugger.debug"; if (sys.get_engine_info().is_debug) { lldebugger.start(); } // defold-typescript:setup-debug ENDThe
is_debugguard keeps the call inert in release builds, so the entry is safe to leave in shipped code — it only activates in a debug build with the debugger attached. TheBEGIN/ENDsentinels are what let a latersetup-debugrun refresh the block if its wording changes.
The engine debugger
From Defold 1.14.1, debug and headless engines carry their own debugger, which speaks the Debug Adapter Protocol (DAP). The Defold editor's debugger runs on it, and other DAP clients can attach to it.
It steps through the generated Lua and reads no source maps. A breakpoint in a .ts file binds only through the setup-debug path this page describes.
The two debuggers stay apart by how the engine is launched. lldebugger.start() does nothing unless VS Code's Local Lua Debugger launched the engine, and the engine debugger installs no hook until its listener starts. While a client is attached, it owns Lua's debug hooks, so use one debugger per session.
Calling the engine debugger from TypeScript
debugger is a reserved word in TypeScript, and the API reference does not document the module, so the types package declares nothing for it. Declare it in your own .d.ts beside your scripts, under the same include1 pattern as lldebugger.debug.d.ts:
/** @customName debugger */
declare const debugger_:
| {
/** Start the engine's debug listener and return its port; pass 0 for a free port. */
start(this: void, port?: number, address?: string): number;
}
| undefined;@customName makes TSTL write the Lua global debugger wherever your code says debugger_. The global is undefined in release and web builds and on engines older than 1.14.1, so call it through ?.:
import { defineScript } from "@defold-typescript/types";
export default defineScript({
init() {
const port = debugger_?.start(0);
if (port !== undefined) {
print(`engine debugger listening on port ${port}`);
}
},
});The script compiles to:
local ____exports = {}
function init()
local port = debugger and debugger.start(0)
if port ~= nil then
print("engine debugger listening on port " .. tostring(port))
end
end
return ____exportsstart raises a Lua error when it cannot bind the port.
See also
- Script lifecycle — typing
selfand the lifecycle hooks you will step through. - Code editor setup — the rest of the scaffolded
.vscode/config and the watch loop.