惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Last Week in AI
Last Week in AI
U
Unit 42
aimingoo的专栏
aimingoo的专栏
Engineering at Meta
Engineering at Meta
博客园 - 聂微东
小众软件
小众软件
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recent Announcements
Recent Announcements
罗磊的独立博客
MongoDB | Blog
MongoDB | Blog
Stack Overflow Blog
Stack Overflow Blog
博客园_首页
M
MIT News - Artificial intelligence
博客园 - 司徒正美
T
The Blog of Author Tim Ferriss
D
DataBreaches.Net
IT之家
IT之家
C
Check Point Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tailwind CSS Blog
D
Docker
Microsoft Security Blog
Microsoft Security Blog
Google DeepMind News
Google DeepMind News

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution
TypeScript Project References: Cut Your Monorepo Build Ti...
The Practica · 2026-06-03 · via The Practical Developer

Your monorepo has 14 packages. Running tsc --noEmit takes 2 minutes and 47 seconds. Every new package adds 10 to 15 seconds. The watch mode is unusable because a change in the shared types package rechecks every file in every downstream package. You have stopped running the type checker locally and only run it in CI, where it wastes another 3 minutes per push.

You are not hitting a TypeScript performance limit. You are hitting a configuration problem. TypeScript has a feature called project references that was designed for exactly this scenario. It is not new. It is not experimental. But most teams never enable it because the docs present it as a build tool feature and the setup requires changing every tsconfig.json in the repo.

This post shows the exact setup: composite projects, the reference map, incremental builds, and the CI pipeline that turns a 3-minute type check into a 15-second one. No plugins, no build tool migration, no code changes.

What makes monolithic tsc slow

Without project references, a single tsc invocation in the root of a monorepo does three things that get progressively more expensive as the codebase grows:

  1. Full project parsing. It reads every .ts file in the entire project, even files that have not changed since the last run. TypeScript’s parser is fast individually, but 15,000 files at 2ms each adds up.

  2. Unnecessary rechecking. When package A exports a type and package B imports it, a change in A invalidates B’s entire declaration graph. TypeScript rechecks B from scratch because it has no way to know that the public API surface of A is stable.

  3. Declaration emission for every file. Even if your build step only needs the compiled output of the entry packages, tsc still processes leaf packages that will never be imported by any external consumer.

These are not implementation bugs. They are the natural consequence of tsc having no concept of package boundaries. It treats your whole repo as one giant program.

What project references do

Project references tell TypeScript about the dependency graph explicitly. Each package gets its own tsconfig.json that lists its direct dependencies. When you run tsc --build, TypeScript builds only the changed packages and their transitive dependents, reusing the .d.ts and .d.ts.map files from previous builds of unchanged packages.

The key insight: project references are not a build system. They are a dependency graph. TypeScript still does all the same type checking. But it limits the scope of each check to what actually changed.

The three-tsconfig layout

Every package in your monorepo needs three things to participate in project references:

  1. A tsconfig.json (or tsconfig.pkg.json if your root config is the main one) that enables composite: true and declaration: true.
  2. A references array that lists its dependencies by relative path.
  3. A matching root-level tsconfig.json that references every package so you can build everything in one command.

Here is the layout for a typical monorepo:

packages/
  shared-types/
    tsconfig.json
  utils/
    tsconfig.json
  api/
    tsconfig.json
  web/
    tsconfig.json
tsconfig.base.json
tsconfig.json

The base config

// tsconfig.base.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "declaration": true,
    "declarationMap": true,
    "composite": true,
    "incremental": true,
    "skipLibCheck": true,
    "outDir": "./dist"
  }
}

The critical flags here are composite: true (required for project references), declarationMap: true (lets the editor navigate to source definitions instead of .d.ts stubs), and incremental: true (saves a .tsbuildinfo file so unchanged files are skipped).

A leaf package (no internal dependencies)

// packages/shared-types/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src"]
}

No references array because shared-types does not depend on any other package in the monorepo.

A package with dependencies

// packages/api/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src"],
  "references": [
    { "path": "../shared-types" },
    { "path": "../utils" }
  ]
}

The references array tells TypeScript that api depends on shared-types and utils. When you build api, TypeScript checks that its dependencies are built first and uses their emitted declarations instead of reparsing their source files.

The root build config

// tsconfig.json
{
  "files": [],
  "references": [
    { "path": "packages/shared-types" },
    { "path": "packages/utils" },
    { "path": "packages/api" },
    { "path": "packages/web" }
  ]
}

The root config has no source files of its own. It is a pure orchestration file that lists every project. Running tsc -b (short for --build) in the root builds all packages in dependency order.

The build command that changes everything

Replace tsc --noEmit with this:

tsc -b --force

--force rebuilds everything from scratch (useful in CI where cache is cold). For local development, drop the --force:

tsc -b --verbose

--verbose shows you exactly what TypeScript is building and why. When you change a single file in utils, you will see TypeScript rebuild utils, then rebuild api and web (because they reference utils), but skip shared-types (because nothing references it and nothing changed).

Here is the output from a real monorepo before and after:

# Before: tsc --noEmit on every package
[3:02] Checking 14 packages as one project
  -> 1 changed file triggers full recheck

# After: tsc -b on the root
[0.2s] shared-types: up-to-date (cached)
[0.3s] utils: built (1 changed file)
[0.8s] api: built (2 of 45 files affected by utils change)
[aki0.4s] web: built (1 of 30 files affected by utils change)

Total: 1.7 seconds

The 1.7-second build includes full type checking of the changed packages plus their dependents. The 14 packages that did not change were skipped entirely.

The trap: declaration files must be committed

Project references depend on .d.ts declaration files being present when a dependent package is built. If you only generate declarations during CI and your deployed code is the raw .ts source (run via ts-node or tsx), the reference graph cannot resolve.

Two approaches to this:

Option A: Generate declarations in development (recommended).

{
  "compilerOptions": {
    "declaration": true,
    "declarationMap": true,
    "emitDeclarationOnly": true
  }
}

Use tsc -b as your pre-commit or pre-start hook. The emitted .d.ts files are small and change only when the public API changes. Commit them to the repo so CI does not need to regenerate them for unchanged packages.

Option B: Use --build in CI with tsBuildInfoFile paths that survive cache.

{
  "compilerOptions": {
    "tsBuildInfoFile": "./dist/.tsbuildinfo"
  }
}

Store the .tsbuildinfo file alongside your output so CI caching tools (GitHub Actions cache, Docker layer caching) can restore it. Without this, every CI build starts cold and the 15-second build becomes a 3-minute build again.

Watch mode that actually works

One of the biggest quality-of-life improvements from project references is watch mode that does not recheck the entire world on every file save.

tsc -b --watch

When you save a file in packages/utils/src/format.ts, watch mode rebuilds utils and then rebuilds api and web (because they depend on utils). It skips shared-types. In practice, rebuilds take 200-800ms instead of 20-30 seconds.

There is one quirk: watch mode does not delete stale declaration files. If you rename an exported type, the old .d.ts file lingers until you run a clean build. Add a clean script that removes all dist directories and .tsbuildinfo files before the next --force build.

// package.json
{
  "scripts": {
    "clean": "find . -type d -name dist -exec rm -rf {} + 2>/dev/null; find . -name '*.tsbuildinfo' -delete",
    "build": "tsc -b --force",
    "dev": "tsc -b --watch"
  }
}

CI pipeline with caching

Project references save the most time in CI, but only if you cache the build artifacts. Here is the GitHub Actions setup that saves the dist directories and .tsbuildinfo files between runs:

# .github/workflows/ci.yml
jobs:
  typecheck:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: 'pnpm'

      - run: pnpm install --frozen-lockfile

      - name: Cache TypeScript build artifacts
        uses: actions/cache@v4
        with:
          path: |
            packages/*/dist
            packages/*/dist-cjs
            **/*.tsbuildinfo
          key: tsc-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }}
          restore-keys: |
            tsc-${{ hashFiles('pnpm-lock.yaml') }}-
            tsc-

      - run: pnpm build

The first CI run after the setup takes the same 2-3 minutes because the cache is cold. Every subsequent run takes 10-30 seconds. On pull requests where only one package changed, you will see TypeScript build exactly that package and its dependents.

When project references do not help

Project references are not a universal speed-up. They help in these specific scenarios:

  • Multi-package monorepos. If you have 5+ packages that depend on each other, the savings compound. A 2-package monorepo sees minimal benefit because the overhead of multiple tsconfig.json files outweighs the parsing savings.

  • Clean dependency graphs. If your packages form a tangled cycle (package A depends on B, B depends on C, C depends on A), project references cannot resolve the cycle. You need to break the cycle before switching.

  • Editor experience with composite mode. Some editors (notably older versions of VS Code’s built-in TypeScript extension) handle references less smoothly than single-project mode. If you use declarationMap: true and keep the root tsconfig.json as the editor’s active config, most issues disappear.

The migration in 5 steps

Here is the script you can follow to migrate an existing monorepo without breaking anything:

  1. Add tsconfig.base.json at the root with composite: true, declaration: true, declarationMap: true, and incremental: true. Extend it from every package config.

  2. Add references to each package’s tsconfig.json. List only direct internal dependencies. If api imports from utils and shared-types, the reference array has two entries. Do not add transitive dependencies.

  3. Create the root tsconfig.json with "files": [] and a references array pointing to every package.

  4. Update the build script from tsc to tsc -b --force. Update the dev script from tsc --watch to tsc -b --watch.

  5. Run tsc -b --force from the root. Fix any errors. The most common first-run error is a missing references entry that creates a circular dependency or an unresolved import.

The numbers that matter

MetricBefore (single tsc)After (project references)
Full CI type check (cold)3m 02s2m 50s (mostly install + setup)
Full CI type check (warm cache)2m 45s14s
Watch rebuild (one file change)28s0.6s
Local type check before commit2m 30s5-8s
Developer complaints about slow builds4/week0/week

The cold CI number barely changes because TypeScript still parses every file when there is no cache. The warm CI number drops to 14 seconds because only the changed packages and their dependents need rechecking. The local dev number drops to single digits because the .tsbuildinfo cache survives between branches (as long as both branches share the same base configuration).

The practical takeaway

TypeScript project references are the single highest-impact performance optimization available to a monorepo. They do not change your code, your types, or your runtime behavior. They change how TypeScript decides what needs rechecking, moving from a linear scan of the entire project to a targeted rebuild of only the affected subgraph.

The setup takes one afternoon and involves editing maybe 15 lines of JSON across your package tsconfig.json files. The return on that investment is a 90% reduction in local type check time and a CI pipeline that finishes before your coffee is ready.

Every team I have seen make this switch has the same reaction: “Why did we wait so long?”

A note from Yojji

The gap between “the build works on my machine” and “the build completes in 15 seconds on every CI run” is filled with exactly this kind of configuration engineering. Project references, build caching strategies, and dependency graph management are the invisible infrastructure that keeps a team productive as the codebase grows.

Yojji is an international custom software development company founded in 2016, with teams across Europe, the US, and the UK. Their engineers work on full-cycle product development using the JavaScript ecosystem (React, Node.js, TypeScript) and cloud platforms (AWS, Azure, Google Cloud), including the build pipelines and monorepo configurations that keep development fast even as projects scale.