Sub topic 5
Reusing work with incremental builds
This chapter shows how --incremental lets tsc skip type checking for files that have not been affected by a change. It also covers what the .tsbuildinfo file stores, how to measure the gain, and the cases where the cache is thrown away.
It assumes you have run tsc --extendedDiagnostics and can read its output. The earlier chapters on compiler phases and baseline measurement cover that. You should also be comfortable with tsconfig.json, include, and outDir.
What incremental mode does
Without incremental mode, every tsc run starts from nothing. It finds files, parses them, binds them, checks them, and emits them, even if you changed one line. Most of that work produces the same answer as last time.
With incremental turned on, tsc saves a record of its work to a file ending in .tsbuildinfo. On the next run it reads that file, compares it with the current files, and works out which files could have a different result. It re-checks only those files.
The saved file holds:
- A version identifier (a content hash) for each source file.
- The compiler options that affect results.
- The module-level relationships between files, meaning which file imports which.
- A "signature" for each file, which is a hash of its exported declarations.
- The diagnostics (errors) from the previous check, so unchanged files can report them again without re-checking.
The cache stores file hashes, not modification times. A fresh git checkout that gives files new timestamps but identical content still hits the cache.
What is still paid on every run
Incremental mode does not skip everything. tsc must still build the program: read the tsconfig.json, resolve the file list, and resolve module imports. It also has to detect which files changed. In the --extendedDiagnostics output, expect the check and emit phases to shrink the most. Parse and bind times often stay close to the baseline.
If your baseline shows most time in "Parse time" or "I/O Read time" (too many files in the program), incremental mode helps little. Fix the program scope first.
Turning it on
Add incremental to tsconfig.json. Since TypeScript 4.0 you can combine it with noEmit, which makes it useful for type-check-only scripts.
{
"compilerOptions": {
"noEmit": true,
"incremental": true,
"tsBuildInfoFile": "./node_modules/.cache/tsc/app.tsbuildinfo",
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}tsBuildInfoFile is optional. When you omit it, tsc picks a location for you:
- If
outDiris set, the file goes insideoutDir. - Otherwise it goes next to the
tsconfig.json, named after it (for exampletsconfig.tsbuildinfo).
Putting it under node_modules/.cache keeps it out of your source tree and out of version control. If you leave the default, add *.tsbuildinfo to .gitignore.
You can also pass the flag on the command line, with no config change:
npx tsc --noEmit --incremental --extendedDiagnosticsMeasuring the benefit
Do not assume incremental mode helped. Measure a cold run (no cache), a warm run (nothing changed), and a run after a small edit.
# Cold: remove any existing cache first
rm -f node_modules/.cache/tsc/app.tsbuildinfo
npx tsc -p tsconfig.json --extendedDiagnostics | grep -E "Check time|Total time"
# Warm: nothing changed since the last run
npx tsc -p tsconfig.json --extendedDiagnostics | grep -E "Check time|Total time"
# After a small edit: append a comment to one file, then run again
echo "// touch" >> src/index.ts
npx tsc -p tsconfig.json --extendedDiagnostics | grep -E "Check time|Total time"A typical result has three patterns:
| Run | Check time | What happened |
|---|---|---|
| Cold | Same as your baseline | No cache, every file is checked and the cache file is written |
| Warm, no changes | Close to zero | Every file's previous result is reused |
| After a small edit | Small fraction of cold | Only the changed file and files affected by it are re-checked |
The exact numbers depend on your project. The shape matters: if the warm run is not much faster than the cold run, something is invalidating the cache. See the section on invalidation below.
Which files get re-checked
When you edit a file, tsc must decide who else could be affected. It uses the signature mentioned earlier.
- The edited file is always re-checked.
tscrecomputes the edited file's signature, the hash of its exported shape.- If the signature is unchanged, nothing that imports the file can behave differently, so the importers are skipped.
- If the signature changed, the files that import it are re-checked. Their own signatures are then compared, and the change can ripple further.
Here is an example. The two files below show the difference between a body-only edit and a signature edit.
// src/price.ts
export function totalCents(items: { cents: number }[]): number {
return items.reduce((sum, item) => sum + item.cents, 0);
}// src/report.ts
import { totalCents } from "./price";
export function summary(items: { cents: number }[]): string {
return `Total: ${totalCents(items)} cents`;
}If you change the body of totalCents (say, to ignore negative values), the exported signature (items: { cents: number }[]) => number is the same. Only price.ts is re-checked. If you change the return type to string, the signature changes, and report.ts is re-checked too.
Why explicit annotations help here
The signature is built from the declared exports. When a function has an inferred return type, the inferred type becomes part of the signature. A body edit can then change the inferred type and force importers to be re-checked. With an explicit return type, a body edit that keeps the contract cannot change the signature. This is the same advice from the type-shape chapter, with an extra benefit: it limits the ripple of changes.
What invalidates the cache
Some changes make tsc discard the cached results for many or all files. If your warm runs are slow, check these.
- Compiler options that affect checking. Changing
strict,target,lib,module,moduleResolution, ortypesforces a full re-check. Options that affect only emit may force only a re-emit. - A different TypeScript version. The cache records the compiler version. Upgrading, or running a different version in CI than on your machine, produces a full run.
- Global declarations. Files with no
importorexportare scripts, and their declarations are visible everywhere. A change to a script file can affect every file, sotsctreats it as widely affecting. - Changes in
node_modulestypes. When a.d.tsfile in a dependency changes, files that depend on it are re-checked. Updating a widely used package such as@types/nodecan touch most of the program. - A deleted or moved cache file. If the
.tsbuildinfofile is missing, the run is cold.
If you suspect a stale or corrupted cache, delete the .tsbuildinfo file and run again. That is always safe: the next run is slower and rebuilds it.
Using the cache in continuous integration
On a developer machine the cache persists between runs. On CI, every job usually starts on a clean machine, so every run is cold unless you restore the cache.
The idea is to save the .tsbuildinfo file at the end of one job and restore it at the start of the next.
- Use a cache key that includes your lockfile and the TypeScript version, so an upgrade does not reuse an incompatible file. A mismatch is not dangerous, since
tscdiscards a cache it cannot use, but it wastes the restore. - Restore from the most recent cache on the main branch when no exact match exists. A slightly stale cache still saves most of the work.
- Keep
tsBuildInfoFileat a fixed path so the cache step can find it.
Because the cache is keyed on file contents rather than timestamps, restoring it onto a freshly checked-out repository works.
# Example CI steps (after restoring node_modules/.cache/tsc from your CI cache)
npx tsc -p tsconfig.json --extendedDiagnostics
# Save node_modules/.cache/tsc back to the CI cache after the jobIncremental mode and the watch mode
tsc --watch and your editor already keep the program in memory and re-check only what changed. They gain nothing from .tsbuildinfo while they are running. The file helps at startup: with --incremental, tsc --watch can begin from the saved state instead of checking everything on first launch. The editor's language server (tsserver) does not read .tsbuildinfo, so incremental mode does not fix a slow editor. That case is covered in the tsserver chapter.
Incremental mode versus project references
Both features reuse earlier work, but at different scales.
| Row | `incremental` | Project references (`composite`, `tsc --build`) |
|---|---|---|
| Unit of reuse | Files within one program | Whole sub-projects |
| Cache file | One `.tsbuildinfo` per program | One `.tsbuildinfo` per project |
| Needs config changes | One option | Split `tsconfig.json` files and `references` |
| Skips loading unchanged code | No, the program is still built | Yes for up-to-date projects, which are read from their `.d.ts` output |
composite: true implies incremental: true. If you adopt project references later, you keep the same mechanism. Start with plain incremental and move to references only when the whole program is still too large to load on each run. The next chapter covers that step.
Common mistakes
- Measuring only the cold run. The first run after enabling
incrementalis not faster, and is slightly slower because it writes the cache. Always compare warm runs. - Writing the cache into a folder that is cleaned. If a build step wipes
outDir, it deletes the.tsbuildinfoinside it. Move the file withtsBuildInfoFile. - Sharing one
tsBuildInfoFilebetween two configs. Two differenttsconfig.jsonfiles writing to the same path overwrite each other and are always cold. Give each config its own path. - Expecting a faster first run in CI. Without a restored cache, every CI run is a cold run.
- Treating
--incrementalas a fix for a slow type. It saves re-checking unchanged files. A single expensive type in a changed file is still expensive every time that file is checked. Use the trace tools for that.
Exercises
Exercise
You enable incremental and run tsc --noEmit --extendedDiagnostics three times with no edits in between. The first run takes 40 seconds and the second and third take 38 seconds. What should you check, and what are two likely causes?
Show answer
The cache is not being reused. Check that the .tsbuildinfo file exists after the first run and that its path does not change between runs. Likely causes: the file is written to a folder that is deleted between runs (or tsBuildInfoFile points at a path that is cleaned), or something changes between runs that invalidates the cache, such as a different TypeScript version, altered compiler options, or a generated file that is rewritten each time. Another possibility is that time is dominated by parse and I/O rather than checking, in which case incremental mode cannot help much.
Exercise
In a project, src/types.ts has no import or export statements and declares a global interface. After you edit it, almost every file is re-checked. Explain why, and name one way to fix it.
Show answer
A file with no imports or exports is a script, so its declarations are global and any file could depend on them. tsc cannot prove that importers are unaffected, so it re-checks widely. Fix it by making the file a module: add export to its declarations and import them where needed, or add export {}; and move truly global declarations into a small, rarely edited file.
Exercise
A function export function load(path: string) { return parse(read(path)); } has an inferred return type. Why can editing only its body cause importers to be re-checked, and how does an explicit return type change that?
Show answer
The inferred return type is part of the file's exported signature. If the edit changes what the body returns, the inferred type changes, the signature changes, and files that import load are re-checked. With an explicit return type such as : Document, the signature stays the same as long as the contract is unchanged, so body-only edits do not re-check importers.