What is the difference between buildable, non-buildable and publishable Nx libraries?
Nx distinguishes library types by which targets a project has, not by folder layout or a type field. That makes the differences concrete: open project.json and look at the targets block.
A non-buildable library has no build target. Its targets might contain only lint and test. Consuming apps import it through a path alias in the root tsconfig.base.json that points at the library's source entry file. The app's bundler or compiler then treats that source as part of the app. Each app that imports the library compiles it again, and no standalone artifact exists to cache or reuse.
A buildable library adds a build target, usually backed by a TypeScript compiler or bundler executor, with an outputs path under dist/. Nx can run, cache and skip that target independently. This makes incremental builds possible, but it does not make them automatic, as later sections explain.
A publishable library is a buildable library with release metadata: a unique npm-style import path, a package.json with name and version, and output shaped for a registry. Buildable does not imply publishable. Most buildable libraries in a monorepo are never released. They are buildable only so their compilation can be cached.
| Type | build target |
Compiled by | Produces artifact | Registry-ready |
|---|---|---|---|---|
| Non-buildable | No | Each consuming app | No | No |
| Buildable | Yes | The library itself | Yes, in dist/ |
No |
| Publishable | Yes | The library itself | Yes, as a package | Yes |
// libs/ui-utils/project.json (NON-BUILDABLE)
// No build target: apps compile src/index.ts via the tsconfig path alias.
{
"name": "ui-utils",
"sourceRoot": "libs/ui-utils/src",
"projectType": "library",
"targets": {
"lint": { "executor": "@nx/eslint:lint" },
"test": { "executor": "@nx/jest:jest" }
}
}
// libs/data-access/project.json (BUILDABLE)
// Adding a build target lets Nx run, cache and skip this library on its own.
{
"name": "data-access",
"sourceRoot": "libs/data-access/src",
"projectType": "library",
"targets": {
"build": {
"executor": "@nx/js:tsc",
// Declared outputs are what Nx caches and restores.
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/libs/data-access",
"main": "libs/data-access/src/index.ts",
"tsConfig": "libs/data-access/tsconfig.lib.json"
}
},
"lint": { "executor": "@nx/eslint:lint" },
"test": { "executor": "@nx/jest:jest" }
}
}
Two project.json files, shown with comments, which Nx's JSON parser accepts. The only structural difference between a non-buildable and a buildable library is the presence of a build target with declared outputs.
How do incremental builds work in Nx?
Incremental builds in Nx come from one rule in nx.json. Under targetDefaults, the build target gets "dependsOn": ["^build"]. The caret means "run build on every project this one depends on first." Once each library has its own build target, building a service expands into a task graph rather than a single compiler invocation.
orders-api:build MISS (runs, waits on children)
├── domain:build HIT (restored from cache)
│ └── shared-types:build HIT
└── payments:build MISS (runs after money)
└── money:build MISS (runs after shared-types)
└── shared-types:build HIT
Critical path: shared-types → money → payments → orders-api
Before running a task, Nx computes a hash from its inputs. These include the project's source files, relevant configuration, and the hashes of the dependency tasks it relies on. If that hash matches an earlier run, Nx restores the recorded outputs and terminal log from the local cache or a remote cache instead of executing the task. Here, domain and shared-types cost almost nothing. When orders-api consumes their built output instead of their source, its own compile step also has less code to process.
Two consequences follow. First, caching works per task, so you only gain when library tasks are hits. A change to shared-types invalidates every task above it, and the graph then does more work than one monolithic compile would, because each task carries its own process startup and type-checking overhead. Second, depth matters. Siblings like domain and payments can run in parallel, but each link in a chain must wait for the one below it. A deep dependency path therefore sets a floor on wall-clock time, no matter how many cores you have.
{
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": ["default", "!{projectRoot}/**/*.spec.ts"],
"sharedGlobals": ["{workspaceRoot}/tsconfig.base.json"]
},
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": ["production", "^production"],
"outputs": ["{options.outputPath}"],
"cache": true
}
}
}
A minimal nx.json where every project's build target first runs build on its dependencies (^build). The hash covers the project's own production files plus those of its dependencies (^production), and the declared outputs are what Nx restores from cache on a hit.
Are buildable libraries faster? An illustrative cost model
Wall-clock time is only part of the cost. Each buildable library is also a separate task with fixed overhead: process startup, its own tsc or bundler invocation, and writing outputs to the cache or restoring them from it. The worked example below shows how that overhead affects the result.
Illustrative estimate (assumed numbers, not a benchmark). Assume 1 service and 20 libraries. A full non-buildable app compile takes 60 s, of which 40 s is library source (2 s per library) and 20 s is app code. Per-task overhead o = 3 s, cache restore r = 0.5 s per library, and the app build against prebuilt declarations A = 23 s.
Formula: T = Σ(cᵢ + o) over cache misses + (hits × r) + A
| Scenario (assumed) | Non-buildable | Buildable |
|---|---|---|
| Change touches 2 leaf libraries | 60 s | 2×(2+3) + 18×0.5 + 23 = 42 s |
| Change to shared base, 8-library chain rebuilds sequentially | 60 s | 8×(2+3) + 12×0.5 + 23 = 69 s |
In the common case, the buildable setup is faster because most libraries become cheap restores. When a base library changes, the misses form a dependency chain and cannot run in parallel, so the per-task overhead accumulates at every step. Small libraries make this worse. A library that compiles in 2 s still pays 3 s of overhead, so splitting it into its own build task costs more than it saves.
For development cost, the outcome depends on where commits usually land. If they mostly touch leaf libraries, the buildable setup wins. If they often touch shared foundations, it can lose. CI time follows the same pattern, with one difference: a cold or evicted remote cache turns every task into a miss.
How do TypeScript project references compare to Nx task caching?
TypeScript has its own incremental mechanism, and it works at a finer grain. A project marked composite must declare its files explicitly and emit declarations. tsc --build walks the references graph, builds each project in dependency order and writes a .tsbuildinfo file recording file hashes and declaration signatures. On the next run, tsc skips projects that are up to date and, inside a changed project, rechecks only the affected files.
Nx works one level up. It hashes a task's declared inputs and, on a match, restores outputs and replays logs without running anything. The two mechanisms complement each other. Nx skips whole projects across machines, and tsc saves work inside a project that did change. They also duplicate effort: both decide what is stale. If .tsbuildinfo is not a declared output, a cache restore can leave tsc with stale or missing state and a full recheck.
| Aspect | tsc --build |
Nx task cache |
|---|---|---|
| Unit of reuse | File within project | Whole task |
| State | .tsbuildinfo on local disk |
Local or remote cache |
| Dependency source | tsconfig references |
Nx project graph |
| Shared across CI agents | No | Yes, if a remote cache is configured |
Keep the two graphs aligned. Nx infers edges from imports and manifests, while references are maintained by hand. When they diverge, tsc can check a project against stale declarations even though Nx ordered the tasks correctly.
If builds use esbuild or swc, nothing in that path checks types. Add a separate typecheck target that runs tsc --noEmit, or tsc --build for a referenced setup. Mark it cacheable and list the tsconfig files among its inputs.
{
"name": "ui",
"targets": {
"build": {
"executor": "nx:run-commands",
"options": {
"command": "esbuild src/index.ts --bundle --format=esm --outfile=dist/index.js",
"cwd": "libs/ui"
},
"cache": true,
"outputs": ["{projectRoot}/dist"]
},
"typecheck": {
"executor": "nx:run-commands",
"options": {
"command": "tsc --build tsconfig.lib.json",
"cwd": "libs/ui"
},
"cache": true,
"dependsOn": ["^typecheck"],
"inputs": [
"{projectRoot}/src/**/*.ts",
"{projectRoot}/tsconfig*.json",
"{workspaceRoot}/tsconfig.base.json",
{ "externalDependencies": ["typescript"] }
],
"outputs": ["{projectRoot}/out-tsc"]
}
}
}
A project.json where esbuild emits JavaScript without type checks, while a separate cacheable typecheck target runs tsc --build, includes tsconfig files and the TypeScript version in its inputs, and declares out-tsc (declarations plus .tsbuildinfo) as outputs so restores keep tsc state.
Why does your app still compile library source? Path aliases versus built output
The default path alias is the usual cause. An Nx workspace maps each library's import name to its src/index.ts in tsconfig.base.json. Every consumer inherits that mapping. Marking a library buildable does not change it, so the app's compiler keeps resolving imports to library source. The build succeeds, the library's build target runs, and its dist output is never read. You pay for both builds and get the incremental benefit from neither.
Verify which files the app actually compiles
- Inspect compiler inputs. Run
tsc --listFilesortsc --explainFilesagainst the app's tsconfig. If paths underlibs/*/srcappear, the alias is winning.--explainFilesalso states which import pulled each file in. - Inspect the output. Search the bundle or its source maps for library source paths. Built artifacts should show up as
distpaths or.d.tsreferences, not original.tsfiles.
Fixing this requires a tsconfig for the app's build that resolves library imports to built output, or a bundler configured to read dist.
Stale output during local development
Once consumers read built artifacts, developers can serve the app while it runs against an old dist. The app works, but it is running yesterday's library code. Make serve depend on ^build and run library builds in watch mode alongside it. Otherwise, use the source alias for serving only and reserve built output for CI and production builds.
Cache configuration produces the same staleness. If a library's inputs omit its tsconfig, an asset folder, or a shared config file, Nx restores an old artifact after those files change. If outputs are wrong, Nx caches nothing useful. When results look stale, rerun with --skip-nx-cache and compare the output.
#!/usr/bin/env bash
# Check whether the 'web' app compiles library source or reads built output.
# Paths are placeholders; adjust them to your workspace layout.
set -euo pipefail
APP_TSCONFIG=apps/web/tsconfig.app.json
APP_DIST=dist/apps/web
# 1. List every file the compiler pulls in for the app.
# Any match under libs/*/src means the tsconfig.base.json path alias is
# resolving imports to library source, not to dist.
echo "== Library source files in the app's compilation =="
npx tsc -p "$APP_TSCONFIG" --noEmit --listFiles | grep -E '/libs/[^/]+/src/' || echo "none"
# 2. Ask the compiler why one of those files was included.
# --explainFiles names the import that pulled each file in.
echo "== Why library files were included =="
npx tsc -p "$APP_TSCONFIG" --noEmit --explainFiles | grep -A2 -E '/libs/[^/]+/src/' | head -n 20 || true
# 3. Build the app without the cache so you inspect fresh output,
# not an artifact restored from an earlier run.
npx nx build web --skip-nx-cache
# 4. Search the emitted source maps for original library .ts paths.
# Hits mean library source was bundled from libs/, not read from dist.
echo "== Source maps referencing library source =="
grep -rlE 'libs/[^\"]+/src/[^\"]+\.ts' --include='*.map' "$APP_DIST" || echo "none"
A shell check that uses tsc --listFiles and --explainFiles, an uncached Nx build, and a source-map search to show whether the app compiles library source through the path alias instead of reading built output.
How do buildable libraries affect Node service deployment and Docker images?
With a bundler such as esbuild or webpack, workspace libraries are inlined into the service's output file, so the deployable artifact is the same whether or not those libraries are buildable. Third-party packages are usually kept external and installed at runtime. Buildable libraries matter more for unbundled output, for example plain tsc emit. In that case the compiled service still contains import ... from '@org/lib', and Node has to resolve that specifier at runtime. TypeScript path aliases do not exist at runtime, so the built library output has to appear in node_modules or be remapped. Buildable libraries give you a dist folder to place there, but you must do that wiring yourself.
Nx's Node build executors can generate a package.json for the service from the project graph. It lists only the external dependencies the service actually imports, so the image does not install the whole monorepo's dependency set. Pair it with a pruned lockfile so installs stay reproducible.
For Docker, copy the generated package.json and lockfile first, install dependencies, and then copy the built code. The install layer is rebuilt only when external dependencies change.
| Concern | Bundled output | Unbundled output with buildable libs |
|---|---|---|
| Resolving workspace libs at runtime | Nothing to do; code is inlined | Copy lib dist into node_modules or remap paths |
Generated package.json |
Lists external deps only | Must also account for local lib packages |
| Docker layer caching | A service or lib change rebuilds only the final layer | Copy lib output after npm ci, or a lib change invalidates the install layer |
| Stack traces | Need source maps | Readable file paths |
Bundling makes deployment simpler. Unbundled output makes runtime debugging simpler.
When should you make an Nx library buildable, and when should you avoid it?
Start with non-buildable libraries and treat buildability as an optimisation you opt into per library. Every buildable library adds a separate compile target, an output directory and dependency edges that the task graph has to schedule. That overhead pays off only when Nx can skip most of those targets most of the time.
| Signal | Favours buildable | Favours non-buildable |
|---|---|---|
| Size | Large, slow to type-check | Small or thin wrappers |
| Change frequency | Changes rarely | Edited in most PRs |
| Consumers | Many apps and libs depend on it | One or two consumers |
| Graph shape | Shallow, near the leaves | Deep chains of buildable libs |
| Caching | Remote cache shared across CI and developers | Local cache only, CI agents start cold |
Foundational libraries are the trap. If your churn is concentrated in a shared core or types library, every change invalidates everything above it, and a deep chain then rebuilds level by level. That is slower than compiling the source once. Without a remote cache, a cold CI agent has nothing to skip and pays the full per-library cost on every run.
A strict buildable setup has a useful side effect. It exposes implicit imports and circular dependencies that path aliases were hiding. Fixing them improves the architecture, but a single cycle between two libraries can block a conversion until someone untangles it.
Convert a few high-value leaf libraries first, then measure the result before going further. Some repos will show no gain, and keeping everything non-buildable is a legitimate outcome.
How do you measure whether buildable libraries save engineering time?
Keep a written baseline before changing anything. Pick a representative window of CI runs, ideally a mix of small fixes, cross-cutting refactors and dependency bumps. For each run, record total wall-clock time on the critical path, not the sum of per-task times. Parallel agents hide a lot of task time, so a library build that adds work off the critical path costs compute but not engineer waiting time.
Then run a trial conversion on one or two candidate libraries. Before converting, open nx graph and check how deep the dependency chain is and how many projects depend on each candidate. A buildable library on a long chain adds a sequential build step. A library with high fan-out that rarely changes is the case most likely to produce cache hits.
Over a similar window afterwards, compare three numbers from Nx's task output: cache hit rate for the converted libraries' build targets, app build duration on runs where those libraries were cache hits, and critical-path wall-clock time across all runs.
Illustrative estimate (assumed numbers, not a benchmark): Net saving per run = (hit rate × time saved per hit) − ((1 − hit rate) × added time per miss). With an assumed 0.8 hit rate, 40 s saved per hit and 25 s added per miss: (0.8 × 40) − (0.2 × 25) = 27 s per run.
Keep the change if this figure is clearly positive and larger than run-to-run noise. Revert it if the result is near zero or negative, or if developers start reporting stale-output confusion.
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 buildable libraries, 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.