
Nx Monorepo
- 1.6k installs
- 311 repo stars
- Updated June 22, 2026
- giuseppe-trisciuoglio/developer-kit
nx-monorepo is an agent skill that provides comprehensive nx monorepo management guidance for typescript/javascript projects. use when creating nx workspaces, generating apps/libraries/components, running affected comman
About
nx-monorepo is an agent skill from giuseppe-trisciuoglio/developer-kit that provides comprehensive nx monorepo management guidance for typescript/javascript projects. use when creating nx workspaces, generating apps/libraries/components, running affected commands, setting up . # Nx Monorepo ## Overview Provides guidance for Nx monorepo management in TypeScript/JavaScript projects. Covers workspace creation, project generation, task execution, caching strategies, Module Federation, and CI/CD integration. ## When to Use Use this skill when: - Creating a new Nx workspace or initializing Nx in an existing project - Gener Developers invoke nx-monorepo during build/backend work for backend & apis tasks. The skill documents triggers, prerequisites, and step-by-step workflows grounded in SKILL.md. Compatible with Claude Code, Cursor, and Codex agent runtimes that load marketplace skills. Review the Security Audits panel on this listing before installing in production environments.
- Creating a new Nx workspace or initializing Nx in an existing project
- Generating applications, libraries, or components with Nx generators
- Running affected commands or executing tasks across multiple projects
- Setting up CI/CD pipelines for Nx projects (GitHub Actions, CircleCI, etc.)
- Configuring Module Federation with React or Next.js
Nx Monorepo by the numbers
- 1,606 all-time installs (skills.sh)
- +63 installs in the week ending Jul 28, 2026 (Skillselion tracking)
- Ranked #297 of 4,386 Backend & APIs skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
nx-monorepo capabilities & compatibility
- Capabilities
- creating a new nx workspace or initializing nx i · generating applications, libraries, or component · running affected commands or executing tasks acr · setting up ci/cd pipelines for nx projects (gith · configuring module federation with react or next
- Use cases
- orchestration
What nx-monorepo says it does
- Creating a new Nx workspace or initializing Nx in an existing project
- Generating applications, libraries, or components with Nx generators
- Running affected commands or executing tasks across multiple projects
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill nx-monorepoAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.6k |
|---|---|
| repo stars | ★ 311 |
| Security audit | 3 / 3 scanners passed |
| Last updated | June 22, 2026 |
| Repository | giuseppe-trisciuoglio/developer-kit ↗ |
What it does
Provides comprehensive Nx monorepo management guidance for TypeScript/JavaScript projects. Use when creating Nx workspaces, generating apps/libraries/components, running affected commands, setting up
Who is it for?
Developers working on backend & apis during build tasks.
Skip if: Tasks outside Backend & APIs scope described in SKILL.md.
When should I use this skill?
Provides comprehensive Nx monorepo management guidance for TypeScript/JavaScript projects. Use when creating Nx workspaces, generating apps/libraries/components, running affected commands, setting up
What you get
Completed backend & apis workflow aligned with SKILL.md steps.
- nx.json configuration snippets
- project.json target dependency definitions
Files
Nx Monorepo
Overview
Provides guidance for Nx monorepo management in TypeScript/JavaScript projects. Covers workspace creation, project generation, task execution, caching strategies, Module Federation, and CI/CD integration.
When to Use
Use this skill when:
- Creating a new Nx workspace or initializing Nx in an existing project
- Generating applications, libraries, or components with Nx generators
- Running affected commands or executing tasks across multiple projects
- Setting up CI/CD pipelines for Nx projects (GitHub Actions, CircleCI, etc.)
- Configuring Module Federation with React or Next.js
- Implementing NestJS backend applications within Nx
- Managing TypeScript package libraries with buildable and publishable libs
- Setting up remote caching or Nx Cloud
- Optimizing monorepo build times and caching strategies
- Debugging dependency graph issues or circular dependencies
Trigger phrases: "create Nx workspace", "Nx monorepo", "generate Nx app", "Nx affected", "Nx CI/CD", "Module Federation Nx", "Nx Cloud"
Instructions
Workspace Creation
1. Create a new workspace with interactive setup:
npx create-nx-workspace@latestFollow prompts to select preset (Integrated, Standalone, Package-based) and framework stack.
2. Initialize Nx in an existing project:
nx@latest init3. Create with specific preset (non-interactive):
npx create-nx-workspace@latest my-workspace --preset=reactVerify: nx show projects lists the new workspace projects
Project Generation
1. Generate a React application:
nx g @nx/react:app my-app2. Generate a library:
# React library
nx g @nx/react:lib my-lib
# TypeScript library
nx g @nx/js:lib my-utilVerify: nx show projects lists the new lib
3. Generate a component in lib:
nx g @nx/react:component my-comp --project=my-lib4. Generate NestJS backend:
nx g @nx/nest:app my-apiVerify: nx show projects lists my-api and nx run my-api:build succeeds
Task Execution
1. Run tasks for affected projects only:
nx affected -t lint test build2. Run tasks across all projects:
# Build all projects
nx run-many -t build
# Test specific projects
nx run-many -t test -p=my-app,my-lib
# Test by pattern
nx run-many -t test --projects=*-app3. Run specific target on single project:
nx run my-app:build4. Visualize dependency graph:
nx graphProject Configuration
Each project has a project.json defining targets, executor, and configurations:
{
"name": "my-app",
"projectType": "application",
"sourceRoot": "apps/my-app/src",
"targets": {
"build": {
"executor": "@nx/react:webpack",
"outputs": ["{workspaceRoot}/dist/apps/my-app"],
"configurations": {
"production": {
"optimization": true
}
}
},
"test": {
"executor": "@nx/vite:test"
}
},
"tags": ["type:app", "scope:frontend"]
}Dependency Management
1. Set up project dependencies:
{
"targets": {
"build": {
"dependsOn": [
{ "projects": ["shared-ui"], "target": "build" }
]
}
}
}2. Use tags for organization:
{ "tags": ["type:ui", "scope:frontend", "platform:web"] }Module Federation (Nx 17+)
1. Generate a remote (micro-frontend):
nx g @nx/react:remote checkout --host=dashboard2. Generate a host:
nx g @nx/react:host dashboardCI/CD Setup
Use affected commands in CI to only build/test changed projects:
# .github/workflows/ci.yml
- run: npx nx affected -t lint --parallel
- run: npx nx affected -t test --parallel
- run: npx nx affected -t build --parallelExamples
Example 1: Create New React Workspace
Input: "Create a new Nx workspace with React and TypeScript"
Steps:
npx create-nx-workspace@latest my-workspace
# Select: Integrated Monorepo → React → Integrated monorepo (Nx Cloud)Verify: cd my-workspace && nx show projects lists the created app
Expected Result: Workspace created with:
apps/directory with React applibs/directory for shared librariesnx.jsonwith cache configuration- CI/CD workflow files ready
Example 2: Run Tests for Changed Projects
Input: "Run tests only for projects affected by recent changes"
Command:
nx affected -t test --base=main~1 --head=mainExpected Result: Only tests for projects affected by changes between commits are executed, leveraging cached results from previous runs.
Example 3: Generate and Build a Shared Library
Input: "Create a shared UI library and use it in the app"
Steps:
# Generate library
nx g @nx/react:lib shared-ui
# Generate component in library
nx g @nx/react:component button --project=shared-ui
# Import in app (tsconfig paths auto-configured)
import { Button } from '@my-workspace/shared-ui'Verify: nx run shared-ui:build completes successfully and nx graph shows the dependency link to your app
Expected Result: Buildable library at libs/shared-ui with proper TypeScript path mapping configured.
Example 4: Set Up Module Federation
Input: "Configure Module Federation for micro-frontends"
Steps:
# Create host app
nx g @nx/react:host dashboard
# Add remote to host
nx g @nx/react:remote product-catalog --host=dashboard
# Start dev servers
nx run dashboard:serve
nx run product-catalog:serveVerify: Both servers start without errors and nx graph shows dashboard → product-catalog remote connection
Expected Result: Two separate applications running where product-catalog loads dynamically into dashboard at runtime.
Example 5: Debug Build Dependencies
Input: "Why is my app rebuilding when unrelated lib changes?"
Diagnosis:
# Show project graph
nx graph --focused=my-app
# Check implicit dependencies
nx show project my-app --json | grep implicitDependenciesSolution: Add explicit dependency configuration or use namedInputs in nx.json to exclude certain files from triggering builds.
Verify Fix Worked: Make a change to the unrelated lib, run nx affected -t build — my-app should not appear in the affected projects list.
Best Practices
- Always use `nx affected` in CI to only test/build changed projects
- Organize libs by domain/business capability, not by technical layer
- Use tags consistently (
type:app|lib,scope:frontend|backend|shared) - Prevent circular dependencies by configuring
workspaceLayoutboundaries innx.json - Enable remote caching with Nx Cloud for team productivity
- Keep project.json simple - use defaults from
nx.jsonwhen possible - Leverage generators instead of manual file creation for consistency
- Configure `namedInputs` to exclude test files from production cache keys
- Use Module Federation for independent deployment of micro-frontends
- Keep workspace generators in
tools/for project-specific scaffolding
Constraints and Warnings
- Node.js 18.10+ is required for Nx 17+
- Windows users: Use WSL or Git Bash for best experience
- First-time setup may take longer due to package installation
- Large monorepos (50+ projects) should use distributed task execution
- Module Federation requires webpack 5+ and specific Nx configuration
- Some generators require additional plugins to be installed first
- Cache location: Default
~/.nx/cachecan grow large; configurecacheDirectoryinnx.jsonif needed - Circular dependencies will cause build failures; use
nx graphto visualize - Preset migration: Converting between Integrated/Standalone/Package-based requires manual effort
Reference Files
For detailed guidance on specific topics, consult:
| Topic | Reference File |
|---|---|
| Workspace setup, basic commands | references/basics.md |
| Generators (app, lib, component) | references/generators.md |
| React, Next.js, Expo patterns | references/react.md |
| NestJS backend patterns | references/nestjs.md |
| TypeScript packages | references/typescript.md |
| CI/CD (GitHub, CircleCI, etc.) | references/ci-cd.md |
| Caching, affected, advanced | references/advanced.md |
Advanced Nx Reference
Task Orchestration
Dependencies
Define task dependencies in project.json:
{
"targets": {
"build": {
"dependsOn": [
{ "projects": ["shared-ui"], "target": "build" },
{ "projects": ["api"], "target": "build", "params": "ignore" }
]
}
}
}Target Defaults
Configure default behavior in nx.json:
{
"targetDefaults": {
"build": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production"]
},
"test": {
"cache": true,
"inputs": ["default", "^production"]
},
"lint": {
"cache": true
}
}
}Caching
Local Cache
Enabled by default. Cache location:
.nx/cacheBypass Cache
# Single run
nx run my-app:build --skip-nx-cache
# Reset cache
nx resetRemote Cache
# Install Azure cache
nx add @nx/azure-cache
# Generates activation key saved to .nx/key/key.ini
# Set as environment variable: NX_KEYConfiguration in nx.json:
{
"nxCloudId": "your-workspace-id",
"nxCloudUrl": "https://cloud.nx.app"
}Affected Commands
Base Configuration
# GitHub Actions
- uses: nrwl/nx-set-shas@v4
with:
main-branch-name: 'main'Affected Patterns
# Basic affected
nx affected -t build
# With base/head
nx affected -t build --base=origin/main~1 --head=HEAD
# With files
nx affected -t build --files=libs/shared/*
# Exclude projects
nx affected -t build --exclude=legacy-app
# Run multiple targets
nx affected -t lint test build
# Parallel execution
nx affected -t build --parallel=5Project Graph
Visualize Graph
# Open in browser
nx graph
# Output as JSON
nx graph --json=output.json
# Output as static HTML
nx graph --file=graph.html
# Watch mode
nx graph --watchQuery Projects
# List all projects
nx show projects
# List projects with specific tags
nx show projects --tags=type:ui
# Show project details
nx show project my-app
# Show dependencies (JSON)
nx show project my-app --json
# Show affected projects
nx show projects --affectedModule Federation
Micro-Frontends Architecture
host-app (Shell)
├── remote1 (Checkout)
├── remote2 (Catalog)
└── remote3 (User Profile)Setup Host
nx g @nx/react:host shell-appSetup Remote
nx g @nx/react:remote checkout --name=remote1 --port=4201Add Remote to Host
nx g @nx/react:remote-configuration shell-app \
--remote=remote1 \
--port=4201 \
--type=moduleModule Federation Config
// apps/shell-app/module-federation.config.ts
module.exports = {
name: 'shell',
remotes: {
remote1: 'remote1@http://localhost:4201/remoteEntry.js',
},
};Named Inputs
Configuration in nx.json
{
"namedInputs": {
"default": ["{projectRoot}/**/*"],
"production": [
"default",
"!{projectRoot}/**/*.spec.ts",
"!{projectRoot}/**/*.test.ts",
"!{projectRoot}/**/*.stories.ts"
],
"nonProduction": [
"default",
"{projectRoot}/**/*.spec.ts",
"{projectRoot}/**/*.test.ts"
]
},
"targetDefaults": {
"build": {
"inputs": ["production", "^production"]
},
"test": {
"inputs": ["default", "^production"]
}
}
}Workspace Layout
Integrated Layout
my-workspace/
├── apps/
├── libs/
└── tools/Standalone Projects
my-workspace/
├── packages/
│ ├── app1/
│ └── lib1/Set in nx.json:
{
"workspaceLayout": {
"appsDir": "packages",
"libsDir": "packages"
}
}Plugins
Use Plugins
// nx.json
{
"plugins": [
{
"plugin": "@nx/react"
},
{
"plugin": "@nx/js",
"options": {
"buildTargetName": "build",
"testTargetName": "test"
}
}
]
}Custom Plugin Options
{
"plugins": [
{
"plugin": "@nx/dotnet",
"options": {
"build": {
"targetName": "compile",
"configurations": {
"production": { "optimization": true }
}
},
"test": {
"targetName": "unit-test",
"dependsOn": ["build"]
}
}
}
]
}Generators
Custom Workspace Generator
# Create generator
nx g workspace-generator my-generator
# Run generator
nx workspace-generator my-generatorSync Generator
Run automatically after npm install / yarn:
nx g @nx/js:lib my-lib --syncRelease
Version Projects
# Version all
nx release version --version=1.0.0
# Version specific projects
nx release version --projects=my-lib --version=1.2.3
# Interactive
nx release versionPublish
# Dry run
nx release publish --dry-run
# Publish
nx release publish
# With first release
nx release publish --firstReleaseChangelog
# Generate changelog
nx release changelog
# For specific version
nx release changelog --version=1.0.0Conformance
Install Conformance
nx add @nx/conformanceConfiguration
// nx.json
{
"conformance": {
"rules": [
{
"rule": "@nx/conformance/enforce-project-boundaries",
"options": {},
"projects": ["*"]
}
]
}
}Owners
GitHub CODEOWNERS
// nx.json
{
"owners": {
"format": "github",
"outputPath": "CODEOWNERS",
"patterns": [
{
"description": "Frontend team owns UI projects",
"projects": ["tag:type:ui"],
"owners": ["@frontend-team"]
},
{
"description": "Backend team owns API",
"projects": ["api"],
"owners": ["@backend-team"]
},
{
"description": "DevOps owns workflows",
"files": [".github/workflows/**/*"],
"owners": ["@devops"]
}
]
}
}Performance
Task Runner Options
// nx.json
{
"targetDefaults": {
"build": {
"parallel": true,
"maxParallel": 4
}
}
}Cache Encryption
// nx.json
{
"encryptionKey": "your-encryption-key"
}Agent Configuration (Nx Cloud)
Launch Templates
// .nx/workflows/agents.yaml
launch-templates:
my-linux-medium-js:
resource-class: 'docker_linux_amd64/medium'
image: 'ubuntu22.04-node20.11-v9'
init-steps:
- name: Checkout
uses: 'nrwl/nx-cloud-workflows/v5/workflow-steps/checkout/main.yaml'
- name: Install Node Modules
uses: 'nrwl/nx-cloud-workflows/v5/workflow-steps/install-node-modules/main.yaml'Start CI Run
# Manual distribution
npx nx-cloud start-ci-run --distribute-on="manual"
# Static distribution
npx nx-cloud start-ci-run --distribute-on="3 linux-medium-js"
# Stop agents after specific tasks
npx nx-cloud start-ci-run --stop-agents-after="e2e-ci"Troubleshooting
Debug Task Execution
# Dry run
nx affected -t build --dry-run
# Verbose output
nx run my-app:build --verbose
# Show task graph
nx affected -t build --graph=stdout
# Skip cache
nx run my-app:build --skip-nx-cacheCommon Issues
"Project X not found"
- Check project name in
project.jsonorworkspace.json
"Circular dependency detected"
- Check
dependsOnconfiguration - Use
nx graphto visualize dependencies
Cache not working
- Check
outputspaths inproject.json - Verify cache directory permissions
Nx Basics Reference
Workspace Creation
New Workspace with Presets
npx create-nx-workspace@latestInteractive prompts guide you through:
- Workspace name
- Package manager (npm, yarn, pnpm, bun)
- Preset selection (React, Angular, Node, TypeScript, etc.)
Initialize Nx in Existing Project
For projects with existing package.json:
nx@latest initFor npm workspace projects, create package.json first:
{
"name": "my-workspace",
"version": "1.0.0",
"private": true,
"workspaces": ["packages/*", "apps/*"]
}Then run nx@latest init.
Project Structure
Standard Layout
my-workspace/
├── apps/ # Deployable applications
│ ├── web-app/ # React app
│ └── api/ # NestJS API
├── libs/ # Shared libraries
│ ├── shared-ui/ # UI components
│ └── utils/ # Utilities
├── tools/ # Workspace tools
├── nx.json # Nx workspace config
├── tsconfig.base.json # Base TS config
└── package.json # Root package.jsonConfiguration Files
nx.json - Workspace-level configuration:
{
"namedInputs": {
"default": ["{projectRoot}/**/*"],
"production": [
"default",
"!{projectRoot}/**/*.spec.ts",
"!{projectRoot}/**/*.test.ts"
]
},
"targetDefaults": {
"build": {
"cache": true,
"dependsOn": ["^build"]
}
}
}project.json - Project-level configuration (per project):
{
"name": "my-app",
"projectType": "application",
"sourceRoot": "apps/my-app/src",
"targets": {
"build": { "executor": "@nx/react:webpack" },
"serve": { "executor": "@nx/react:dev-server" },
"test": { "executor": "@nx/vite:test" },
"lint": { "executor": "@nx/linter:eslint" }
}
}Essential Commands
Running Tasks
# Run specific target on project
nx run <project>:<target>
# Run target with configuration
nx run <project>:<target> --configuration=production
# Run task for all affected projects
nx affected -t <target>
# Run multiple targets for affected projects
nx affected -t lint test build
# Run task across specific projects
nx run-many -t <target> -p <proj1> <proj2>
# Run task across all projects
nx run-many -t <target>
# Run with parallel control
nx run-many -t build --parallel=3
# Run sequentially
nx run-many -t build --parallel=falseProject Operations
# List all projects
nx show projects
# Show project graph
nx graph
# Show project details
nx show project <project-name>
# Show dependencies
nx show project <project-name> --web=false --jsonGenerator Shortcuts
# g = generate
nx g <collection>:<generator>
# Examples
nx g @nx/react:component my-component
nx g @nx/js:lib shared-utilsInstallation
Install Nx Plugins
# React plugin
nx add @nx/react
# Angular plugin
nx add @nx/angular
# Node/NestJS plugin
nx add @nx/node
# JavaScript/TypeScript plugin
nx add @nx/jsEnsure plugin version matches Nx version.
Global Installation (Optional)
# Ubuntu/Debian
sudo add-apt-repository ppa:nrwl/nx
sudo apt update
sudo apt install nx
# Use globally
nx build my-project
nx generate application
nx graphCommon Workflows
New Feature Development
# 1. Generate feature library
nx g @nx/js:lib feature-a --directory=libs/features
# 2. Add component/service
nx g @nx/react:component button --project=feature-a
# 3. Run tests
nx run-many -t test --projects=feature-a
# 4. Build affected
nx affected -t build
# 5. Update dependency graph
nx graphDebugging Task Execution
# Show what would run without running
nx affected -t build --dry-run
# Show task graph
nx affected -t build --graph
# Verbose output
nx run my-app:build --verbose
# Skip cache
nx run my-app:build --skip-nx-cacheCI/CD Reference
GitHub Actions
Basic CI Workflow
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
actions: read
contents: read
jobs:
main:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
filter: tree:0
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- uses: nrwl/nx-set-shas@v4
- run: npx nx affected -t lint test build
- run: npx nx fix-ci
if: always()With Nx Cloud DTE
name: Nx Cloud - Main Job
on:
push:
branches: [main]
pull_request:
jobs:
main:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
filter: tree:0
- uses: actions/setup-node@v3
with:
node-version: 20
cache: 'npm'
- run: npm ci
- uses: nrwl/nx-set-shas@v4
- name: Initialize Nx Cloud distributed CI run
run: npx nx-cloud start-ci-run --distribute-on="manual" --stop-agents-after=e2e-ci
- name: Check formatting
run: npx nx-cloud record -- nx format:check
- name: Lint, test, build, and run e2e
run: npx nx affected -t lint,test,build,e2e-ci --configuration=ci
agents:
runs-on: ubuntu-latest
strategy:
matrix:
agent: [1, 2, 3]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v3
with:
node-version: 20
cache: 'npm'
- run: npm ci
- name: Start Nx Agent
run: npx nx-cloud start-agent
env:
NX_AGENT_NAME: ${{ matrix.agent }}Static Agent Distribution
- run: npx nx-cloud start-ci-run --distribute-on="3 linux-medium-js" --stop-agents-after="build"CircleCI
Basic Configuration
// .circleci/config.yml
version: 2.1
orbs:
nx: nrwl/nx@1.7.0
jobs:
main:
docker:
- image: cimg/node:lts-browsers
steps:
- checkout
- run: npm ci
- nx/set-shas:
main-branch-name: 'main'
- run:
command: npx nx affected -t lint test build
- run:
command: npx nx fix-ci
when: on_fail
workflows:
version: 2
ci:
jobs:
- mainWith Nx Cloud DTE
version: 2.1
orbs:
nx: nrwl/nx@1.5.1
jobs:
main:
docker:
- image: cimg/node:lts-browsers
steps:
- checkout
- run: npm ci
- nx/set-shas
- run: npx nx-cloud start-ci-run --distribute-on="manual" --stop-agents-after=e2e-ci
- run: npx nx-cloud record -- nx format:check
- run: npx nx affected --base=$NX_BASE --head=$NX_HEAD -t lint,test,build,e2e-ci --parallel=2 --configuration=ci
workflows:
build:
jobs:
- agent:
matrix:
parameters:
ordinal: [1, 2, 3]
- mainAzure Pipelines
Basic Configuration
jobs:
- job: main
displayName: Nx Cloud Main Job
pool:
vmImage: 'ubuntu-latest'
steps:
- checkout: self
fetchDepth: '0'
fetchFilter: tree:0
persistCredentials: true
- script: npm ci
- script: npx nx-cloud start-ci-run --distribute-on="manual" --stop-agents-after=e2e-ci
- script: npx nx-cloud record -- nx format:check
- script: npx nx affected -t lint,test,build,e2e-ci --configuration=ciJenkins
Declarative Pipeline
pipeline {
agent none
environment {
NX_BRANCH = env.BRANCH_NAME.replace('PR-', '')
}
stages {
stage('Pipeline') {
parallel {
stage('Main') {
when {
branch 'main'
}
agent any
steps {
sh "npm ci"
sh "npx nx affected -t lint test build"
}
}
stage('PR') {
when {
not { branch 'main' }
}
agent any
steps {
sh "npm ci"
sh "npx nx affected -t lint test build --base=origin/main"
}
}
}
}
}
}GitLab CI
Basic Configuration
// .gitlab-ci.yml
image: node:20
variables:
CI: 'true'
stages:
- test
test:
stage: test
script:
- npm ci
- npx nx run-many -t lint test build
only:
- main
- merge_requestsWith Nx Cloud DTE
image: node:20
clone:
depth: full
definitions:
steps:
- step: &agent
name: Agent
script:
- export NX_BRANCH=$BITBUCKET_PR_ID
- npm ci
- npx nx-cloud start-agent
pipelines:
pull-requests:
'**':
- parallel:
- step:
name: CI
script:
- export NX_BRANCH=$BITBUCKET_PR_ID
- npm ci
- npx nx-cloud start-ci-run --distribute-on="manual" --stop-agents-after="e2e-ci"
- npx nx-cloud record -- nx format:check
- npx nx affected --target=lint,test,build,e2e-ci --parallel=2
- step: *agent
- step: *agent
- step: *agentBitbucket Pipelines
Basic Configuration
image: node:20
pipelines:
branches:
main:
- step:
name: CI
script:
- npm ci
- npx nx affected -t lint test build
pull-requests:
'**':
- step:
name: CI
script:
- npm ci
- npx nx affected -t lint test build --base=origin/mainDocker Publishing
GitHub Actions Docker Workflow
name: Docker Publish
on:
push:
branches: [main]
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 20
- name: Install dependencies
run: npm ci
- name: Build applications
run: npx nx run-many -t build
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_TOKEN }}
- name: Build and tag Docker images
run: npx nx release version --dockerVersionScheme=production
- name: Publish Docker images
run: npx nx release publishAffected Commands in CI
Base Branch Configuration
- uses: nrwl/nx-set-shas@v4
with:
main-branch-name: 'main'Affected Command Patterns
# Test affected
npx nx affected -t test
# Lint, test, build affected
npx nx affected -t lint test build
# With configuration
npx nx affected -t build --configuration=production
# Exclude projects
npx nx affected -t build --exclude=legacy-app
# Parallel execution
npx nx affected -t test --parallel=5Nx Cloud Setup
Connect Workspace
nx connectSelf-Healing CI
- run: npx nx fix-ci
if: always()Record Commands
# Record specific command
npx nx-cloud record -- nx format:check
# Record with environment variables
npx nx-cloud record --env=MY_VAR=value -- nx testCache Configuration
GitHub Actions Cache
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'Nx Remote Cache
# Install Azure cache
nx add @nx/azure-cache
# Install AWS cache (custom setup required)
# See Nx docs for S3-based cachingCI Best Practices
1. Use affected commands - Only test/build changed projects 2. Set SHAs correctly - Required for affected to work 3. Enable caching - Speed up CI with npm cache and Nx cache 4. Parallel execution - Use --parallel flag where appropriate 5. Distributed task execution - For large repos, use Nx Cloud agents 6. Fix CI - Use nx fix-ci for automatic fixes 7. Record tasks - Use nx-cloud record for better debugging
Nx Generators Reference
Application Generators
React Application
# Using Vite
nx g @nx/react:app my-app --style=css
# Using Webpack
nx g @nx/react:app my-app --bundler=webpack
# With specific directory
nx g @nx/react:app my-app --directory=apps/web
# With TypeScript strict mode
nx g @nx/react:app my-app --strict
# With routing
nx g @nx/react:app my-app --routing
# Options: style (css|scss|stylus|less|sass)
nx g @nx/react:app my-app --style=scssNext.js Application
# Basic Next.js app
nx g @nx/next:app my-next-app
# With custom directory
nx g @nx/next:app my-next-app --directory=apps/next
# With TypeScript
nx g @nx/next:app my-next-app --tsConfig=tsconfig.base.jsonNestJS Application
# NestJS app
nx g @nx/node:app my-api --framework=nest
# Or using NestJS plugin directly
nx g @nx/nest:app my-api
# With directory
nx g @nx/nest:app my-api --directory=apps/apiExpress Application
nx g @nx/node:app my-express-api --framework=expressLibrary Generators
React Library
# Buildable library (creates build target)
nx g @nx/react:lib shared-ui
# Publishable library
nx g @nx/react:lib shared-ui --publishable
# With directory
nx g @nx/react:lib shared-ui --directory=libs/shared/ui
# Import path (importable as @myorg/shared-ui)
nx g @nx/react:lib shared-ui --importPath=@myorg/shared-uiTypeScript/JavaScript Library
# Basic library
nx g @nx/js:lib utils
# Buildable with entry point
nx g @nx/js:lib utils --buildable
# With directory structure
nx g @nx/js:lib utils --directory=libs/shared/utils
# Set import path
nx g @nx/js:lib date-fns --importPath=@myorg/date-fnsNode Library
nx g @nx/node:lib my-node-libComponent Generators
React Component
# In specific project
nx g @nx/react:component button --project=shared-ui
# With directory in project
nx g @nx/react:component header --project=web-app --path=apps/web-app/src/components
# With styling
nx g @nx/react:component card --project=shared-ui --style=scss
# With export (barrel export)
nx g @nx/react:component button --project=shared-ui --export
# With flat structure
nx g @nx/react:component button --project=shared-ui --flat
# Skip tests
nx g @nx/react:component button --project=shared-ui --skipTestsAngular Component
nx g @nx/angular:component header --project=my-appService/Class Generators
NestJS Services
# Module in NestJS app
nx g @nx/nest:module users --project=my-api
# Controller
nx g @nx/nest:controller users --project=my-api
# Service
nx g @nx/nest:service users --project=my-api
# All at once (module + controller + service)
nx g @nx/nest:resource users --project=my-apiTypeScript Interfaces/Classes
# Interface
nx g @nx/js:interface user --project=utils
# Class
nx g @nx/js:class validator --project=utilsSpecialized Generators
Module Federation
# Host application
nx g @nx/react:host host-app
# Remote application
nx g @nx/react:remote remote-app --name=remote1
# Add remote to host
nx g @nx/react:remote-configuration host-app --remote=remote1 --port=4201Storybook Setup
# For React library
nx g @nx/react:storybook-configuration shared-ui
# For Angular library
nx g @nx/angular:storybook-configuration shared-uiTailwind CSS
# React project
nx g @nx/react:setup-tailwind my-app
# With custom stylesheet
nx g @nx/react:setup-tailwind my-app --stylesEntryPoint=apps/my-app/src/styles.scssTesting Setup
# Cypress E2E
nx g @nx/cypress:cypress-project my-app-e2e --bundler=vite
# Playwright E2E
nx g @nx/playwright:project my-app-e2e
# Jest unit tests
nx g @nx/jest:project my-libGenerator Options Reference
Common Options
| Option | Description | Example |
|---|---|---|
--directory | Output directory | --directory=libs/shared |
--tags | Project tags | --tags=type:ui,scope:frontend |
--style | Styling approach | --style=scss |
--skipTests | Skip test files | --skipTests |
--flat | Flat directory structure | --flat |
--export | Export from index | --export |
--strict | Enable strict mode | --strict |
Path Modes
Nx supports two path modes for generators:
As-provided (recommended):
nx g lib my-lib # apps/my-lib
nx g lib my-lib --directory=libs/shared
# libs/shared/my-libDerived (legacy):
nx g lib my-lib # Creates directory based on workspace configWorkflow Examples
Create New Feature Library
# 1. Create library
nx g @nx/react:lib feature-auth --directory=libs/features --importPath=@myorg/feature-auth
# 2. Add components
nx g @nx/react:component LoginForm --project=feature-auth --export
nx g @nx/react:component LoginButton --project=feature-auth --export
# 3. Build library
nx run feature-auth:buildAdd E2E Tests to App
# Add Cypress to existing app
nx g @nx/cypress:cypress-project web-app-e2e --bundler=vite --project=web-appMigrate Component
# Move component to library
nx g @nx/react:component button --project=shared-ui --export --flatNestJS Backend Reference
Create NestJS Application
Basic Setup
# Using Node plugin with NestJS framework
nx g @nx/node:app my-api --framework=nest
# Using NestJS plugin directly
nx g @nx/nest:app my-api
# With directory
nx g @nx/nest:app my-api --directory=apps/apiNestJS Library
# NestJS library
nx g @nx/nest:lib auth --directory=libs/backend
# With import path
nx g @nx/nest:lib shared-backend --importPath=@myorg/shared-backendProject Configuration
project.json for NestJS App
{
"name": "api",
"projectType": "application",
"sourceRoot": "apps/api/src",
"targets": {
"build": {
"executor": "@nx/js:tsc",
"outputs": ["{workspaceRoot}/dist/apps/api"],
"options": {
"assets": ["apps/api/src/assets"],
"main": "apps/api/src/main.ts",
"tsConfig": "apps/api/tsconfig.app.json"
},
"configurations": {
"production": {
"optimization": true,
"extractLicenses": true,
"inspect": false
}
}
},
"serve": {
"executor": "@nx/js:node",
"options": {
"buildTarget": "api:build"
}
},
"test": {
"executor": "@nx/jest:jest",
"options": {
"jestConfig": "apps/api/jest.config.ts"
}
},
"lint": {
"executor": "@nx/linter:eslint"
}
}
}Webpack Configuration (Optional)
For webpack bundling, configure nx-webpack.config.js:
const { NxWebpackPlugin } = require('@nx/webpack');
const { join } = require('path');
module.exports = {
output: {
path: join(__dirname, '../../dist/apps/api'),
},
plugins: [
new NxWebpackPlugin({
target: 'node',
compiler: 'tsc',
transformers: [
{
name: '@nestjs/swagger/plugin',
options: {
dtoFileNameSuffix: ['.dto.ts', '.entity.ts'],
},
},
],
}),
],
};NestJS Generators
Resource Generator (All-in-One)
# Creates module, controller, service
nx g @nx/nest:resource users --project=my-api
# Creates with specific path
nx g @nx/nest:resource products --project=my-api --path=productsIndividual Generators
# Module
nx g @nx/nest:module auth --project=my-api
# Controller
nx g @nx/nest:controller users --project=my-api
# Service
nx g @nx/nest:service email --project=my-api
# Interface
nx g @nx/nest:interface user --project=my-api
# Class (DTO/Entity)
nx g @nx/nest:class create-user-dto --project=my-apiSubdirectory Structure
# Create in subdirectory
nx g @nx/nest:controller admin/users --project=my-api
# Creates: apps/api/src/admin/users/users.controller.tsSwagger Integration
Setup Swagger
// apps/api/src/main.ts
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app/app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Swagger configuration
const config = new DocumentBuilder()
.setTitle('API Documentation')
.setDescription('My API description')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();DTO with Swagger Decorators
// apps/api/src/users/dto/create-user.dto.ts
import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({ example: 'john@example.com' })
email: string;
@ApiProperty({ example: 'John Doe' })
name: string;
@ApiProperty({ example: 'P@ssw0rd!' })
password: string;
}Testing
Unit Tests
# Run tests
nx test my-api
# Watch mode
nx test my-api --watch
# Coverage
nx test my-api --coverageE2E Tests
# Add E2E to NestJS app
nx g @nx/jest:app my-api-e2e --project=my-api
# Run E2E
nx e2e my-api-e2eExample Test
// apps/api/src/users/users.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
describe('UsersService', () => {
let service: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersService],
}).compile();
service = module.get<UsersService>(UsersService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('should create a user', () => {
const user = service.create({
email: 'test@example.com',
name: 'Test User',
});
expect(user).toHaveProperty('id');
});
});Common Patterns
Microservices
# Create microservice app
nx g @nx/node:app auth-microservice --framework=nestConfiguration:
// apps/auth-microservice/src/main.ts
import { NestFactory } from '@nestjs/core';
import { Transport, MicroserviceOptions } from '@nestjs/microservices';
import { AppModule } from './app/app.module';
async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.TCP,
options: { host: '127.0.0.1', port: 8877 },
},
);
await app.listen();
}
bootstrap();Shared Backend Library
# Create shared library
nx g @nx/nest:lib shared-backend --importPath=@myorg/shared-backend
# Add interfaces/dto
nx g @nx/nest:interface user --project=shared-backend
nx g @nx/nest:class create-user-dto --project=shared-backend
# Use in API
// apps/api/src/users/users.service.ts
import { CreateUserDto } from '@myorg/shared-backend';Environment Configuration
// apps/api/src/config/configuration.ts
export default () => ({
port: parseInt(process.env.PORT, 10) || 3000,
database: {
host: process.env.DATABASE_HOST || 'localhost',
port: parseInt(process.env.DATABASE_PORT, 10) || 5432,
},
});TypeORM Integration
# Install TypeORM
npm install @nestjs/typeorm typeormConfiguration:
// apps/api/src/app/app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'user',
password: 'pass',
database: 'mydb',
autoLoadEntities: true,
}),
],
})
export class AppModule {}Running NestJS App
# Development with watch
nx serve my-api
# Production build
nx build my-api --configuration=production
# Run production
node dist/apps/api/main.jsCommon Tasks
Add Validation
npm install class-validator class-transformer// dto/create-user.dto.ts
import { IsEmail, IsString, MinLength } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
@MinLength(2)
name: string;
}Add Guard
nx g @nx/nest:guard auth --project=my-apiAdd Interceptor
nx g @nx/nest:interceptor logging --project=my-apiAdd Pipe
nx g @nx/nest:pipe validation --project=my-apiReact / Next.js / Expo Reference
React Applications
Create React App
# Vite (recommended)
nx g @nx/react:app my-app --style=scss
# Webpack
nx g @nx/react:app my-app --bundler=webpack
# With routing
nx g @nx/react:app my-app --routing
# With standalone mode (React 19+)
nx g @nx/react:app my-app --standaloneReact Library
# Buildable library
nx g @nx/react:lib shared-ui --style=scss
# Publishable npm package
nx g @nx/react:lib design-system --publishable --importPath=@myorg/design-system
# With directory structure
nx g @nx/react:lib ui-components --directory=libs/shared/uiReact Component Generator
# Basic component
nx g @nx/react:component Button --project=shared-ui
# With all options
nx g @nx/react:component Header \
--project=web-app \
--style=scss \
--export \
--skipTests \
--flatProject Configuration
{
"name": "web-app",
"projectType": "application",
"sourceRoot": "apps/web-app/src",
"targets": {
"build": {
"executor": "@nx/vite:build",
"outputs": ["{workspaceRoot}/dist/apps/web-app"],
"configurations": {
"production": {
"mode": "production"
},
"development": {
"mode": "development"
}
}
},
"serve": {
"executor": "@nx/vite:dev-server",
"configurations": {
"production": {
"buildTarget": "web-app:build:production"
}
}
},
"test": {
"executor": "@nx/vite:test"
},
"lint": {
"executor": "@nx/linter:eslint"
}
}
}Next.js Applications
Create Next.js App
# Pages router
nx g @nx/next:app my-next-app
# App directory (Next.js 13+)
nx g @nx/next:app my-next-app --style=scss
# With custom directory
nx g @nx/next:app my-next-app --directory=apps/nextNext.js Project Configuration
{
"targets": {
"build": {
"executor": "@nx/next:build",
"outputs": ["{workspaceRoot}/dist/apps/next-app"],
"configurations": {
"production": {},
"development": {}
}
},
"serve": {
"executor": "@nx/next:server"
},
"export": {
"executor": "@nx/next:export"
}
}
}Serve Next.js
# Development
nx serve my-next-app
# Production build serve
nx start my-next-app
nx serve my-next-app --prodExpo / React Native
Create Expo App
nx g @nx/expo:app my-mobile-appServe Expo App
# Web
nx start my-mobile-app --web
# iOS
nx start my-mobile-app --ios
# Android
nx start my-mobile-app --androidModule Federation
Micro-Frontend Setup
# Host application
nx g @nx/react:host shell-app
# Remote application
nx g @nx/react:remote checkout-app --name=checkout --port=4201
# Add remote to host
nx g @nx/react:remote-configuration shell-app \
--remote=checkout \
--port=4201 \
--type=moduleModule Federation Config
Webpack configuration for module federation is automatically generated. Key files:
apps/shell-app/
├── module-federation.config.ts
└── src/
├── app/
│ ├── app.component.tsx
│ └── routes.tsx
└── bootstrap.tsxLoad remote module:
// routes.tsx
import { loadRemoteModule } from '@angular-architects/module-federation';
export const routes: Routes = [
{
path: 'checkout',
loadChildren: () =>
loadRemoteModule({
type: 'module',
remoteEntry: 'http://localhost:4201/remoteEntry.js',
exposedModule: './Module'
}).then(m => m.RemoteModule)
}
];Tailwind CSS
Setup Tailwind
# React project
nx g @nx/react:setup-tailwind my-app
# With custom stylesheet
nx g @nx/react:setup-tailwind my-app --stylesEntryPoint=apps/my-app/src/styles.scssNx React Webpack Plugin
Configure for custom webpack:
const { NxReactWebpackPlugin } = require('@nx/react/webpack-plugin');
module.exports = {
plugins: [
new NxReactWebpackPlugin({
svgr: false, // Disable SVGR
}),
],
};Storybook
Setup Storybook for Library
# React library
nx g @nx/react:storybook-configuration shared-ui
# Run Storybook
nx storybook shared-ui
# Build Storybook
nx build-storybook shared-uiStorybook Composition
For composed Storybooks (multiple libraries):
# Start individual instances
nx storybook ui-lib-1 # Port: 4400
nx storybook ui-lib-2 # Port: 4401Testing
Vitest (Recommended for Vite)
# Test project
nx test my-react-app
# Watch mode
nx test my-react-app --watch
# UI mode
nx test my-react-app --ui
# Coverage
nx test my-react-app --coverageComponent Testing
# Component with test
nx g @nx/react:component Button --project=shared-uiTest example:
// button.component.spec.tsx
import { render, screen } from '@testing-library/react';
import { Button } from './button';
describe('Button', () => {
it('renders with text', () => {
render(<Button text="Click me" />);
expect(screen.getByText('Click me')).toBeInTheDocument();
});
});E2E Testing
# Add Cypress to app
nx g @nx/cypress:cypress-project my-app-e2e --bundler=vite
# Run E2E
nx e2e my-app-e2e
# Run with UI
nx e2e my-app-e2e --watchCommon Patterns
Shared UI Library
# 1. Create library
nx g @nx/react:lib design-system --style=scss --importPath=@myorg/design-system
# 2. Add components
nx g @nx/react:component Button --project=design-system --export
nx g @nx/react:component Input --project=design-system --export
nx g @nx/react:component Card --project=design-system --export
# 3. Build library
nx run design-system:build
# 4. Use in app
// apps/web-app/src/app/app.tsx
import { Button } from '@myorg/design-system';Feature Libraries
# Feature-specific libraries
nx g @nx/react:lib feature-auth --directory=libs/features --tags=scope:auth,type:feature
nx g @nx/react:lib feature-checkout --directory=libs/features --tags=scope:checkout,type:feature
nx g @nx/react:lib feature-catalog --directory=libs/features --tags=scope:catalog,type:feature
# Run tests for all features
nx run-many -t test --projects=tag:type:featureLibrary Dependencies
// project.json for web-app
{
"targets": {
"build": {
"dependsOn": [
{ "projects": ["shared-ui"], "target": "build" }
]
}
}
}TypeScript Packages Reference
TypeScript Library Setup
Create Buildable Library
# Basic buildable library
nx g @nx/js:lib utils --buildable
# With directory
nx g @nx/js:lib date-fns --directory=libs/shared/utils
# With import path (publishable)
nx g @nx/js:lib logger --importPath=@myorg/loggerPublishable Package
# Publishable library
nx g @nx/js:lib my-package --publishable --importPath=@myorg/my-package
# With version configuration
nx g @nx/js:lib my-package --publishable --importPath=@myorg/my-packagePackage Configuration
Buildable Library package.json
For buildable libraries, configure package.json with proper exports:
{
"name": "@acme/pkg1",
"version": "0.0.1",
"type": "commonjs",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
}
}project.json for Buildable Lib
{
"name": "utils",
"projectType": "library",
"sourceRoot": "libs/utils/src",
"targets": {
"build": {
"executor": "@nx/js:tsc",
"outputs": ["{workspaceRoot}/dist/libs/utils"],
"options": {
"assets": ["libs/utils/*.md"],
"main": "libs/utils/src/index.ts",
"tsConfig": "libs/utils/tsconfig.lib.json"
}
},
"test": {
"executor": "@nx/jest:jest"
},
"lint": {
"executor": "@nx/linter:eslint"
}
}
}Non-Buildable Library
For libraries that don't need compilation (consumed via TS paths):
{
"name": "utils",
"projectType": "library",
"sourceRoot": "libs/utils/src",
"targets": {
"lint": {
"executor": "@nx/linter:eslint"
},
"test": {
"executor": "@nx/jest:jest"
}
}
}TypeScript Config
tsconfig.base.json
Root TypeScript configuration with path mappings:
{
"compileOnSave": false,
"compilerOptions": {
"rootDir": ".",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"lib": ["ES2022"],
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"resolveJsonModule": true
},
"exclude": ["node_modules", "tmp"]
}Library tsconfig.lib.json
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "../../dist/libs/utils",
"declaration": true,
"types": ["node"]
},
"include": ["**/*.ts"],
"exclude": ["**/*.spec.ts", "**/*.test.ts"]
}Path Aliases
Using Import Path
# Create library with import path
nx g @nx/js:lib logger --importPath=@myorg/loggerUsage:
// apps/web-app/src/app/app.ts
import { Logger } from '@myorg/logger';TS Path Mapping
Manual path mapping in tsconfig.base.json:
{
"compilerOptions": {
"paths": {
"@myorg/utils": ["libs/utils/src/index.ts"],
"@myorg/ui": ["libs/ui/src/index.ts"]
}
}
}Publishing Packages
Nx Release Commands
# Version all projects
nx release version --version=1.0.0
# Version specific projects
nx release version --projects=my-lib --version=1.2.3
# Create changelog
nx release changelog
# Publish to npm
nx release publishGitHub Actions Docker Publishing
name: Docker Publish
on:
push:
branches: [main]
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 20
- name: Install dependencies
run: npm ci
- name: Build applications
run: npx nx run-many -t build
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_TOKEN }}
- name: Build and tag Docker images
run: npx nx release version --dockerVersionScheme=production
- name: Publish Docker images
run: npx nx release publishTesting TypeScript Packages
Vitest
# Library with Vitest
nx g @nx/js:lib my-lib --unitTestRunner=vitest
# Run tests
nx test my-lib
# Watch mode
nx test my-lib --watchJest
# Library with Jest
nx g @nx/js:lib my-lib --unitTestRunner=jest
# Run tests
nx test my-lib
# Coverage
nx test my-lib --coverageExample Test
// libs/utils/src/lib/utils.spec.ts
import { formatDate } from './utils';
describe('formatDate', () => {
it('should format date correctly', () => {
const date = new Date('2024-01-01');
expect(formatDate(date)).toBe('2024-01-01');
});
});Common Patterns
Shared Utilities Library
# Create utilities library
nx g @nx/js:lib utils --directory=libs/shared
# Add utility functions
# libs/shared/utils/src/lib/date.ts
export function formatDate(date: Date): string {
return date.toISOString().split('T')[0];
}
// libs/shared/utils/src/lib/string.ts
export function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// libs/shared/utils/src/index.ts
export * from './lib/date';
export * from './lib/string';Type Definitions Library
# Create types library
nx g @nx/js:lib types --directory=libs/shared
// libs/shared/types/src/index.ts
export interface User {
id: string;
email: string;
name: string;
}
export interface ApiResponse<T> {
data: T;
message: string;
}Constants Library
nx g @nx/js:lib constants --directory=libs/shared
// libs/shared/constants/src/index.ts
export const API_URL = 'https://api.example.com';
export const MAX_RETRY_ATTEMPTS = 3;
export const TIMEOUT_MS = 5000;Multi-Package Monorepo
# Create multiple packages
nx g @nx/js:lib pkg1 --importPath=@myorg/pkg1
nx g @nx/js:lib pkg2 --importPath=@myorg/pkg2
nx g @nx/js:lib pkg3 --importPath=@myorg/pkg3
# Build all packages
nx run-many -t build --projects=pkg1,pkg2,pkg3
# Test all packages
nx run-many -t test --projects=pkg*Dependencies Between Packages
Local Dependencies
// libs/pkg2/package.json
{
"name": "@myorg/pkg2",
"dependencies": {
"@myorg/pkg1": "*"
}
}// libs/pkg2/project.json
{
"targets": {
"build": {
"dependsOn": ["pkg1^build"]
}
}
}Import from Local Package
// libs/pkg2/src/index.ts
import { something } from '@myorg/pkg1';
export function useSomething() {
return something();
}tsconfig Paths Generator
Nx automatically generates tsconfig.base.json paths based on project configuration.
To manually regenerate:
nx g @nx/js:ts-configRelated skills
Forks & variants (1)
Nx Monorepo has 1 known copy in the catalog totaling 22 installs. They canonicalize to this original listing.
- giuseppe-trisciuoglio - 22 installs
How it compares
Pick nx-monorepo for Nx-specific task graphs and cache tuning; use generic monorepo docs when not on the Nx toolchain.
FAQ
What does nx-monorepo do?
Provides comprehensive Nx monorepo management guidance for TypeScript/JavaScript projects. Use when creating Nx workspaces, generating apps/libraries/components, running affected commands, setting up
When should I use nx-monorepo?
During build backend work for backend & apis.
Is nx-monorepo safe to install?
Review the Security Audits panel on this listing before production use.