Sub topic 2
Laying Out TypeScript Projects in a Repository
Assume you know basic TypeScript, tsconfig.json, ES modules, and how to run tsc. This chapter focuses on how several TypeScript projects fit together.
A Repository Layout
Give each independently built package its own directory and configuration:
packages/core/srccontains shared code.packages/app/srccontains the application.packages/core/tsconfig.jsonandpackages/app/tsconfig.jsondefine separate projects.- A root
tsconfig.jsoncoordinates the projects.
Each referenced project should set composite: true. It should also emit declarations so dependent projects can type-check against a stable boundary.
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"declaration": true,
"declarationMap": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}With composite, every source file must be included by include or files. The compiler also records build information in a .tsbuildinfo file.
Declaring and Using Dependencies
The application declares that it depends on core:
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"],
"references": [{ "path": "../core" }]
}The dependency graph tells TypeScript to build core before app. The application can then import the shared module across the project boundary:
import { greet } from "../../core/src/greet.js";
console.log(greet("project references"));In a package-managed repository, prefer a package name and its public exports instead of importing another package’s internal src path.
Incremental Builds and Build Mode
The .tsbuildinfo file stores information about inputs, options, and outputs. On a later build, TypeScript compares this information and skips projects that are still up to date.
A solution-style root configuration lists the projects but compiles no files itself:
{
"files": [],
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/app" }
]
}Run build mode from the repository root:
tsc --build
tsc --build --dry --verbose
tsc --build --clean
tsc --build --watch--build follows references, builds dependencies first, and skips unchanged projects. --clean removes outputs, and --watch rebuilds after changes.
Exercise
What must be true before app can use declarations from core?
Show answer
core must be a composite referenced project that emits declarations, and app must list it in references.