Skip to main content

NX Monorepo

NX is an open-source build system that orchestrates monorepos. It adds caching, dependency graphs, code generators, and affected commands on top of an Angular (or multi-framework) workspace.

Monorepo Structure

my-workspace/
├── apps/
│ ├── shop/ ← Angular app
│ └── admin/ ← Another Angular app
├── libs/
│ ├── ui/ ← Shared component library
│ ├── data-access/ ← Shared services and models
│ └── utils/ ← Pure utility functions
├── nx.json ← NX global config
├── tsconfig.base.json ← Shared path aliases
└── package.json

Create a Workspace

npx create-nx-workspace@latest my-workspace
# → Choose: Angular / Integrated Monorepo

Essential Commands

# Serve an app
nx serve shop

# Build an app
nx build shop --configuration=production

# Run tests
nx test shop
nx test ui

# Generate a new app
nx g @nx/angular:app admin

# Generate a shared library
nx g @nx/angular:lib ui --directory=libs/ui

# Generate a component inside a lib
nx g @nx/angular:component button --project=ui --export

Shared Libraries and Path Aliases

When you generate a lib, NX automatically registers a path alias in tsconfig.base.json:

{
"compilerOptions": {
"paths": {
"@my-workspace/ui": ["libs/ui/src/index.ts"],
"@my-workspace/data-access": ["libs/data-access/src/index.ts"]
}
}
}

Consume it from any app:

import { ButtonComponent } from '@my-workspace/ui';

No npm publish required — libraries are resolved locally.

Dependency Graph

nx graph

Opens an interactive browser view showing which apps depend on which libs. Circular dependencies are flagged automatically.

Rule: apps depend on libs, never the reverse. libs can depend on other libs.

Affected Commands (CI Optimization)

NX analyzes the dependency graph to know what a change impacts:

# Only build what changed + its dependents
nx affected --target=build

# Only test what changed + its dependents
nx affected --target=test

# Run in parallel
nx affected --target=build --parallel=3

In CI, this avoids rebuilding and retesting the entire monorepo on every commit.

Library Type Conventions

TypeContentsNaming example
featureSmart components, pages, routingfeature-checkout
uiPresentational componentsui-button, ui-form
data-accessServices, store, HTTP callsdata-access-products
utilPure functions, helpersutil-formatting

NX vs Angular Workspace

FeatureAngular WorkspaceNX
Multiple appsBasicAdvanced
Build cacheNoneLocal + Cloud
Dependency graphNoneVisual
Code generatorsLimitedPlugin ecosystem
Affected buildsNonenx affected