What are Nx TypeScript project references, and why do path aliases break down at scale?
The target setup has two parts. First, each internal library gets its own package.json, and the package manager's workspaces feature links it into node_modules, so @acme/billing resolves the way any installed package does. Second, each library's tsconfig is a composite TypeScript project that lists the projects it depends on in references. Type-checking then becomes an incremental build that emits declaration files and reuses them across projects.
The older pattern puts a paths map in tsconfig.base.json that points every alias at a library's source entry file. That works well for a handful of libraries. It degrades as the workspace grows, for four reasons:
- One giant program per check. An alias resolves to source, not declarations, so type-checking any project pulls in the source of everything it transitively imports. The same library code gets parsed and checked again in every consumer.
- No declared dependencies. Every alias is visible to every project. A library can import anything, and nothing forces it to state its dependencies. Boundaries exist only as lint rules or convention.
- Memory grows with the workspace. The editor's language service and
tschold those large programs in memory, so cost tracks the size of the whole repository rather than the project you are working on. - Duplicated resolution config. Node does not read
paths. The runtime, the test runner and the bundler each need their own alias mapping, and those mappings drift out of sync.
This guide is for backend and platform engineers running medium-to-large Nx workspaces with many libraries and package boundaries they need to enforce.
How does workspaces linking replace tsconfig paths?
With workspaces linking, each library stops being a directory that a path alias points into and becomes a package with its own package.json. That manifest declares a scoped name such as @acme/billing-core, along with exports, main and types entries that point at the library's build output, not at src. Dependencies on other internal libraries are listed like any other dependency. Under pnpm, Yarn and Bun this uses the workspace: protocol. npm workspaces do not support that protocol, so they rely on a matching version range instead. Either way, the dependency graph is written in the manifests, so Nx and the package manager can both read it.
On install, the package manager symlinks each workspace package into node_modules. Every tool in the chain then resolves @acme/billing-core through ordinary package lookup. That includes Node at runtime, the TypeScript compiler, the test runner and the bundler. None of them needs a private alias table, so the per-tool mappings that drifted out of sync are gone. The same resolution path also applies to published packages, so the behaviour you test locally is much closer to what consumers get.
The cost of this is that all those tools must interpret the manifest the same way. The exports map is now the contract, and each tool picks entries based on which conditions it matches, such as import, require, types or a custom development condition. TypeScript only reads exports when moduleResolution is set to node16, nodenext or bundler. Under the older node setting it ignores exports and falls back to main and types. If the type checker, the test runner and the runtime resolve the same import differently, the build can typecheck and then fail at runtime. Choose one resolution model and configure every tool to match it.
# libs/billing-core/package.json: the library is now a real package.
# Entry points target build output (dist), not src.
cat > libs/billing-core/package.json <<'EOF'
{
"name": "@acme/billing-core",
"version": "0.0.0",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"default": "./dist/index.js"
}
},
"dependencies": {
"@acme/money": "workspace:*"
}
}
EOF
# 'main' and 'types' are fallbacks for tools that ignore 'exports'.
# 'workspace:*' works in pnpm, Yarn and Bun. With npm, use a version range
# that matches @acme/money's own version instead.
# Shared compiler options: TypeScript reads 'exports' only under
# node16, nodenext or bundler. The older 'node' setting ignores it.
cat > tsconfig.base.json <<'EOF'
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"composite": true,
"declaration": true
}
}
EOF
# Symlink every workspace package into node_modules, then check the link.
pnpm install
ls -l node_modules/@acme/
# The test runner and bundler must match the same export conditions as tsc.
A library becomes a real package: its package.json points exports, main and types at build output, it depends on another internal package through the workspace protocol, and the shared tsconfig uses a moduleResolution mode that reads exports.
How do TypeScript project references and tsc build mode work?
…it consistently across all three before turning to the TypeScript build itself.
Project references make each library a separately compiled unit. Setting composite: true in a library's tsconfig tells the compiler the project can be referenced. It also turns on declaration and requires every source file to be covered by include or files, so the compiler knows the project's full input set. A consumer lists its dependencies in a references array of relative paths. When the consumer imports from a referenced project, the compiler reads that project's emitted .d.ts files instead of its .ts source. That is the main benefit: the consumer type-checks against a fixed public surface and does not re-check the dependency's internals on every build.
tsc -b (build mode) walks the reference graph from the root solution tsconfig. It builds leaves first and writes a .tsbuildinfo file per project that records input state. On the next run it skips any project whose inputs and outputs are unchanged.
tsconfig.json (solution: references only, no files)
├── apps/api/tsconfig.json ──refs──┐
├── libs/domain/tsconfig.json ─refs─┤
└── libs/util/tsconfig.json │
▼
build order: util ──► domain ──► api
emits: dist/libs/util/*.d.ts
dist/libs/domain/*.d.ts (reads util .d.ts)
dist/apps/api (reads domain .d.ts)
Nx caches the same outputs separately, using its own input hashes. The two caches can drift apart. If Nx restores dist but not .tsbuildinfo, or restores a .tsbuildinfo that was written from a different input state, tsc -b may rebuild work that didn't need it or misjudge what is up to date. To prevent this, emit .tsbuildinfo alongside dist and declare both as cached outputs of the target. That way Nx always restores them together.
// tsconfig.json (solution root): no files of its own, only the graph entry points
{
"files": [],
"references": [{ "path": "./apps/api" }]
}
// libs/domain/tsconfig.json
{
"compilerOptions": {
"composite": true, // referenceable; implies declaration: true
"rootDir": "src",
"outDir": "../../dist/libs/domain",
// Put .tsbuildinfo inside the same dist folder so one Nx output covers both
"tsBuildInfoFile": "../../dist/libs/domain/tsconfig.tsbuildinfo"
},
"include": ["src/**/*.ts"], // composite requires every input file to be listed
"references": [{ "path": "../util" }] // consume util through its emitted .d.ts
}
// libs/domain/project.json (build target excerpt)
{
"targets": {
"build": {
"executor": "nx:run-commands",
"options": { "command": "tsc -b libs/domain/tsconfig.json" },
"dependsOn": ["^build"],
// Declares .d.ts output and .tsbuildinfo together so Nx restores them as a pair
"outputs": ["{workspaceRoot}/dist/libs/domain"]
}
}
}
A composite library tsconfig that writes its .tsbuildinfo into its dist folder. The matching Nx build target declares that one folder as its output, so Nx caches and restores the declarations and the build info together.
How do you structure tsconfig files for project references in Nx?
Give each project a tsconfig.json that is solution-style: files is empty, and it contains only references to its own tsconfig.lib.json and tsconfig.spec.json. Editors and tsc -b open this file first and then follow the references, so library code and test code each get their own compilation settings without sharing one program.
tsconfig.lib.json holds the real build settings. Enable composite. Set rootDir to src and outDir to dist so the emitted layout matches the exports or types fields in package.json. If rootDir is left unset, TypeScript infers it from the input files, and a single stray file can shift every output path. Turn on declaration and declarationMap. Without the map, go-to-definition on an import from another package opens a .d.ts file. With it, the editor jumps to the original .ts source. tsconfig.spec.json references tsconfig.lib.json and adds test types. This keeps test-only globals out of the published declarations.
The root tsconfig.json lists project references and nothing else. Shared compiler options go in tsconfig.base.json, which every project extends.
Each project's references must match its workspace dependencies in package.json. Do not maintain them by hand. Run nx sync to generate them from the project graph, and run nx sync:check in CI to fail any branch where they have drifted.
A missing reference often goes unnoticed locally. tsc -b does not know it has to build the dependency first, so the import resolves through the workspace symlink to whatever .d.ts files already exist in that package's dist. On your machine those files may be stale. On a clean CI runner they may not exist yet, and the build fails.
// packages/ui/tsconfig.json: solution-style entry point for editors and tsc -b
{
"files": [],
"references": [{ "path": "./tsconfig.lib.json" }, { "path": "./tsconfig.spec.json" }]
}
// packages/ui/tsconfig.lib.json: the real build settings for published code
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"rootDir": "src", // pinned so a stray file can't shift output paths
"outDir": "dist", // must match "types"/"exports" in package.json
"declaration": true,
"declarationMap": true // go-to-definition lands in .ts, not .d.ts
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.spec.ts"],
// Written by `nx sync` from workspace deps in package.json; do not hand-edit.
// Removing it lets tsc -b skip building util, so imports read stale or missing dist/*.d.ts.
"references": [{ "path": "../util/tsconfig.lib.json" }]
}
// packages/ui/tsconfig.spec.json: test-only types stay out of published .d.ts
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"rootDir": "src",
"outDir": "out-tsc/spec",
"types": ["node", "jest"]
},
"include": ["src/**/*.spec.ts"],
"references": [{ "path": "./tsconfig.lib.json" }]
}
// CI step: fail the branch if references have drifted from the project graph
// $ npx nx sync:check
A per-project split into a solution-style tsconfig.json, a composite tsconfig.lib.json with pinned rootDir/outDir and declaration maps, and a tsconfig.spec.json that references the lib, where nx sync generates the dependency references and nx sync:check enforces them in CI.
How do you migrate incrementally from path aliases to project references?
That failure mode is why order matters. Each step below removes one way for an import to resolve to something other than what you expect.
1. Break cycles before touching configuration
Project references form a directed acyclic graph, and tsc --build refuses to process a cycle. Run nx graph and look for libraries that import each other, directly or through a chain. The usual fix is to extract the shared types or utilities into a new leaf library that both sides depend on. If the dependency only points in one direction, move the code the other way.
2. Convert leaves first, then move upward
Start with libraries that depend on nothing else in the workspace. Give each one a package.json with a name and an exports entry, plus a tsconfig set up for composite builds. Then convert its direct consumers, adding the package as a dependency and a references entry. A library can only be converted once everything below it is done. Otherwise its build depends on an unbuilt alias target.
3. Keep the overlap short and tracked
While both mechanisms exist, a given import can resolve to the alias's source file in one tool and to the linked package's dist in another. Keep a checklist of which libraries are still mid-transition, and treat every entry on it as a known source of inconsistent behavior. When the last consumer of a library goes through the workspace, delete that library's entry from paths in tsconfig.base.json. Don't wait to remove all the aliases in one batch.
4. Verify each part of the setup
- Delete every
distfolder and the Nx cache, then build from scratch. - Remove a workspace dependency from a consumer's
package.json. The build should fail. If it still passes, some path is resolving around the workspace link. - Check that go-to-definition in your editor opens source files, not stale declarations.
- Run the test runner and the bundler with all alias plugins removed.
#!/usr/bin/env bash
# Verification pass after removing path aliases (assumes a pnpm workspace).
set -euo pipefail
# 1. Build from scratch. Stale dist output or cached task results can hide
# a broken reference graph.
find apps libs -type d -name dist -prune -exec rm -rf {} +
npx nx reset
npx tsc --build tsconfig.json # root solution file listing all references
npx nx run-many -t build
# 2. Negative test: drop one workspace dependency from a consumer.
# If the build still passes, something resolves around the workspace link
# (a leftover alias, a bundler alias plugin, or a hoisted symlink).
CONSUMER=apps/web
DEP=@acme/util
cp "$CONSUMER/package.json" /tmp/consumer-package.json.bak
restore() {
cp /tmp/consumer-package.json.bak "$CONSUMER/package.json"
pnpm install
}
trap restore EXIT
(cd "$CONSUMER" && npm pkg delete "dependencies.$DEP")
pnpm install # relink so $CONSUMER/node_modules no longer contains $DEP
if npx tsc --build "$CONSUMER/tsconfig.json"; then
echo "FAIL: $CONSUMER still builds without $DEP" >&2
exit 1
fi
echo "OK: removing $DEP breaks the $CONSUMER build as expected"
# 3. Confirm no aliases remain in the base config.
if grep -q '"paths"' tsconfig.base.json; then
echo "WARN: tsconfig.base.json still defines paths" >&2
fi
A verification script that rebuilds from a clean state, checks that removing a workspace dependency from a consumer's package.json makes its build fail, and flags any paths entries left in tsconfig.base.json.
What does the migration cost, and where does it save engineering time?
The costs arrive early and stay visible. The savings are spread across every later edit, so they are easy to underrate.
| Cost | Saving | |
|---|---|---|
| Configuration | Every library carries its own tsconfig files and references list, and these must stay in sync with package.json dependencies |
Bundler, test runner and editor all resolve packages through one model, so you maintain a single source of truth |
| Builds | Cold clones and empty caches emit declarations for the whole graph before anything is type-checked | tsc --build rechecks only changed projects and the dependents whose inputs changed |
| Boundaries | An undeclared import fails, which forces extra edits | Boundary violations surface at build time rather than in review |
| Editor | Without declaration maps, go-to-definition lands on .d.ts files |
The language server loads smaller programs for each project |
| Debugging | A stale .tsbuildinfo or mismatched Nx cache output can produce phantom errors, so clean builds become a routine tool |
Type errors are scoped to the project that owns them |
Illustrative estimate (assumed numbers, not a benchmark). Assume 40 libraries of roughly equal size. Assume a typical change touches 2 libraries, and those libraries have 6 downstream dependents between them whose declaration inputs change.
Fraction of type-check work per change ≈ (changed + affected dependents) ÷ total = (2 + 6) ÷ 40 = 20%.
With path aliases, every check pays 100% of the work. The real number depends on graph shape. A change to a widely shared library near the root approaches 100%, and changes to leaf libraries cost far less. Plug in your own fan-out to see which case your workspace falls into.
When should you avoid project references, and what are the alternatives?
Project references pay off when the graph is large enough that rebuilding only what changed matters. Three situations break that assumption.
Small workspaces. With a handful of libraries, a single type-check over everything is already fast. Per-project tsconfig files, emitted declarations and build ordering then add maintenance cost and save little time.
Teams that won't treat libraries as built packages. References assume each library has a declared output and an explicit dependency list. If engineers expect to edit a library and see the change in a consumer without a build step, they will hit stale declarations. They will also resent the extra configuration. The model only works if people accept it.
Unresolved cycles. TypeScript rejects circular project references outright. If two libraries import each other and you can't split them yet, you can't express that graph as references. Keep path aliases for that cluster until the cycle is broken.
| Approach | Type-check scope | Dependency enforcement | Runtime resolution | Configuration overhead | Cold-start cost |
|---|---|---|---|---|---|
| Plain tsconfig paths | Whole program, from source | None; any alias is importable | Needs bundler or loader support for aliases | Low | Moderate; everything is checked together |
| Workspaces linking, no references | Each project, against linked packages | Declared package.json dependencies, strictness depends on the package manager | Native, through node_modules links | Medium | Moderate |
| Workspaces plus references | Per project, against emitted declarations | Declared dependencies plus explicit references | Native, through node_modules links | High | Highest on first build, then incremental |
Linking without references is a reasonable middle step. It gives you correct runtime resolution and explicit dependencies now, and you can add references later.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nx typescript project references, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.