Sub topic 6
Splitting a large codebase with project references
This chapter assumes you can read a tsconfig.json, run tsc from the command line, and have already measured a baseline with --extendedDiagnostics. It also assumes that earlier steps (narrowing include, skipLibCheck, incremental) have not brought checking time down far enough.
What project references change
A normal TypeScript program is one graph of source files. Every tsc run parses, binds, and checks the whole graph, or at least decides what has changed in it. In a large repository, that graph can contain tens of thousands of files, and an edit to one file forces the compiler to reason about all of them.
Project references split the repository into several smaller programs. Each program has its own tsconfig.json. A program that depends on another one does not read the other one's source. It reads the other one's emitted .d.ts declaration files.
This changes two costs:
- The compiler does not re-check a dependency's source when you work on a dependent project. It loads declarations, which are cheaper to parse and contain no function bodies to check.
tsc --build(ortsc -b) rebuilds only projects whose inputs changed, and the projects that depend on them.
References do not make each individual check faster. They shrink the amount of code each check touches, and they let the compiler skip projects entirely.
The project graph
Consider a repository with a shared library, a server, and a web client.
The arrows from server and web to core mean "references". core must be built first, and its declaration output is what the other two projects read. The graph must have no cycles. If core referenced server, tsc -b would report an error.
Configuring a referenced project
A project that others reference must set composite: true. This option enforces the rules that make a project safe to consume as declarations:
declarationis turned on automatically.rootDirdefaults to the folder containing thetsconfig.json.- Every source file must be matched by
includeor listed infiles. If a file is imported but not matched, you get error TS6307. incrementalis turned on, so a.tsbuildinfofile is written.
Put the shared settings in a base file.
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true,
"composite": true,
"declarationMap": true
}
}Save that as tsconfig.base.json at the repository root. Then configure core:
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"types": ["node"]
},
"include": ["src"]
}This is packages/core/tsconfig.json. The server project adds a references array that points at the folder containing core's config:
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"types": ["node"]
},
"include": ["src"],
"references": [{ "path": "../core" }]
}The web project looks the same, with "types": [] and its own include. Note that compilerOptions are not inherited through references. Only extends shares settings.
The solution-style root config
At the repository root, create a config that builds nothing itself. It lists the projects to build.
{
"files": [],
"references": [
{ "path": "packages/core" },
{ "path": "packages/server" },
{ "path": "packages/web" }
]
}The empty files array matters. Without it, include defaults to every file under the root, and the root config would become a huge program of its own. That would undo the point of the split. It would also make the editor choose the root config for files that belong to a package.
Building with tsc --build
Run the whole graph from the root:
npx tsc --build --verbose--verbose prints, for each project, whether it is up to date and why not. Typical lines look like "Project 'packages/core/tsconfig.json' is out of date because output 'packages/core/dist/index.d.ts' is older than input 'packages/core/src/index.ts'". This output is your first diagnostic: it tells you whether a change really invalidated what you think it did.
Other useful flags:
| Flag | Effect |
|---|---|
| `--dry` | Prints what would be built without building. |
| `--force` | Rebuilds everything, ignoring up-to-date checks. Use it for a clean baseline. |
| `--clean` | Deletes the outputs of the listed projects. |
| `--watch` | Rebuilds affected projects when files change. |
Two points about --build often surprise people. First, plain tsc -p packages/server does not build core for you. If core/dist is missing or stale, server fails to find declarations or type checks against old ones. Always use --build when references are involved. Second, --build accepts only a limited set of compiler flags. Options like --noEmit do not apply the way they do with a normal tsc run, so set such things in the config files.
Declaration-only emit
Many repositories compile JavaScript with a bundler or another tool, and use tsc only for type checking. References still need the declaration files and the .tsbuildinfo. Set emitDeclarationOnly in the base config:
{
"compilerOptions": {
"composite": true,
"emitDeclarationOnly": true,
"outDir": "dist"
}
}This writes .d.ts files, .d.ts.map files, and .tsbuildinfo, and no .js files. Declaration emit is part of the work, so this is where explicit return annotations on exports pay off. An export whose type must be inferred and printed costs time in every project that exports it.
Measuring whether the split helped
Do not assume the split is faster. Compare the same scenarios before and after.
- Run
npx tsc --build --force --verboseon a clean checkout and record the wall time. This is the cold build. - Run the same command again with no changes. This should finish in a second or two, because every project is up to date.
- Edit a function body in
core(not an exported type) and rebuild. Declarations are unchanged, so dependent projects can be skipped for type checking and, in many versions, only have their timestamps updated. - Edit an exported type in
coreand rebuild. Nowserverandwebmust be checked again. - Run
npx tsc -p packages/server --extendedDiagnosticsaftercoreis built. Compare "Files" and "Check time" with the numbers from the single-program baseline.
The "Files" count for server should drop sharply. It still includes core's .d.ts files, but not core's sources. If the count stays near the old total, a reference is not being used. The usual cause is an import that reaches into another package's source path in a way TypeScript does not map to the referenced project, or a project that is missing from references.
You can confirm which files are used with --explainFiles, the same tool you used for program scope:
npx tsc -p packages/server --explainFiles | grep "core"You should see entries ending in .d.ts under packages/core/dist, not .ts files under packages/core/src.
Gotchas and failure modes
Stale declarations
Because dependents read emitted declarations, a stale dist produces confusing errors that disappear after a rebuild. The fix is a habit: use tsc --build, and in CI build from a clean state with --force at least occasionally.
Source in the editor
In the editor, tsserver by default redirects imports of a referenced project to its source files, not to the built declarations. This is convenient. You get go-to-definition into source and see edits instantly, with no rebuild. The cost is that the editor may load more files than tsc --build does. If a package is huge, the editor can still be slow even when the command line is fast. The compiler option disableSourceOfProjectReferenceRedirect turns off this redirect, and disableReferencedProjectLoad avoids loading referenced projects until needed. Both are set in compilerOptions or tsconfig for large repositories, and the next chapters on tsserver logs show how to tell whether this is your problem.
Too many or too small projects
Each project has startup overhead: its own .tsbuildinfo, its own program, its own global lib parse. A repository with hundreds of tiny projects can be slower than one with a dozen medium ones. Split along real dependency boundaries, such as packages that already have separate package.json files and stable public interfaces. Do not split by folder alone.
Circular dependencies
References must form a directed acyclic graph. If two parts of the code import each other, you cannot put them in separate projects without first breaking the cycle, for example by moving shared types into a third project that both reference.
Wide exported types
If a project's public declarations are large or expensive, such as huge intersections or inferred types that print to thousands of characters, every dependent pays for them when reading the .d.ts file. References cut the repeated checking of function bodies. They do not repair expensive types. Use the trace tools from the earlier chapters on those.
When to use project references
Use them when most of these are true:
- The repository has distinct packages with stable boundaries between them.
- Editing one package should not force a re-check of unrelated ones.
- Cold
--extendedDiagnosticsshows check time dominating, and narrowing scope has already been done. - You can keep CI caches for
.tsbuildinfoand declaration output.
Skip them when the codebase is a single tightly coupled app, when the slowness comes from a few expensive types (fix those first), or when the team will not keep the graph and the include lists accurate.
Exercise
You added packages/core as a reference of packages/server. After npx tsc --build, running npx tsc -p packages/server --extendedDiagnostics still shows about the same file count as before the split. Name two likely causes and one command that helps you check.
Show answer
Likely causes: the references entry for packages/core is missing or points at the wrong folder, or server imports core through a path that resolves to source files outside the referenced project's configured include/rootDir, so TypeScript does not substitute the declaration output. A third cause is that core has not been built, so no .d.ts files exist. Run npx tsc -p packages/server --explainFiles | grep core to see whether core files appear as dist/*.d.ts (the reference is working) or as src/*.ts (it is not).
Exercise
Why does the solution-style root config contain "files": []?
Show answer
Without it, include defaults to all TypeScript files under the root, so the root config would form a large program that duplicates every package. An empty files array makes the root config a pure list of references, so tsc --build builds each package as its own project.