Sub topic 3
Turning a project into a composite project
This chapter assumes you can read a tsconfig.json, know what target, strict, outDir and rootDir do, and have run tsc from the command line. It also assumes you have seen the shared tsconfig.base.json from the previous chapter.
What composite means
composite is a compiler option that marks a project as safe to reference from another project. Setting it to true changes how the compiler treats the project. It does not change the JavaScript that your code compiles to.
A referencing project must be able to trust a referenced project without re-reading its source. That trust requires three things:
- The referenced project's file set is known in advance.
- The project writes declaration files (
.d.ts) that describe its public types. - The project writes a
.tsbuildinfofile that records what was built and from which inputs.
composite turns on the settings and checks that provide these three guarantees.
What the flag changes
When composite is true, the compiler applies these defaults and constraints:
| Effect | Detail |
|---|---|
| `declaration` defaults to `true` | The project emits a `.d.ts` file for every source file. |
| `incremental` defaults to `true` | The project writes a `.tsbuildinfo` file. |
| `rootDir` defaults to the directory that holds the `tsconfig.json` | Without an explicit `rootDir`, output paths follow that directory. |
| Every source file must be matched by `include` or `files` | An unlisted file is an error, not a silent addition. |
The last row causes the most surprise. In an ordinary project, the compiler happily follows an import to a file outside include and compiles it too. In a composite project, that import is an error. The compiler will not let a project's file set depend on whatever the import graph happens to reach.
A first composite project
Here is the packages/core/tsconfig.json used throughout this tutorial.
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"declarationMap": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}The extends line pulls in target, module, strict and the other shared options. The project then adds only what is specific to it.
compositemakes the project referenceable.declarationMapwrites a.d.ts.mapfile next to each declaration file. Editors use it to jump from a.d.tsfile back to the original.tssource.rootDirfixes the directory that maps to the root of the output tree.outDirsends all output todist, away from the sources.includelists the files that belong to the project.
The project's only source file is the small shared module.
export function greet(name: string): string {
return `Hello, ${name}!`;
}Run the compiler in build mode from the repository root.
tsc --build packages/coreThe dist folder now holds greet.js, greet.d.ts and greet.d.ts.map. A tsconfig.tsbuildinfo file also appears, and the next chapters explain its location and role.
Why the file set must be explicit
Consider how an incremental build decides whether a project is out of date. It compares the timestamps and hashes of the project's inputs with the values recorded in the .tsbuildinfo file. That comparison is only reliable if the inputs are a fixed, enumerable list.
If imports could silently enlarge the list, a change in a file outside include would alter the output without the compiler knowing the project was stale. The explicit-list rule removes that failure mode.
The error you see when you break the rule looks like this:
error TS6307: File '/repo/shared/util.ts' is not listed within the file list of project '/repo/packages/core/tsconfig.json'. Projects must list all files or use an 'include' pattern.There are two fixes, and the right one depends on what the file is:
- If the file belongs to this project, move it under
srcor widenincludeto cover it. - If the file belongs to another project, do not import its source. Reference that project instead, which is the subject of the chapter on the
referencesfield.
Avoid the shortcut of widening include to the whole repository. It removes the error but merges two projects into one and defeats the point of splitting them.
rootDir and the shape of the output
With composite, the default rootDir is the directory that contains the tsconfig.json. That default is easy to forget, because without composite the compiler infers rootDir as the longest common path of the input files.
The difference matters when sources live in a subfolder. Suppose the config sits in packages/core and the only source is packages/core/src/greet.ts.
- Without
rootDir, a composite project writesdist/src/greet.js, because the root ispackages/core. - With
"rootDir": "src", it writesdist/greet.js.
Setting rootDir explicitly keeps the output layout stable. It also stops the layout from changing if someone later adds a file in a different folder. Make this a habit in every composite project.
Declaration output is part of the contract
Because declaration is on, the compiler must be able to describe every exported value with a type that can be written in a .d.ts file. Most code works without changes. Some patterns fail.
A function whose inferred return type refers to a type that is not exported or importable produces a declaration error:
interface Internal {
id: number;
}
function makeInternal(): Internal {
return { id: 1 };
}
export const created = makeInternal();Here created has type Internal, and Internal is not exported. The compiler reports TS4025, which says that the exported variable has or is using private name Internal. The fix is to export the interface, or to write an explicit exported type for the value.
Annotating the public surface of a project with explicit types has a second benefit. It makes declaration output faster and more predictable, because the compiler does not need to infer and print complex types.
Options that interact with composite
A few other options are worth knowing at this point.
declaration: falseis an error whencompositeistrue. The project must emit declarations.noEmitcannot be combined withcompositein a project that others reference. A referenced project has to produce output. Use a separate non-composite config for type-check-only runs.tsBuildInfoFilelets you choose where the.tsbuildinfofile is written. If you omit it, the file goes next to theoutDircontent, named after the config file.emitDeclarationOnlyis allowed. It suits projects whose JavaScript is produced by another tool such as a bundler, whiletscprovides only types.
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"emitDeclarationOnly": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}Common mistakes
- Forgetting
include. With noincludeorfiles, the compiler defaults to every TypeScript file under the config's directory, includingdistoutput folders if they hold.d.tsfiles. Always writeincludeexplicitly. - Putting
outDirinsideinclude. Ifincludeis["."]andoutDirisdist, the compiler excludesoutDirby default, but a custom layout can bring generated files back in. Keep sources in a dedicated folder such assrc. - Setting
compositein the base config. The base config is inherited by every project, including the solution-style root and any tooling configs that should not be composite. Setcompositeper project. - Expecting
compositeto affect runtime behavior. It does not change the emitted JavaScript. It changes what the compiler checks and writes.
Summary of the mechanism
A composite project is a project with a promise: a fixed list of inputs, declaration files for every output, and a build record. Other projects depend on that promise. The next chapters show how declaration output, the build record and the references field turn that promise into faster, isolated builds.
Exercise
A teammate sets "composite": true in packages/core/tsconfig.json, then imports ../../shared/util.ts from a file in src. The build fails with TS6307. Give two valid ways to fix it, and name one fix you should avoid.
Show answer
Valid fixes: (1) move util.ts into packages/core/src, or widen include so the file is part of the core project; (2) put util.ts in its own composite project and add it to core's references, then import it through that project's output. Avoid widening include to the whole repository or turning off composite, because that hides the error by merging project boundaries instead of respecting them.
Exercise
A composite project's config sits in packages/core and its only source is packages/core/src/greet.ts. There is no rootDir, and outDir is dist. Where does greet.js end up, and how do you get it to dist/greet.js?
Show answer
With composite, rootDir defaults to the config's directory, so the output is dist/src/greet.js. Add "rootDir": "src" to the compiler options to get dist/greet.js.