Monorepo Setup with TypeScript Project References
Advanced20 min
Configure TypeScript project references to build, type-check, and navigate across multiple packages in a monorepo with incremental compilation.
Prerequisites
- -TypeScript 4.0+
- -Monorepo with multiple packages (pnpm workspaces, npm workspaces, or Turborepo)
Steps
1
Create a base tsconfig for shared settings
Define a root tsconfig.base.json with common compiler options shared across all packages.
$ cat > tsconfig.base.json << 'EOF'
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"composite": true
}
}
EOF
The composite: true flag is required for project references to work.
2
Configure each package tsconfig
Each package extends the base config and declares references to packages it depends on.
$ cat > packages/shared/tsconfig.json << 'EOF'
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src"]
}
EOF
3
Add references in dependent packages
Packages that import from shared add it as a reference.
$ cat > packages/web/tsconfig.json << 'EOF'
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src"
},
"references": [
{ "path": "../shared" }
],
"include": ["src"]
}
EOF
4
Create the root tsconfig with all references
The root tsconfig.json lists all packages as references for orchestrated builds.
$ cat > tsconfig.json << 'EOF'
{
"files": [],
"references": [
{ "path": "packages/shared" },
{ "path": "packages/web" },
{ "path": "packages/api" }
]
}
EOF
5
Build all projects incrementally
Use tsc --build to compile all referenced projects in the correct dependency order.
$ tsc --build --verbose
Subsequent builds only recompile changed packages. Use tsc --build --clean to reset.
Full Script
FAQ
Discussion
Loading comments...