TypeScript
Build mode
Learn project building with tsc --build.
What is build mode?
tsc --build is a mode that compiles projects in dependency order and uses an incremental cache. Referenced projects need composite: true to be buildable; incremental: true lowers rebuild cost with a .tsbuildinfo file.
// tsconfig.json
{
"compilerOptions": {
"composite": true,
"incremental": true,
"outDir": "dist"
}
}
Build mode recompiles only changed projects, so it speeds up large monorepos.
composite and incremental
composite: true makes a project referenceable by others; it also forces declaration and outDir. incremental: true writes build info to a .tsbuildinfo file and processes only changed files on subsequent builds.
{
"compilerOptions": {
"composite": true,
"incremental": true,
"declaration": true,
"outDir": "dist"
}
}
A non-composite project cannot be referenced; build mode errors out.
Exercise Validate build config
Write a validateBuildConfig function that checks a config object's composite and incremental fields and pushes to an errors array when missing. Print the error count for the config { composite: true, incremental: true }.
Show example solution
function validateBuildConfig(config: { composite?: boolean; incremental?: boolean }): string[] {
const errors: string[] = [];
if (!config.composite) errors.push("composite must be true");
if (!config.incremental) errors.push("incremental recommended");
return errors;
}
const config = { composite: true, incremental: true };
console.log(validateBuildConfig(config).length);
Test yourself
-
In what order does `tsc --build` compile?
- Only the root project
- Random order, in parallel
- In dependency order, rebuilding changed projects
- Alphabetically, all projects
Show answer
In dependency order, rebuilding changed projects — Build mode first resolves dependencies, then compiles in dependency order and rebuilds only changed projects; it is not alphabetical or random.
-
Enable composite
{
"compilerOptions": {
"composite": ____,
"declaration": true
}
}
Show answer
{
"compilerOptions": {
"composite": true,
"declaration": true
}
}
-
Build mode parts
- tsc --build
- compiles projects in dependency order
- composite: true
- enables referenceability
- incremental: true
- enables .tsbuildinfo cache
- .tsbuildinfo
- incremental build info
Next lesson: Project references