Sub topic 11
Build order and the no-cycles rule
This chapter explains how tsc --build decides the order in which to build projects, and why the references graph must not contain a cycle. It assumes you can write a composite project with references, as in the earlier chapters, and that you have run tsc --build at least once.
The references field defines a graph
Each project is a node. Each entry in references is a directed edge from the project that lists it to the project it depends on. In the example repository, packages/app lists packages/core, so the edge points from app to core.
The edge means: "my type checking needs the declaration output of that project." The compiler cannot check app until core has produced its .d.ts files, so core must be built first.
Build mode turns this into a build order by walking the graph depth first. It visits a project's references before the project itself. The result is a topological order: every project appears after everything it depends on.
Suppose the repository now has three projects:
sharedholds types and constants and references nothing.corereferencesshared.appreferencescoreandshared.
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"],
"references": [{ "path": "../core" }, { "path": "../shared" }]
}That is packages/app/tsconfig.json. Running a dry build shows the order the compiler chose:
tsc --build --dry --verboseThe first lines of the output look like this, with timestamps left out:
Projects in this build:
* packages/shared/tsconfig.json
* packages/core/tsconfig.json
* packages/app/tsconfig.json
* tsconfig.jsonshared comes first even though app lists core before it. The walk reaches core, finds that core needs shared, and so shared is built before either of them.
What decides the order
Three rules cover almost every case:
- A project always builds after every project it references.
- Projects with no dependency path between them have no guaranteed relative order. In practice the compiler follows the order of the
referencesarray and the order of the root's list, so treat any such order as incidental. - Each project is built at most once per
tsc --buildrun, however many projects reference it. In the example,sharedis referenced twice and built once.
The order is computed per invocation from the project you name on the command line. If you run tsc --build packages/core, only core and its dependencies are in the build. app is not touched. This is useful when you are working on a lower layer and want fast feedback.
References are not transitive for imports. If app imports from shared directly, app needs shared in its own references, even though core already references it. Without that entry, app may fail to resolve the import or may read shared's source files instead of its declarations. The error that follows usually says a file is not listed in the project or is outside rootDir.
What happens when an upstream project fails
The compiler builds a project only if its dependencies built cleanly. If core has a type error, tsc --build reports that error and does not build app. It prints a message saying app was skipped because its dependency has errors.
This is intentional. app would otherwise be checked against declaration files that were never produced, or against stale ones from a previous build. You get the root cause once, instead of a cascade of misleading errors downstream.
Two practical consequences follow:
- Fix errors from the top of the output, because the first failing project in build order is usually the real problem.
- A project that was skipped does not have a fresh
.tsbuildinfo, so it will be considered out of date on the next run and rebuilt.
The no-cycles rule
The graph of references must be acyclic. If project A references B and B references A, there is no valid build order. A cannot be checked until B's declarations exist, and B cannot be checked until A's declarations exist.
Here is a cycle that is easy to create by accident. core needs a type that lives in app, so someone adds a reference back:
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"],
"references": [{ "path": "../app" }]
}This is packages/core/tsconfig.json, and app already references core. Running the build now fails before any compilation starts:
tsc --builderror TS6202: Project references may not form a circular graph. Cycle detected: ...After the message comes the list of project paths that form the loop. Read that list to see which edge to remove. The check runs while the compiler is building the graph, so you get this error even if no file in core imports anything from app yet.
Cycles can be longer than two projects. A references B, B references C, and C references A is just as invalid. The cycle listing in the error shows the whole path.
Breaking a cycle
A cycle means two projects each depend on something the other owns. You cannot fix it with a compiler option. You fix it by changing where code lives. These are the usual approaches:
- Extract the shared part into a lower project. Move the types or functions both sides need into a new project, such as
shared, and have both reference it. This is the most common fix and the one to try first. - Invert the dependency. If
coreneeds behavior thatappprovides, define an interface incoreand haveappimplement it and pass it in.corethen depends on nothing inapp. - Merge the projects. If two projects cannot be separated cleanly, they may be one unit. Put them in a single project and drop the reference.
- Check whether the edge is real. Sometimes the reference was added to make an editor error go away, and nothing needs it. Remove it and see whether the build still passes.
After extracting, the graph returns to the shape shown in the diagram earlier in this chapter: shared at the bottom, core above it, and app on top.
Layering as a design tool
Because the graph must be acyclic, it forces a layered structure. You can use that on purpose:
| Layer | Example project | May reference |
|---|---|---|
| Foundation | `shared` | nothing |
| Libraries | `core` | foundation |
| Applications | `app` | libraries, foundation |
| Tests and tooling | `app-tests` | anything below it |
Test projects sit at the top, because nothing should depend on them. A project that other projects reference should not itself depend on its consumers, and the table makes that visible.
A narrow graph also helps build speed. When shared changes, everything above it is out of date. When app changes, only app is out of date. Keeping widely used code in small, stable lower projects means fewer edits trigger large rebuilds.
Checking the graph before a build
--dry with --verbose is the fastest way to inspect the order without building:
tsc --build --dry --verboseFor each project it reports whether the project is up to date and, if not, which input is newer than which output. Use it when a build order surprises you, or when you want to confirm that a project is being rebuilt only because a dependency changed.
For a visual check on a large repository, you can print the graph from the command line. This script reads each project's references and prints one line per edge. It assumes the tsconfig.json files contain plain JSON with no comments:
import { readFileSync } from "node:fs";
import { dirname, join, relative } from "node:path";
const root = process.argv[2] ?? ".";
const projects = process.argv.slice(3);
for (const project of projects) {
const file = join(root, project, "tsconfig.json");
const config = JSON.parse(readFileSync(file, "utf8"));
for (const ref of config.references ?? []) {
const target = relative(root, join(dirname(file), ref.path));
console.log(`${project} -> ${target}`);
}
}Run it with the repository root first and then each project directory, for example node print-graph.js . packages/core packages/app. The output is one from -> to line for each edge, which you can paste into a diagram tool.
Common mistakes
- Adding a reference to silence an editor error. This can create a cycle and hides a layering problem. Ask why the import needs the other project.
- Relying on listing order for independent projects. The order of unrelated projects can change when someone edits a
referencesarray. If order matters, add a real reference. - Forgetting the direct reference. Importing from a project without listing it in
references, because another project already lists it. - Referencing a project without
composite. The compiler reports that the referenced project must havecomposite: true. Fix it in the referenced project, not in the one that references it.
Exercise
A repository has three composite projects. ui references core. core references shared. A developer then adds { "path": "../ui" } to the references of shared because a shared type needs a ui component type. What error does tsc --build report, and how would you fix it?
Show answer
The compiler reports TS6202, "Project references may not form a circular graph", and lists the cycle ui, core, shared, ui. The fix is to remove the shared to ui reference and move the needed type out of ui into shared (or into a new lower project). If shared needs behavior from ui, define an interface in shared and have ui implement it. The reference must point downward so the graph stays acyclic.
Exercise
app imports a function from shared and also uses core. app references only core, and core references shared. Why is that configuration fragile, and what should change?
Show answer
References are not transitive for imports. app imports shared directly, so app should list shared in its own references. Without it, the import may be resolved to shared's source files rather than its declarations, which produces errors about files outside rootDir or not listed in the project. Adding { "path": "../shared" } to app's references fixes this, and it does not create a cycle.