Sub topic 6
Splitting a codebase with composite projects and references
This chapter assumes you can read a tsconfig.json, know what a .d.ts file is, and have seen incremental and .tsbuildinfo from earlier chapters. A monorepo with npm workspaces helps but is not required.
Why one big project is slow to rebuild
A single tsconfig.json describes one program. When you change one file, incremental can skip files whose results are still valid. The compiler still has to load the whole program and work out which files are affected. In a large codebase, a change in a widely imported file invalidates many others.
Project references let you cut the codebase into several programs. Each one is checked and emitted on its own. A program that depends on another reads that program's emitted .d.ts files instead of its source. If the dependency did not change, the compiler does not look at its source at all.
This costs some structure:
- You must declare which project depends on which.
- Each project must emit declaration files.
- Projects must build in dependency order.
The layout used in this chapter
The examples use a small workspace with two packages. core is a library. app depends on core.
repo/
tsconfig.base.json
tsconfig.json
packages/
core/
tsconfig.json
src/index.ts
app/
tsconfig.json
src/main.tsShared options live in a base file that each project extends:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true
}
}Making a project composite
A project can be referenced only if it sets composite: true. This is the core package's tsconfig.json:
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"declaration": true,
"isolatedDeclarations": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}composite changes the compiler's behavior in four ways:
| Effect of `composite` | What it means in practice |
|---|---|
| `declaration` defaults to `true` | Every build writes `.d.ts` files. Other projects will read these. |
| `incremental` defaults to `true` | The project writes a `.tsbuildinfo` file, so it gets the incremental behavior from earlier chapters. |
| `rootDir` defaults to the directory holding the `tsconfig.json` | Output paths are predictable. Set it explicitly, as above, when sources live in `src`. |
| Every implementation file must match `include` or `files` | The compiler can then say exactly which files make up the project. Otherwise it reports error TS6307. |
The last rule matters more than it looks. A normal project can pull in an extra file just because something imports it. A composite project cannot, because its file list has to be known before it is built. If you import a file from outside include, you get TS6307: "File is not listed within the file list of project".
The isolatedDeclarations option in this example is explained in a later chapter. It is not required for composite mode. It is shown here because composite libraries are where it pays off most.
Referencing a project
The consumer lists the library in references:
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"outDir": "dist",
"rootDir": "src"
},
"references": [{ "path": "../core" }],
"include": ["src"]
}The path points to a directory containing a tsconfig.json, or to a specific config file.
To see what changes, give core an export and import it from app:
// packages/core/src/index.ts
export interface Greeting {
text: string;
}
export function greet(name: string): Greeting {
return { text: `Hello, ${name}` };
}// packages/app/src/main.ts
import { greet } from "../../core/src/index.js";
console.log(greet("build").text);Without the reference, TypeScript would read core/src/index.ts as source and add it to the app program. It would then fail with a rootDir error, because that file sits outside app/src. With the reference, the compiler sees that the import path belongs to a referenced project. It substitutes that project's output file, core/dist/index.d.ts, and does not parse the .ts source.
In a real workspace you would import @acme/core instead of a relative path. That name resolves through node_modules to the package's package.json, which should point at dist. The project reference still matters in that setup. It tells tsc --build to build core first, and it lets the editor map the package back to its source.
The solution-style root config
Running tsc in each folder works, but you usually want one entry point. A common pattern is a root tsconfig.json that owns no files and only lists the projects:
{
"files": [],
"references": [
{ "path": "packages/core" },
{ "path": "packages/app" }
]
}"files": [] stops the root config from picking up every .ts file in the repository as one huge program. The root exists only to name the projects. Running tsc --build from the repository root builds both of them. The next chapter covers build mode in detail. For now it is enough to know that plain tsc -p . on this root does nothing useful, because there are no files, so you need --build or -b.
What `tsc --build` does with the graph
You can build app and everything it depends on with one command:
tsc --build packages/app --verboseWith --verbose, the output tells you why each project was rebuilt or skipped. A typical sequence on a first run is that core is out of date because its output does not exist, then app is built, because it depends on a project that was just rebuilt. On a second run with no changes, both are reported as up to date.
The check uses file timestamps and, in current TypeScript versions, the information in the .tsbuildinfo file. A project is up to date when its outputs are newer than all of its inputs, including the declaration outputs of the projects it references.
Editor behavior and declaration maps
When you "go to definition" on greet from app, the editor lands on core/dist/index.d.ts, not on core/src/index.ts. This is correct but irritating. Adding "declarationMap": true to core writes a .d.ts.map file next to each declaration file. The editor uses it to jump to the real source.
Declaration maps have a cost: one more file per source file in dist, and they must be published or kept alongside the declarations. For a library you publish, decide whether you want to ship them. For internal packages, they are almost always worth turning on.
Choosing where to cut
Splitting has diminishing returns. Some guidelines:
- Cut along lines that already exist, such as packages, layers, or an app and its shared library. Do not cut by file count.
- Keep the graph acyclic. TypeScript rejects circular references, so if two folders import each other, they must stay in one project or you must move the shared code into a third project.
- Put code that changes rarely at the bottom. A stable
corethat is rebuilt once a week saves more time than a volatile one. - Test files are a common extra split. A
tsconfig.test.jsonthat references the main project lets tests use differenttypessettings without affecting production output. - Avoid many tiny projects. Every project has startup cost: it reads a config, loads the library
.d.tsfiles, and writes its own.tsbuildinfo.
Common errors
| Error | Cause | Fix |
|---|---|---|
| TS6306: Referenced project must have setting "composite": true | The target of a `references` entry is not composite | Add `composite: true` to the referenced project |
| TS6307: File is not listed within the file list of project | A composite project imports a file outside `include` or `files` | Add the file to `include`, or move it into a project that owns it |
| TS6305: Output file has not been built from source file | The consumer was checked before the referenced project was built | Run `tsc --build` so projects build in order, not `tsc -p` |
| TS6059: File is not under `rootDir` | A file outside `rootDir` is being pulled into the program | Import through a reference, or widen `rootDir` |
| TS6202: Project references may not form a circular graph | Two projects reference each other, directly or indirectly | Extract shared code into a third project |
The most common mistake is TS6305. It appears when someone runs tsc -p packages/app directly. Plain -p does not build references, so core/dist does not exist yet. The editor may also show it if you have never built the library.
Summary of the working model
Each composite project is a separate compilation unit with a declared file list, its own output directory, and its own saved state. Consumers check against emitted declarations, not source, so unchanged dependencies cost almost nothing. The price is that every project must emit accurate declarations, and a build order must be enforced. Declaration emit normally needs the full type checker, which is why the next chapters look at isolatedDeclarations as a way to make it cheaper.
Exercise
You run tsc -p packages/app on a fresh clone and get TS6305 saying the output file for core has not been built. app's tsconfig.json already lists core in references, and core has composite: true. What is wrong with the command, and what do you run instead?
Show answer
Plain tsc -p checks one project and does not build the projects it references, so packages/core/dist does not exist yet. Run tsc --build packages/app (or tsc -b). Build mode walks the reference graph, builds core first, and then builds app against core's emitted .d.ts files.
Exercise
A composite project has "include": ["src"], and one source file imports ../scripts/helpers.ts. What error do you get, and name two ways to resolve it.
Show answer
TS6307, because scripts/helpers.ts is not in the project's file list. You can add scripts to include (and adjust rootDir so it covers both folders), or move the helper into a project that owns it and import it through a project reference.
Exercise
Why does adding "files": [] to the solution-style root tsconfig.json matter?
Show answer
Without it, the root config would include every .ts file under the repository by default and compile them as one large program, which defeats the split. With an empty files list, the root owns no source and only names the projects in references, so tsc --build builds each project separately.