What is the difference between buildable and non-buildable Nx libraries?

A non-buildable library has no build target in its project configuration. It is a folder of TypeScript source that the workspace exposes through path mappings in the root tsconfig. When an application imports it, the application's own build compiles the library's source along with everything else. The library never produces output of its own, so Nx caches nothing for it separately. A change to the library invalidates the cached build of every application that imports it.

A buildable library has its own build target that compiles the library into an output directory. Nx can cache that output and skip rebuilding the library when its inputs have not changed. A consumer configured for incremental builds can compile against the library's emitted JavaScript and type declarations instead of its source. Without that configuration, the consumer still resolves the source through the path mapping. Having a build target alone does not change how consumers compile.

A publishable library is a buildable library with a contract for consumers outside the workspace. It adds a real package name, a version, a package.json with dependency declarations, and release configuration. Making a library buildable creates an internal build artifact. Making it publishable commits you to semver, a changelog, and backward compatibility for people you cannot coordinate with in one pull request.

Type Build target Output How consumers resolve it Intended consumer
Non-buildable None None; compiled inside the consumer's build TypeScript path mapping to source Apps and libraries in the same workspace
Buildable Yes Compiled JS and declarations in an output directory Source via path mapping, or compiled output in incremental setups Workspace projects that want cached, separately built dependencies
Publishable Yes, plus release configuration Versioned package ready for a registry Package name from a registry External repositories and teams
# Non-buildable: no build target. Consumers compile its source
# through the path mapping added to tsconfig.base.json.
nx g @nx/js:library --name=order-rules --directory=libs/order-rules --bundler=none

# Buildable: adds a build target (tsc) that writes JS + .d.ts
# to an output directory that Nx can cache on its own.
nx g @nx/js:library --name=order-store --directory=libs/order-store --bundler=tsc

# Publishable: buildable plus a real package name and release
# metadata for consumers outside this workspace.
nx g @nx/js:library --name=order-client --directory=libs/order-client \
  --bundler=tsc --publishable --importPath=@acme/order-client

# Inspect the resolved targets. Only the buildable and
# publishable libraries list a 'build' target.
nx show project order-rules
nx show project order-store

# Build the buildable library by itself. A second run with
# unchanged inputs is served from the Nx cache.
nx build order-store
nx build order-store

# This fails with no build target. The library is only ever
# compiled as part of an app that imports it.
nx build order-rules

Generating the three Nx library types with @nx/js:library: only the buildable and publishable libraries get a build target that Nx can run and cache on its own.

How do incremental builds work with nx buildable libraries?

Nx builds the project graph first, then runs targets in topological order. When an application's build target depends on the build target of its dependencies, Nx builds the leaf libraries first, then the libraries that use them, then the service. Each task is hashed from its inputs: source files, configuration, relevant environment, and the hashes of its dependencies. If a hash matches a previous run, Nx restores the task's outputs from the local or remote cache instead of running it. Change one library, and only that library and its dependents get new hashes. Everything else is a cache hit. The same graph lets nx affected limit work in CI to projects reachable from the changed files.

That only pays off if the service's build actually consumes the built output. The default TypeScript path mappings in most workspaces point at library source. If the service build still resolves those mappings, the bundler or compiler re-reads and re-transpiles every library's source on every service build. The library builds become extra work that nothing uses.

Source-based resolution             Output-based resolution

orders-service build                orders-service build
  ├─ compiles libs/db/src             ├─ reads dist/libs/db      (cached)
  ├─ compiles libs/auth/src           ├─ reads dist/libs/auth    (cached)
  └─ compiles libs/events/src         └─ reads dist/libs/events  (rebuilt)

cost: all libs, every time          cost: changed libs + service

Whether a service build resolves source or output depends on its executor or plugin. Some executors rewrite path mappings to built output, and some expose an option that controls this. These behaviors and their defaults have changed across Nx releases. Check the current documentation for the executor your workspace uses instead of copying a configuration from an older example.

SOURCE-BASED: service build re-transpiles library source every time

┌─────────────┐  ┌──────────────┐  ┌────────────────┐
│ libs/db/src │  │ libs/auth/src│  │ libs/events/src│
└──────┬──────┘  └──────┬───────┘  └───────┬────────┘
       │                │                  │
       └────────────────┼──────────────────┘
                        ▼
              ┌───────────────────┐
              │ orders-service    │
              │ build: transpiles │
              │ all 3 libs        │
              └───────────────────┘

OUTPUT-BASED: libs build first (topological order), service reads dist/

┌─────────────┐  ┌──────────────┐  ┌────────────────┐
│ libs/db     │  │ libs/auth    │  │ libs/events    │  <- changed
└──────┬──────┘  └──────┬───────┘  └───────┬────────┘
       ▼ cache hit      ▼ cache hit        ▼ rebuilt
┌─────────────┐  ┌──────────────┐  ┌────────────────┐
│ dist/libs/db│  │dist/libs/auth│  │dist/libs/events│
└──────┬──────┘  └──────┬───────┘  └───────┬────────┘
       └────────────────┼──────────────────┘
                        ▼
              ┌───────────────────┐
              │ orders-service    │
              │ build: bundles    │
              │ dist/ output      │
              └───────────────────┘

With source-based resolution the service recompiles every library on each build. With output-based resolution, unchanged libraries come from cache and only the changed library and the service rebuild.

Why do buildable libraries often fail to speed up backend builds?

The most common failure is that the service bundler never uses the library outputs. If the application's build resolves workspace imports through TypeScript path aliases, it compiles every library from source no matter what is in dist. The library builds then run in addition to the full compile instead of replacing part of it.

Granularity is the second failure. Each buildable library is a separate task with its own process startup, compiler initialization, cache lookup and output write. For small libraries, that fixed overhead can be larger than the compilation it avoids.

Third, the dependency graph controls how much is saved. A change to a leaf library rebuilds one project. A change to a shared core utility, such as logging, config or types, invalidates every project that depends on it, and those are usually the libraries that change most often.

Illustrative estimate, with these assumed inputs: 20 libraries at 6 s of compilation each, 2 s of per-task overhead, a 40 s service bundle that compiles from source, and 16 libraries that depend on the core utility.

Scenario (illustrative estimate) Libraries rebuilt Library task time Service bundle Total
Non-buildable baseline 0 0 s 40 s 40 s
Buildable, leaf change 1 8 s 40 s 48 s
Buildable, core change 16 128 s 40 s 168 s

Mixed resolution also causes correctness problems. When one import path resolves to source and another resolves to compiled output, the same module can load twice. That breaks singletons and instanceof checks, path aliases can conflict with package names, and the debugger may step into transpiled JavaScript instead of your TypeScript source.

When should a backend team make a library buildable, and when should it avoid it?

The recommended default for backend services is non-buildable libraries that the application bundles. One build tool, one module graph and one set of compiler settings remove the duplicate-loading and path-resolution problems described above.

Buildable libraries pay off in two situations. The first is a large service with leaf libraries that change often and have low fan-in, such as a payment adapter that only one or two apps import. A change there rebuilds a small artifact and leaves everything else cached. The second is a large CI fleet that uses remote or distributed caching, because one agent's output can then be reused by every other agent.

Remote caching only helps when cache inputs are precise. Hits must be frequent, which means inputs are not over-broad, and correct, which means no real input is missing. If a library reads an undeclared environment variable or a config file outside its inputs, the cache can return stale output, and you ship code that does not match the source. That is harder to diagnose than a slow build, because nothing looks broken until production behaves differently.

Situation Buildable? Why
Small project graph Avoid Orchestration overhead exceeds savings
High fan-in core library Avoid Every change invalidates most dependents
Low fan-in, frequently changed leaf Consider Rebuilds stay small and isolated
Large CI fleet with remote cache Consider Shared hits amortise build cost
Team lacks dependency discipline Avoid Imprecise inputs cause stale caches

The tradeoff with non-buildable libraries is that build time grows with total source size. As the codebase grows, that can become the bottleneck that forces the decision.

How do you measure whether buildable libraries will save time?

Measure before converting anything. You need three numbers: the cost of a build without cache, how often each candidate library changes, and how many projects depend on it.

1. Time cold and warm builds. Pick a representative service and run time nx build my-service --skip-nx-cache several times. Use the median, because the first run includes disk and dependency-install noise. Then run time nx build my-service with the cache enabled. If the uncached build is already short, conversion has little to gain.

2. Find churn in version control. Run git log --since="3 months ago" --name-only --format="" and count changed paths per library directory. Libraries that change in most commits are poor candidates. Their cached output is invalidated so often that you mostly pay the extra build step.

3. Check fan-in. Open nx graph to inspect a library's dependents visually, or export the graph with nx graph --file=graph.json and count the dependents. A stable library with high fan-in is the best candidate. Every dependent reuses its output instead of recompiling it. Run nx affected -t build against recent commits to see how much of the workspace each change actually touches.

Illustrative estimate (assumed numbers, not a benchmark):

Weekly savings = builds × (P(unchanged) × (t_lib − t_overhead) − P(changed) × t_overhead)

Assume the following:

  • 200 builds per week
  • The library takes 20 s to compile inline
  • A separate build step adds 5 s of overhead
  • The library changes in 10% of commits

The calculation is 200 × (0.9 × 15 − 0.1 × 5) = 2,600 s, or about 43 minutes per week. Multiply the per-build term by fan-in when several dependents would otherwise compile the library. If the result is a few minutes per week, the added configuration and maintenance work outweighs the savings.

#!/usr/bin/env bash
# Gather the three numbers before converting any library to buildable.
set -euo pipefail
SERVICE=orders-api          # representative backend service (placeholder)
LIB=shared-domain           # candidate library project name (placeholder)
TIMEFORMAT='%R'             # make bash 'time' print wall-clock seconds only

# 1. Cold builds: five uncached runs, take the median (3rd of 5 sorted).
echo "cold median (s):"
for i in 1 2 3 4 5; do
  { time npx nx build "$SERVICE" --skip-nx-cache >/dev/null 2>&1; } 2>&1
done | sort -n | sed -n '3p'

# Warm build: cache enabled, run after the cold runs have populated it.
echo "warm (s):"
{ time npx nx build "$SERVICE" >/dev/null 2>&1; } 2>&1

# 2. Churn: changed files per library directory over the last 3 months.
# Groups by the first two path segments (libs/<name>); adjust for nested layouts.
git log --since="3 months ago" --name-only --format="" -- libs/ \
  | awk -F/ 'NF>2 {print $1"/"$2}' | sort | uniq -c | sort -rn | head -20

# 3. Fan-in: export the project graph and count projects that depend on LIB.
npx nx graph --file=graph.json
jq --arg lib "$LIB" \
  '[.graph.dependencies[][] | select(.target == $lib) | .source] | unique | length' \
  graph.json

# Blast radius: what a typical recent range of commits would rebuild.
npx nx affected -t build --base=HEAD~20 --head=HEAD

A measurement script that records the median uncached and the cached build time for one service, ranks library directories by three months of git churn, counts a candidate library's direct dependents from the exported Nx project graph, and shows which projects recent commits affect.

How do you convert a library to buildable safely?

Start with every library non-buildable and convert one at a time, only where the estimate from the previous section shows a real saving. If you convert in bulk, you can't tell which conversion helped and which only added overhead.

Each conversion needs three pieces of configuration. The first is a build target that uses a compile executor. The second is a library-specific tsconfig that sets rootDir, emits declarations, and excludes test files. The third is an output path that Nx caches and that dependents resolve against. The example below shows the minimum: a build target, its outputs, and dependsOn: ["^build"] so that upstream libraries compile first. Executor option names have changed across Nx releases, so check the options your installed version supports before copying anything.

Across dozens of libraries, these files tend to drift. One library ends up with a different target, another emits to a different directory. To limit this, generate new libraries from a shared generator or a base tsconfig instead of copying configuration by hand.

Dependency hygiene also becomes mandatory. Every npm package and workspace library that the code imports must be declared. Path aliases let a non-buildable library import anything in the repo, so undeclared imports that worked before will fail once the library compiles on its own. This slows teams down. It also exposes hidden coupling that would eventually have caused problems anyway.

To verify a conversion, compare the service's bundled output before and after, including file list, size, and resolved imports. Then run the service's integration tests and a smoke test against a staging deployment, so you confirm that runtime behavior hasn't changed.

{
  "name": "orders-domain",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/orders-domain/src",
  "projectType": "library",
  "targets": {
    "build": {
      "executor": "@nx/js:tsc",
      "outputs": ["{options.outputPath}"],
      "dependsOn": ["^build"],
      "cache": true,
      "options": {
        "outputPath": "dist/libs/orders-domain",
        "main": "libs/orders-domain/src/index.ts",
        "tsConfig": "libs/orders-domain/tsconfig.lib.json",
        "assets": ["libs/orders-domain/*.md"]
      }
    }
  }
}

A minimal project.json build target for a buildable library: outputs tells Nx what to cache, and dependsOn ["^build"] compiles upstream libraries first. Check the executor options your Nx version supports.

What are the alternatives and complements to buildable libraries?

If the measurements from earlier don't justify the conversion, staying non-buildable is a valid choice. Put the effort into the application's build target instead. Tune the bundler so it skips work it doesn't need, such as type-checking during bundling when a separate typecheck target already handles it. Make sure the target's cache inputs are precise, so that a change to a README doesn't invalidate the service build.

When a single service's build stays slow no matter what you do, the service is usually too large. Splitting it reduces the code each build touches, and that tends to save more time than library-level caching.

Use publishable libraries only when code must be consumed from other repositories. They add versioning and release work that internal code doesn't need.

Library type doesn't enforce architecture. Tags and the @nx/enforce-module-boundaries lint rule do. For example, a constraint with sourceTag: "scope:billing" and onlyDependOnLibsWithTags: ["scope:billing", "scope:shared"] blocks billing code from importing another domain's internals. It works the same way whether or not a library is buildable.

Option Main cost Pays off when
Non-buildable + tuned app build Bundler and cache-input tuning Most backend services
Buildable libraries Config upkeep, cache correctness, dependency friction Measured savings on large, stable libraries
Split the service Deployment and ownership changes One service dominates build time
Publishable libraries Versioning and release process Code ships outside the repo

Weigh the ongoing development cost against the build time you actually measured. That cost includes target configuration, debugging stale caches, and the friction of declaring every dependency. Estimated savings are not enough to justify it.

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.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

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.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • 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.