What are plain, buildable and publishable libraries in Nx?
Nx distinguishes libraries by how their code reaches a consumer, not by what the code does. All three types live in the same workspace and share the same source layout. The difference is whether a library has its own build step and whether it is packaged for use outside the repository.
A plain library has no build target. The consuming app imports it through a TypeScript path mapping in the workspace's base tsconfig, and the app's bundler or compiler pulls the library's source into the app's own build. The library has no separate artifact to version, cache or keep in sync.
A buildable library has its own build target that compiles it to an output directory, typically under dist. Because that target is independent, Nx can cache it and skip it when its inputs are unchanged. The trade-off is that a buildable library should only depend on other buildable libraries, so its compiled output never points at raw source.
A publishable library is a buildable library with package metadata. It has an npm-scope import path such as @acme/logger and a package.json with a name and version, so the build output can be released to a registry.
| Plain | Buildable | Publishable | |
|---|---|---|---|
| Build target | None | Yes | Yes |
| Output | Compiled into the consuming app | Own folder in dist |
Own folder in dist, packaged for release |
| Package metadata | None | Minimal or none | npm-scope name, package.json with name and version |
| Dependency constraints | Can import any allowed library | Should depend only on buildable libraries | Should depend only on buildable or publishable libraries |
| Intended consumers | Apps in the same workspace | Apps in the same workspace | Consumers outside the workspace, via a registry |
Generator options and executor names change across Nx versions. Check them against the version you run.
How does a backend app consume each library type?
With a plain library, the app does all the work. The workspace's base tsconfig maps an import alias to the library's entry file, for example "@acme/billing": ["libs/billing/src/index.ts"]. When the API app's bundler or tsc sees import { Invoice } from '@acme/billing', it resolves that alias straight into the library's source and compiles it along with the app's own code in one pass. The library has no build target and produces no output of its own.
A buildable library adds a build target in its project.json, typically using a TypeScript executor such as @nx/js:tsc, with outputPath pointing somewhere like dist/libs/billing. That target emits compiled JavaScript and .d.ts files. Nx can cache those outputs and skip rebuilding the library when its inputs haven't changed.
Plain library (source via path alias)
apps/api build ──alias──▶ libs/billing/src/*.ts
└── compiles app + library source in one pass
Buildable library (built artifacts)
libs/billing build ──▶ dist/libs/billing/*.js, *.d.ts (cached)
apps/api build ──reads──▶ dist/libs/billing
└── compiles only app source
Marking a library buildable does not make the app's build incremental. If the app's build still resolves the alias to src/index.ts, it recompiles the library source and ignores the cached output. The consuming build has to be configured to read the built artifacts instead. Some Nx bundler executors expose an option for this, such as buildLibsFromSource: false. Executor names and options vary between Nx versions, so check them against the plugins installed in your workspace.
// tsconfig.base.json: the alias points at library SOURCE.
// With this alone, the app compiles libs/billing/src in its own pass.
{
"compilerOptions": {
"paths": {
"@acme/billing": ["libs/billing/src/index.ts"]
}
}
}
// libs/billing/project.json: makes the library buildable.
// Emits .js and .d.ts to dist/, which Nx can cache.
{
"name": "billing",
"targets": {
"build": {
"executor": "@nx/js:tsc",
"outputs": ["{options.outputPath}"],
"options": {
"main": "libs/billing/src/index.ts",
"tsConfig": "libs/billing/tsconfig.lib.json",
"outputPath": "dist/libs/billing"
}
}
}
}
// apps/api/project.json: the consumer must opt in to built artifacts.
// "^build" builds dependencies first, and buildLibsFromSource: false
// makes the bundler read dist/ instead of following the alias into src/.
// Verify executor names and options for your installed Nx version.
{
"targets": {
"build": {
"executor": "@nx/webpack:webpack",
"dependsOn": ["^build"],
"options": { "buildLibsFromSource": false }
}
}
}
Three config fragments, each preceded by a comment naming its file, show a source-pointing path alias, a buildable library's tsc build target, and the app-side settings (dependsOn and buildLibsFromSource: false) needed for the app build to read the library's compiled output.
Do you need buildable libraries if Nx caching and affected already speed up builds?
Caching and the affected graph already work for every library type. When you run test, lint or build, Nx skips projects the change does not reach and restores cached results for any target whose inputs are unchanged. A plain library's tests and lint get the same treatment as a buildable one's.
The difference is inside a changed app's build. Caching works at the project level, locally or remotely. If an app's build misses the cache, its compiler processes every plain library's source again, including libraries that did not change. A buildable library has its own cached build output, so an app configured to consume artifacts compiles only its own code plus the library that changed.
Illustrative estimate. All inputs below are assumed, not measured:
| Scenario | Assumed inputs | Plain libraries | Buildable libraries |
|---|---|---|---|
| Large service, one library changed | 20 libraries at 15 s each, app code 30 s, 10 s artifact overhead | ~330 s | ~55 s (15 + 30 + 10) |
| Small service, one library changed | 4 libraries at 3 s each, app code 10 s, 8 s overhead | ~22 s | ~21 s (3 + 10 + 8) |
In the first case, library compilation dominates the build, so the savings repeat on every CI run and every local rebuild. In the second, the saving is close to zero. You still pay for extra build targets, output paths and per-library configuration that someone has to maintain. That maintenance cost only pays off when compile time is spread across many libraries that change independently.
Why are plain libraries usually the best default for deployable backend services?
For a deployable backend service, the artifact that matters is the container image, not the individual libraries. When libraries are plain, the app's build target compiles them from source through the TypeScript path aliases and a bundler such as esbuild or webpack folds them into one output. Your Dockerfile then copies a single directory instead of reconstructing a workspace layout of per-library dist folders.
The bundle can't contain everything. Node built-ins like fs and crypto are treated as external and resolved by the runtime. Native addons, the packages that ship compiled .node binaries, also have to stay external, because their binaries are built for a specific platform and can't be inlined into JavaScript. Those dependencies need a real node_modules in the image, installed on the same OS and architecture the container runs on.
Nx's Node build executors can generate a package.json for the app output. They derive it from the project graph, so it lists only the third-party packages the service actually imports, with versions taken from the root manifest. Running a production install against that file in the image gives you a lean node_modules without per-library manifests to keep in sync.
The cost is that path aliases are forgiving. A deep import like @acme/billing/src/internal/tax resolves fine in the bundle even though it bypasses the library's index.ts. The problem stays hidden until someone makes that library buildable or publishable, and then the import breaks because the path isn't part of the library's declared entry point.
# Stage 1: build the app. Plain libraries are compiled from source via
# tsconfig path aliases and bundled into dist/apps/api by the app's build target.
# Assumes the build target uses an Nx Node executor (e.g. esbuild) with
# "generatePackageJson": true, so the output includes a pruned package.json.
FROM node:20-slim AS build
WORKDIR /workspace
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npx nx build api --configuration=production
# Stage 2: runtime image. Same base image as above, so native addons
# are installed for the OS and CPU architecture the container actually runs on.
FROM node:20-slim
WORKDIR /app
ENV NODE_ENV=production
# Copy only the generated manifest first so the dependency layer caches well.
# It lists only the third-party packages the service imports, not the whole root manifest.
COPY --from=build /workspace/dist/apps/api/package.json ./
# Install externals that could not be bundled (e.g. packages shipping .node binaries).
# Node built-ins like fs and crypto need nothing here; the runtime provides them.
# If an addon must compile from source, add build tools (python3, make, g++) in this stage.
RUN npm install --omit=dev
# One directory holds the bundled service and every plain library it uses;
# no per-library dist folders or workspace layout to reconstruct.
COPY --from=build /workspace/dist/apps/api ./
USER node
CMD ["node", "main.js"]
A multi-stage Dockerfile that copies a single bundled app output, then runs a production install against the Nx-generated package.json so native addons get a real node_modules built for the container's platform.
How do module boundaries enforce isolation without making libraries buildable?
For isolation, the main tool is the @nx/enforce-module-boundaries lint rule. It operates on the project graph and import statements, not on build output, so it applies the same way to plain, buildable and publishable libraries. You give each project tags in its project.json, such as "tags": ["scope:billing", "type:data-access"]. You then declare depConstraints in the lint config. For example, { "sourceTag": "type:feature", "onlyDependOnLibsWithTags": ["type:data-access", "type:util"] } stops feature code from reaching into other features. A second constraint, { "sourceTag": "scope:billing", "onlyDependOnLibsWithTags": ["scope:billing", "scope:shared"] }, keeps billing from importing ledger internals. The same rule flags relative imports that cross into another library, deep imports that skip a library's index.ts, and circular dependencies. Those are the problems the previous section described.
Buildable libraries work differently. A buildable library's compiled output is built against the compiled output of its dependencies, so a buildable library can only depend on other buildable libraries. Suppose you convert a mid-level billing-domain library so it can be built on its own. Every library it imports must also be converted, and so must every library those import. Each converted library gets its own build target, output directory and correct dependency declarations. In a backend workspace with a deep shared-utility layer, one conversion can spread through most of the graph.
If your goal is "teams must not couple to each other's internals," tags and constraints get you there with a lint config change. They add no build targets and no extra artifacts to keep in sync.
// eslint.config.mjs (workspace root)
// Tags live in each project's project.json, for example:
// libs/billing/feature-invoices/project.json -> "tags": ["scope:billing", "type:feature"]
// libs/billing/data-access/project.json -> "tags": ["scope:billing", "type:data-access"]
import nx from '@nx/eslint-plugin';
export default [
...nx.configs['flat/base'],
{
files: ['**/*.ts'],
rules: {
'@nx/enforce-module-boundaries': [
'error',
{
// Reports a buildable lib that imports a non-buildable one.
// Only relevant if you opt into buildable libs.
enforceBuildableLibDependency: true,
allow: [],
depConstraints: [
// Layering: features never import other features.
{
sourceTag: 'type:feature',
onlyDependOnLibsWithTags: ['type:data-access', 'type:util'],
},
// Domain isolation: billing cannot import ledger internals.
{
sourceTag: 'scope:billing',
onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'],
},
// Shared code must stay generic and depend only on other shared code.
{
sourceTag: 'scope:shared',
onlyDependOnLibsWithTags: ['scope:shared'],
},
],
},
],
},
},
];
This root ESLint flat config enforces scope and layer boundaries through tags and depConstraints. It applies the same way to plain, buildable and publishable libraries, and it adds no build targets.
When should you make a library publishable, and when should you avoid it?
Publishing is a different commitment. A publishable library becomes a package that other code installs by version, so everything the workspace normally handles for you becomes your job.
In practice that means:
- A stable public API. Anything exported from the entry point is a contract. Renaming a function is now a breaking change for people you cannot see.
- Semantic versioning discipline. Someone has to decide whether each change is a patch, minor or major release, and get it right every time.
- A release process. Versions must be bumped, changelogs written and artifacts pushed to a registry, ideally by automation rather than by hand.
- Correct dependency declarations. Runtime imports go in regular dependencies. Build tooling goes in dev dependencies. Shared singletons the consumer already owns, such as a framework or database client, go in peer dependencies.
Dependency mistakes are the dangerous part because the workspace hides them. Inside the repo, every package resolves from the root node_modules, so a missing declaration still works. A consumer installing the package gets a missing-module error at runtime. A framework declared as a regular dependency instead of a peer can install twice, which breaks dependency injection or instanceof checks.
Versioning drift follows. External consumers upgrade on their own schedule, so you cannot change a library and its callers in one commit. You end up supporting several versions at once.
Publish when another repository, an external team or a customer installs the package. For sharing between apps in the same repo, avoid publishing. You pay all of these costs and get nothing back.
How do you choose a library type and convert between them without a rewrite?
Start every library plain and change its type only when you have evidence. Changing type later is a configuration edit, so there is little reason to decide early.
| Situation | Recommended type | Alternative to consider |
|---|---|---|
| Shared code used only by apps in this repo | Plain | Buildable, if profiling shows its compilation dominates |
| Library compilation dominates app build time | Buildable | Splitting the library or trimming its dependencies |
| Library needs different compiler settings | Buildable | Moving the divergent code into its own app |
| Installed as a package outside the repo | Publishable | Buildable plus an internal registry, only if versioning is unavoidable |
Converting in either direction follows the same steps. Before you edit anything, open nx graph and focus on the library. Its dependents are what you will affect, and its dependencies must also become buildable, because a buildable library may depend only on other buildable libraries. To convert, add or remove the build target and the package metadata, then update import paths so consumers resolve the package name rather than a relative path.
Expect three problems that make local and CI results disagree:
- Stale
distoutput. Old artifacts can satisfy an import that should fail. Deletedistand rebuild from clean. - Misconfigured cache inputs. If the cache inputs omit a tsconfig or another config file, a cached result can survive a real change. Run once with the cache skipped and compare the output.
- Mismatched TypeScript settings. The library's tsconfig and the base config can drift apart, for example in
strictortarget. Diff the two before you trust a green build.
#!/usr/bin/env bash
# Pre- and post-conversion checks for one library (placeholder names).
set -euo pipefail
LIB=orders-domain
LIB_DIR=libs/orders-domain
# 1. See the impact first: dependents are affected, dependencies must be buildable.
nx graph --focus="$LIB"
# 2. Confirm which targets the library has now (is there a build target?).
nx show project "$LIB"
# 3. Stale dist output: remove old artifacts so they cannot satisfy imports.
rm -rf dist
# 4. Cache inputs: build with the cache, then without, and compare outputs.
nx build "$LIB"
cp -r "dist/$LIB_DIR" /tmp/cached-build
rm -rf dist
nx build "$LIB" --skip-nx-cache
diff -r /tmp/cached-build "dist/$LIB_DIR" \
&& echo "cached and uncached output match" \
|| echo "outputs differ: check the target's cache inputs"
# 5. TypeScript drift: compare the resolved settings, not the raw files,
# so 'extends' chains are flattened before diffing.
npx tsc --showConfig -p tsconfig.base.json > /tmp/base.json
npx tsc --showConfig -p "$LIB_DIR/tsconfig.lib.json" > /tmp/lib.json
diff <(grep -E '"(strict|target|module|moduleResolution)"' /tmp/base.json) \
<(grep -E '"(strict|target|module|moduleResolution)"' /tmp/lib.json) \
|| echo "compiler settings differ: confirm this is intentional"
A shell script that checks a library's project-graph impact before conversion, then catches stale dist output, cache-input gaps and TypeScript setting drift that can make local and CI builds disagree.
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.