Explain it simply
Project references in plain language
It is like writing a big book in separate chapters. When one chapter refers to another, it does not reread that whole chapter; it looks at the summary page. If you fix a typo in chapter 3, only chapter 3 is reprinted, and the other chapters are left alone as long as the summary did not change.
In TypeScript a chapter is a project with its own tsconfig.json, and the summary page is its .d.ts declaration files. references say which chapter depends on which, and tsc --build reprints only the chapters that changed, in the right order.
Problem → Why → Solution
The problem: one giant tsconfig
A monorepo has a domain package with business rules, a web app that uses it, plus tests and scripts, all under one tsconfig.json. Every tsc run type-checks every file, so CI takes minutes even when you changed one line in a test. Worse, nothing stops the domain code from importing a React component from web, and once that happens the layers are tangled and can no longer be built or published separately.
{
"compilerOptions": { "strict": true, "outDir": "dist" },
"include": ["packages/**/*", "scripts/**/*", "tests/**/*"]
}Why this is slow and fragile
One giant program has one giant cache: any change can affect any file, so the compiler has to consider everything. Project references give each package a boundary with a published contract, its declaration files. The compiler can then rebuild only the packages whose contract or sources changed, and an import across a boundary that is not declared in references becomes a build error instead of a silent dependency.
Core concept: composite projects, declarations and build mode
A project reference splits one big TypeScript program into several smaller ones that know about each other. Each package gets its own tsconfig.json, and a package that depends on another lists it under references. The referenced project must set composite: true, which turns on declaration output and adds rules that make it safe to build on its own: every source file must be matched by include or files, and rootDir defaults to the folder containing the tsconfig.
The key change is what crosses the boundary. When web imports from domain, the compiler does not re-check domain's source files; it reads the .d.ts declaration files that domain's build produced. Declarations are a compact summary of the public types, so checking web stays fast however large domain grows. declarationMap: true also writes .d.ts.map files, so editors can jump from a declaration back to the original .ts source.
tsc --build (or tsc -b) is the build mode that understands references. Given the root tsconfig, it works out the dependency graph, builds domain before web, and writes a .tsbuildinfo file per project that records what it compiled. On the next run it skips every project whose inputs are unchanged. If domain changes but its .d.ts output stays the same, web is not rebuilt at all; only its timestamps are updated. That is where the speed comes from in a large monorepo.
| Command | What it does |
|---|---|
| tsc -b | builds out-of-date projects in dependency order |
| tsc -b --verbose | explains why each project is built or skipped |
| tsc -b --dry | shows what would be built, without building |
| tsc -b --clean | deletes the outputs of all projects |
| tsc -b --force | rebuilds everything, ignoring up-to-date checks |
| tsc -b --watch | rebuilds incrementally as files change |
The root tsconfig.json in the example has files: [] and only references. It is a solution file: it owns no code and just lists the projects, so one command builds them all. Without files: [], the root config would by default include every .ts file below it and compile them a second time, outside the project structure.
- Each package: its own tsconfig
- composite: true emits .d.ts
- references draw the graph
- tsc -b builds only what changed
Downstream projects see a package's declarations, not its source; that is what keeps checks fast.
General pattern (package tsconfig)
{
"compilerOptions": {
"composite": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"],
"references": [{ "path": "../<dependency>" }]
}Give every package that can be referenced composite: true, keep source and output folders apart, and list every package this one imports under references. A path points at a folder containing tsconfig.json, or at the config file itself.
Worked example: the root solution file
This is the tsconfig.json at the repository root. packages/domain and packages/web each have their own composite tsconfig, shown in the deeper section below. Running tsc --build --verbose from the root for the first time prints output like the block below (times and absolute paths will differ).
{
"files": [],
"references": [
{ "path": "./packages/domain" },
{ "path": "./packages/web" }
]
}Code breakdown
- No files of its own
"files": [],The root config compiles nothing itself, so package sources are never compiled a second time outside their project boundaries.
- List the projects
"references": [The projects tsc -b should build. The build order is computed from each project's own references, not from the order of this list.
- Point at a project folder
{ "path": "./packages/domain" },The path points at a folder that contains a tsconfig.json. If that project lacks composite: true, tsc -b stops with TS6306.
10:15:02 AM - Projects in this build:
* packages/domain/tsconfig.json
* packages/web/tsconfig.json
* tsconfig.json
10:15:02 AM - Project 'packages/domain/tsconfig.json' is out of date because output file 'packages/domain/tsconfig.tsbuildinfo' does not exist
10:15:02 AM - Building project '/repo/packages/domain/tsconfig.json'...
10:15:03 AM - Project 'packages/web/tsconfig.json' is out of date because output file 'packages/web/tsconfig.tsbuildinfo' does not exist
10:15:03 AM - Building project '/repo/packages/web/tsconfig.json'...Setting up the two packages
domain depends on nothing. It sets composite: true and declarationMap: true, and keeps source in src and output in dist.
{
"compilerOptions": {
"composite": true,
"declarationMap": true,
"strict": true,
"module": "nodenext",
"target": "es2022",
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}web references domain. When it imports through the workspace package name (for example @app/domain) and domain's package.json points types and exports at dist, the compiler reads domain's .d.ts files. If domain tries to import from web instead, the build fails with TS6307 (or TS6059 for rootDir), because that source file is not part of domain's project.
{
"compilerOptions": {
"composite": true,
"strict": true,
"module": "nodenext",
"target": "es2022",
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"],
"references": [{ "path": "../domain" }]
}npx tsc -b --verbose # first build: domain, then web
npx tsc -b --verbose # nothing changed: both reported "up to date"
npx tsc -b --dry # what would be built, without building
npx tsc -b --clean # delete outputs; next build starts freshChange only a function body in domain and build again. --verbose rebuilds domain, then reports web as "up to date with .d.ts files from its dependencies" and only updates its timestamps. Change an exported function signature and web is fully rebuilt.
In real projects
Project references in real projects
Project references matter most once a codebase has several packages or a slow type-check:
- Monorepos (pnpm, npm or Yarn workspaces): each package has a composite tsconfig plus a root solution file, and CI runs tsc -b once. With the .tsbuildinfo files cached between runs, unchanged packages are skipped.
- Separating app code from tests and tooling: a src project and a test project that references it keep test-only types and globals out of the production build.
- Enforcing architecture: if domain does not reference web, domain cannot import from web, which keeps business rules free of UI code.
- Publishing libraries: the declaration files a composite project emits are exactly what you ship in a package's types field, so consumers get types without your source.
About the new compiler
The TypeScript team is also building a native (Go-based) compiler to make all of this faster. Check the official release notes for its current status and supported options before relying on it; the project-reference basics in this lesson stay the same.
Common mistakes
Common mistakes with project references
Forgetting composite: true on a referenced project
tsc -b stops with error TS6306: Referenced project ... must have setting "composite": true. Every project that appears in someone's references needs it.
Running plain tsc instead of tsc -b
Without --build, tsc compiles only the one project and does not build its references first, so you get "Cannot find module" or missing-declaration errors. Use tsc -b in scripts and CI.
Deleting dist but keeping .tsbuildinfo
If you delete output folders by hand and the .tsbuildinfo files remain, tsc -b may consider the projects up to date and build nothing, while downstream imports fail because dist is gone. Remove outputs with tsc -b --clean or rebuild with --force, and git-ignore both build info and dist.
Creating a reference cycle
If domain references web and web references domain, tsc -b refuses with TS6202: Project references may not form a circular graph. Move the code both need into a third package.
Mini challenge
Mini challenge: compute the build order like tsc -b
To understand what tsc -b does behind the scenes, write a TypeScript function buildOrder that takes a map of project configs and returns the build order. Every project must come after the projects it references. Like tsc, it must reject a reference without composite: true and any circular reference.
- Each project appears after all of its references
- Throw if a referenced project does not set composite: true
- Throw an error showing the path, such as a -> b -> a, when there is a cycle
- Print the result for a valid graph and for a graph with a cycle
type ProjectConfig = {
composite?: boolean;
references?: string[];
};
const projects: Record<string, ProjectConfig> = {
"packages/web": { composite: true, references: ["packages/domain", "packages/ui"] },
"packages/ui": { composite: true, references: ["packages/domain"] },
"packages/domain": { composite: true },
};
function buildOrder(all: Record<string, ProjectConfig>): string[] {
// TODO: depth-first visit; track a "visiting" / "done" state per project
// TODO: throw if a referenced project is missing composite: true
// TODO: throw with the cycle path if you reach a project that is "visiting"
return [];
}
// TODO: print the order for projects, then try a two-project cycleExpected: It prints packages/domain -> packages/ui -> packages/web, then Circular reference: a -> b -> a.
Show hint
Visit a project's references recursively before adding the project itself (depth-first). Mark projects on the current path as "visiting"; reaching one of them again means a cycle.
Show solution
type ProjectConfig = {
composite?: boolean;
references?: string[];
};
const projects: Record<string, ProjectConfig> = {
"packages/web": { composite: true, references: ["packages/domain", "packages/ui"] },
"packages/ui": { composite: true, references: ["packages/domain"] },
"packages/domain": { composite: true },
};
function buildOrder(all: Record<string, ProjectConfig>): string[] {
const order: string[] = [];
const state = new Map<string, "visiting" | "done">();
function visit(name: string, trail: string[]): void {
if (state.get(name) === "done") return;
if (state.get(name) === "visiting") {
throw new Error(`Circular reference: ${[...trail, name].join(" -> ")}`);
}
const project = all[name];
if (!project) throw new Error(`Unknown project: ${name}`);
state.set(name, "visiting");
for (const dep of project.references ?? []) {
if (!all[dep]?.composite) throw new Error(`${dep} must set "composite": true`);
visit(dep, [...trail, name]);
}
state.set(name, "done");
order.push(name);
}
for (const name of Object.keys(all)) visit(name, []);
return order;
}
console.log(buildOrder(projects).join(" -> "));
try {
buildOrder({
a: { composite: true, references: ["b"] },
b: { composite: true, references: ["a"] },
});
} catch (error) {
console.log(error instanceof Error ? error.message : error);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Give each package its own tsconfig with composite: true, and list the packages it depends on under references.
- Downstream projects read .d.ts declarations instead of source, which keeps checks fast and boundaries explicit.
- tsc -b builds in dependency order and uses .tsbuildinfo to skip projects that did not change.
- Keep files: [] in the root solution file; debug with --verbose and reset with --clean or --force.
Announcing TypeScript 7.0 — TypeScript