Project References: Wiring Up a Monorepo

Project References: Wiring Up a Monorepo in TypeScript: A modern shipyard does not build a vessel plank by plank in the dock.

The Analogy: Block Construction at a Shipyard

A modern shipyard does not build a vessel plank by plank in the dock. It fabricates the ship as a set of large hull blocks, each built on its own in the fabrication shop to its own drawings, welded up, outfitted with its pipework and cabling, and inspected as a finished unit before it ever leaves the shed. Only then are the blocks craned into the building dock and joined to one another in a strict erection sequence. A TypeScript monorepo is built the same way: each package is a block with its own tsconfig, compiled and type-checked into a finished, inspected output of its own, and project references are the erection plan that tells the compiler which blocks depend on which and therefore what order to assemble them in.

The erection sequence is not arbitrary; it follows what rests on what. The double-bottom blocks go down before the blocks that sit on them, and a block cannot be craned in until the blocks it lands on are already in place and signed off. Project references encode exactly this dependency order: a package that imports another can only be checked once that other package has been built, so the compiler builds the leaf packages first and works outward. And because each block was inspected as a finished unit in the shed, the yard does not re-inspect the whole ship every time; it certifies each block once and trusts that certificate at the seam, which is what the composite setting and its build-record file do for a package, recording what was checked so unchanged blocks are never rebuilt.

Two further disciplines make block construction work, and both have direct code counterparts. First, blocks join only at their designed butt joints, the engineered seams where two blocks were always meant to meet; a fitter does not cut a fresh hole into the middle of a neighbouring block to run a pipe through, because that would violate a structure that was inspected as a sealed unit. A package exposes a single public surface, its index, and another package imports only from that surface, never by reaching into the neighbour's internal source. Second, the master erection schedule is a document that contains no steel of its own; it lists the blocks and their order and nothing else, exactly as the root solution tsconfig owns no source files and merely names the projects and their references.

The failure mode is twofold, and the shipyard makes both vivid. The first is trying to erect blocks in a sequence that cannot exist, where block A rests on block B while block B also rests on block A; there is no order in which either can go first, and the crane crew is stuck forever. A circular dependency between packages is precisely this, and a build system either refuses it outright or, if it was hand-rolled without a cycle check, spins trying to find an order that does not exist. The second is subtler and catches everyone once: inspecting the erection schedule sheet itself, finding it lists no defects, and declaring the whole ship sound. The schedule has no steel to inspect, so of course it reports nothing wrong. Running an ordinary type check against the empty solution file is exactly that, a silent pass over a repository full of errors, because the solution file owns no source and its references are only followed when you actually build.


Syntax or Core Structure

Each package is a block: a self-contained unit that produces a checked output others consume by package name. The composition below shows a utils layer, a core layer that depends on it, and top-level code that depends on core, all resolving through their public surfaces.

// packages/utils/src/index.ts -- a leaf block
function formatMoney(minor: number): string {
    return "GBP " + (minor / 100).toFixed(2);
}

// packages/core/src/service.ts -- depends on utils
interface Line {
    minor: number;
}
function invoiceTotal(lines: Line[]): string {
    const sum = lines.reduce((running, line) => running + line.minor, 0);
    return formatMoney(sum);
}

// top-level code that depends on core
const lines: Line[] = [{ minor: 1200 }, { minor: 800 }, { minor: 500 }];

console.log(lines.length);
console.log(invoiceTotal(lines));
console.log(invoiceTotal([{ minor: 250 }]));

Output:

3
GBP 25.00
GBP 2.50

The utils block owns formatMoney, core builds invoiceTotal on top of it, and the top-level code assembles the two. The three lines total 1200 + 800 + 500 = 2500 minor units, which formatMoney renders as GBP 25.00, and a single line of 250 renders as GBP 2.50. In a real monorepo the import would read from "@acme/utils" and resolve to that package's compiled declaration output rather than its source, which is why the leaf block must be built before the block that consumes it. The root solution tsconfig that ties these together owns no source itself; it sets "files": [] and lists the packages under references, and it is built with tsc --build rather than a plain type check.


Technical Depth: Build Order, Incremental Rebuilds, and the Commands

Project references buy two things: a correct build order derived from the dependency graph, and incremental rebuilds that touch only what changed. Both are just graph operations, and modelling them in plain code makes the behaviour concrete.

Deriving the erection sequence

The build order is a topological sort: repeatedly take every package whose dependencies are all already built, in a fixed order, until none remain.

// src/order.ts
interface Package {
    name: string;
    deps: string[];
}

function buildOrder(packages: Package[]): string[] {
    const order: string[] = [];
    const done = new Set<string>();
    while (order.length < packages.length) {
        for (const p of packages) {
            if (done.has(p.name)) {
                continue;
            }
            if (p.deps.every((d) => done.has(d))) {
                order.push(p.name);
                done.add(p.name);
            }
        }
    }
    return order;
}

const packages: Package[] = [
    { name: "web", deps: ["core", "utils"] },
    { name: "core", deps: ["utils"] },
    { name: "utils", deps: [] },
];

const order = buildOrder(packages);
console.log(order.join(" -> "));
console.log(order.length);

Output:

utils -> core -> web
3

The first pass can only place utils, because it is the sole package with no unmet dependencies; web and core are skipped since their dependencies are not yet done. The second pass places core, whose only dependency utils is now built. The third places web, whose dependencies core and utils are both done. The result, utils -> core -> web, is exactly the order tsc --build would choose, and its length is the full count of 3.

Which blocks a change forces to rebuild

When one package changes, the compiler rebuilds it and everything that transitively depends on it, and nothing else.

// src/affected.ts
interface Package {
    name: string;
    deps: string[];
}

function affected(packages: Package[], changed: string): string[] {
    const rebuilding = new Set<string>([changed]);
    let grew = true;
    while (grew) {
        grew = false;
        for (const p of packages) {
            if (rebuilding.has(p.name)) {
                continue;
            }
            if (p.deps.some((d) => rebuilding.has(d))) {
                rebuilding.add(p.name);
                grew = true;
            }
        }
    }
    return packages.filter((p) => rebuilding.has(p.name)).map((p) => p.name);
}

const packages: Package[] = [
    { name: "web", deps: ["core", "utils"] },
    { name: "core", deps: ["utils"] },
    { name: "utils", deps: [] },
];

console.log(affected(packages, "utils").join(","));
console.log(affected(packages, "web").join(","));
console.log(affected(packages, "utils").length + " " + affected(packages, "web").length);

Output:

web,core,utils
web
3 1

Changing utils forces everything to rebuild, because core depends on it and web depends on both, so the affected set is all three packages. Changing web rebuilds only web, because nothing depends on it. The counts confirm it: 3 affected for a leaf change, 1 for a top-level change. This asymmetry is the whole argument for putting stable, shared code in a leaf package and volatile code higher up.

The build-mode commands

Because a solution file owns no source, it is driven in build mode, and the common invocations are laid out below.

TaskInvocation
build all in dependency orderbuild mode with no extra flag
rebuild only what changedbuild mode in watch
ignore the cache and rebuild allbuild mode forced
show the plan without buildingbuild mode dry-run
delete every build outputbuild mode clean

Reading the invocation column, all five are the same build-mode entry point with a different flag, and the crucial point is that none of them is a plain type check of the root: run an ordinary check against the solution file and it passes over everything, because the schedule sheet has no steel to inspect.


Real World Example: A Monorepo Build Report

Putting the pieces together, this program takes a three-package repo, computes the erection sequence, and reports each package in build order with its module count and a running total. It is the shipyard's build board: what gets assembled, in what order, and how much is in each block.

// src/buildreport.ts
interface Pkg {
    name: string;
    deps: string[];
    modules: number;
}

function buildOrder(packages: Pkg[]): string[] {
    const order: string[] = [];
    const done = new Set<string>();
    while (order.length < packages.length) {
        for (const p of packages) {
            if (done.has(p.name)) {
                continue;
            }
            if (p.deps.every((d) => done.has(d))) {
                order.push(p.name);
                done.add(p.name);
            }
        }
    }
    return order;
}

function pad(text: string, width: number): string {
    const gap = width - text.length;
    return text + " ".repeat(gap > 0 ? gap : 0);
}

const pkgs: Pkg[] = [
    { name: "web", deps: ["core", "utils"], modules: 12 },
    { name: "core", deps: ["utils"], modules: 8 },
    { name: "utils", deps: [], modules: 5 },
];

const order = buildOrder(pkgs);

let total = 0;
console.log("packages: " + pkgs.length);
console.log(pad("PKG", 8) + "MODULES");
for (const name of order) {
    const p = pkgs.find((candidate) => candidate.name === name);
    if (p === undefined) {
        continue;
    }
    total += p.modules;
    console.log(pad(name, 8) + p.modules);
}
console.log("total: " + total);

Output:

packages: 3
PKG     MODULES
utils   5
core    8
web     12
total: 25

The build order resolves to utils, then core, then web, and the report walks that order rather than the declaration order, which is why utils appears first despite being listed last. Each package contributes its module count, 5 for utils, 8 for core, and 12 for web, and the running total comes to 5 + 8 + 12 = 25. Reporting in build order rather than list order is what makes the board match what the compiler actually does.

The value of the arrangement is that the order is computed from the dependency graph, not hand-maintained: add a package or change a dependency and the sequence recomputes itself, exactly as tsc --build reorders the erection plan when references change. The boundaries are enforced too, because each package is consumed only through its declared surface, so a package cannot quietly reach into a neighbour's internals.

The design has a real and pointed flaw, and it is the circular-dependency case the analogy warned of. buildOrder assumes the graph is acyclic: if two packages depended on each other, no package's dependencies would ever all be done, the while loop's count would never reach the package total, and the function would spin forever rather than report an error, which is the two-blocks-resting-on-each-other deadlock made literal. A production build detects the cycle and fails with a message; this hand-rolled sorter hangs. Two smaller limits sit alongside: pkgs.find matches by name and silently assumes names are unique, so two packages sharing a name would collide with the first one always winning; and modules is treated as a stand-in for build cost, which conflates the number of files with the time to compile them, so the total of 25 measures size, not the build duration a reader might assume.


Common Mistakes

  1. Running a plain type check against the solution file. With "files": [] the root owns no source, so an ordinary check passes over everything; you must use build mode.
  2. Omitting composite: true on a package. Without it the project cannot be referenced at all, so the whole references mechanism silently fails to engage.
  3. Setting paths without references or the reverse. paths tells the checker where to look and references tells the build what order to use; a mismatch gives stale types or unresolved imports.
  4. Creating a circular reference between packages. There is no valid build order, so the tool rejects it, and the cycle is really telling you a boundary is drawn in the wrong place.
  5. Forgetting to build a dependency first. The dependent then reports errors that are nothing but a missing declaration output, sending you to debug a problem that is really a stale build.
  6. Committing build outputs and the build-info file. Both are generated artefacts, so committing dist or the .tsbuildinfo pollutes the repo and causes spurious diffs.
  7. Duplicating compiler options in every package. Copy-pasted options drift apart over time; a shared base config extended everywhere keeps them in step.
  8. Deep-importing another package's internal source. Reaching past a package's public index into its internals defeats the very boundary that references were meant to enforce.
  9. Assuming module or file counts equal build time. Treating size as a proxy for cost misleads capacity planning, because a small package with heavy types can outweigh a large simple one.

Best Practices

  • Keep one shared base config and extend it everywhere. A single tsconfig.base with the common options means a change lands in one place, not in every package.
  • Use a root solution file and build it in build mode. Give the root "files": [] with references only, and never run a plain check against it in CI.
  • Turn on composite and declaration output in the base. These make every package referenceable and let editors navigate to source across package boundaries.
  • Import by workspace package name, never by relative path. Package-name imports keep a package extractable to its own repo with no import changes later.
  • Keep references and paths in agreement. Treat any mismatch between the two as a build bug, because they must describe the same graph.
  • Expose one public index per package. A single entry point makes the public surface explicit and stops consumers depending on internals.
  • Ignore build artefacts in version control. Add the output directory and the build-info file to .gitignore so only source is committed.
  • Keep the dependency graph acyclic. If two packages seem to need each other, extract the shared piece into a third leaf package rather than forming a cycle.

Practice Exercises

  1. The Erection Plan. Model a two-package repo where app depends on utils, compute the build order with a topological sort, and confirm the leaf package is built first.
  2. The Silent Pass. Explain, with reference to "files": [], why a plain type check of the solution file reports no errors on a broken repo while build mode catches them.
  3. The Blast Radius. Write an affected function that, given a changed package, returns the changed package plus everything that transitively depends on it, and check it against both a leaf change and a top-level change.
  4. The Deadlock. Add a circular dependency to the package list, run the topological sort in your head, and describe exactly where the naive sorter hangs and what a real build tool reports instead.