references/advanced.md
# Advanced Nx Reference
## Task Orchestration
### Dependencies
Define task dependencies in `project.json`:
```json
{
"targets": {
"build": {
"dependsOn": [
{ "projects": ["shared-ui"], "target": "build" },
{ "projects": ["api"], "target": "build", "params": "ignore" }
]
}
}
}
```
### Target Defaults
Configure default behavior in `nx.json`:
```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/cache
```
### Bypass Cache
```bash
# Single run
nx run my-app:build --skip-nx-cache
# Reset cache
nx reset
```
### Remote Cache
```bash
# Install Azure cache
nx add @nx/azure-cache
# Generates activation key saved to .nx/key/key.ini
# Set as environment variable: NX_KEY
```
Configuration in `nx.json`:
```json
{
"nxCloudId": "your-workspace-id",
"nxCloudUrl": "https://cloud.nx.app"
}
```
## Affected Commands
### Base Configuration
```yaml
# GitHub Actions
- uses: nrwl/nx-set-shas@v4
with:
main-branch-name: 'main'
```
### Affected Patterns
```bash
# 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=5
```
## Project Graph
### Visualize Graph
```bash
# 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 --watch
```
### Query Projects
```bash
# 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 --affected
```
## Module Federation
### Micro-Frontends Architecture
```
host-app (Shell)
├── remote1 (Checkout)
├── remote2 (Catalog)
└── remote3 (User Profile)
```
### Setup Host
```bash
nx g @nx/react:host shell-app
```
### Setup Remote
```bash
nx g @nx/react:remote checkout --name=remote1 --port=4201
```
### Add Remote to Host
```bash
nx g @nx/react:remote-configuration shell-app \
--remote=remote1 \
--port=4201 \
--type=module
```
### Module Federation Config
```typescript
// 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
```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`:
```json
{
"workspaceLayout": {
"appsDir": "packages",
"libsDir": "packages"
}
}
```
## Plugins
### Use Plugins
```json
// nx.json
{
"plugins": [
{
"plugin": "@nx/react"
},
{
"plugin": "@nx/js",
"options": {
"buildTargetName": "build",
"testTargetName": "test"
}
}
]
}
```
### Custom Plugin Options
```json
{
"plugins": [
{
"plugin": "@nx/dotnet",
"options": {
"build": {
"targetName": "compile",
"configurations": {
"production": { "optimization": true }
}
},
"test": {
"targetName": "unit-test",
"dependsOn": ["build"]
}
}
}
]
}
```
## Generators
### Custom Workspace Generator
```bash
# Create generator
nx g workspace-generator my-generator
# Run generator
nx workspace-generator my-generator
```
### Sync Generator
Run automatically after `npm install` / `yarn`:
```bash
nx g @nx/js:lib my-lib --sync
```
## Release
### Version Projects
```bash
# 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 version
```
### Publish
```bash
# Dry run
nx release publish --dry-run
# Publish
nx release publish
# With first release
nx release publish --firstRelease
```
### Changelog
```bash
# Generate changelog
nx release changelog
# For specific version
nx release changelog --version=1.0.0
```
## Conformance
### Install Conformance
```bash
nx add @nx/conformance
```
### Configuration
```json
// nx.json
{
"conformance": {
"rules": [
{
"rule": "@nx/conformance/enforce-project-boundaries",
"options": {},
"projects": ["*"]
}
]
}
}
```
## Owners
### GitHub CODEOWNERS
```json
// 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
```json
// nx.json
{
"targetDefaults": {
"build": {
"parallel": true,
"maxParallel": 4
}
}
}
```
### Cache Encryption
```json
// nx.json
{
"encryptionKey": "your-encryption-key"
}
```
## Agent Configuration (Nx Cloud)
### Launch Templates
```yaml
// .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
```bash
# 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
```bash
# 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-cache
```
### Common Issues
**"Project X not found"**
- Check project name in `project.json` or `workspace.json`
**"Circular dependency detected"**
- Check `dependsOn` configuration
- Use `nx graph` to visualize dependencies
**Cache not working**
- Check `outputs` paths in `project.json`
- Verify cache directory permissions
references/basics.md
# Nx Basics Reference
## Workspace Creation
### New Workspace with Presets
```bash
npx create-nx-workspace@latest
```
Interactive 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`:
```bash
nx@latest init
```
For npm workspace projects, create `package.json` first:
```json
{
"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.json
```
### Configuration Files
**nx.json** - Workspace-level configuration:
```json
{
"namedInputs": {
"default": ["{projectRoot}/**/*"],
"production": [
"default",
"!{projectRoot}/**/*.spec.ts",
"!{projectRoot}/**/*.test.ts"
]
},
"targetDefaults": {
"build": {
"cache": true,
"dependsOn": ["^build"]
}
}
}
```
**project.json** - Project-level configuration (per project):
```json
{
"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
```bash
# 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=false
```
### Project Operations
```bash
# 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 --json
```
### Generator Shortcuts
```bash
# g = generate
nx g <collection>:<generator>
# Examples
nx g @nx/react:component my-component
nx g @nx/js:lib shared-utils
```
## Installation
### Install Nx Plugins
```bash
# 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/js
```
Ensure plugin version matches Nx version.
### Global Installation (Optional)
```bash
# 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 graph
```
## Common Workflows
### New Feature Development
```bash
# 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 graph
```
### Debugging Task Execution
```bash
# 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-cache
```
references/ci-cd.md
# CI/CD Reference
## GitHub Actions
### Basic CI Workflow
```yaml
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
```yaml
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
```yaml
- run: npx nx-cloud start-ci-run --distribute-on="3 linux-medium-js" --stop-agents-after="build"
```
## CircleCI
### Basic Configuration
```yaml
// .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:
- main
```
### With Nx Cloud DTE
```yaml
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]
- main
```
## Azure Pipelines
### Basic Configuration
```yaml
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=ci
```
## Jenkins
### Declarative Pipeline
```groovy
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
```yaml
// .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_requests
```
### With Nx Cloud DTE
```yaml
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: *agent
```
## Bitbucket Pipelines
### Basic Configuration
```yaml
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/main
```
## Docker Publishing
### GitHub Actions Docker Workflow
```yaml
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 publish
```
## Affected Commands in CI
### Base Branch Configuration
```yaml
- uses: nrwl/nx-set-shas@v4
with:
main-branch-name: 'main'
```
### Affected Command Patterns
```bash
# 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=5
```
## Nx Cloud Setup
### Connect Workspace
```bash
nx connect
```
### Self-Healing CI
```yaml
- run: npx nx fix-ci
if: always()
```
### Record Commands
```bash
# Record specific command
npx nx-cloud record -- nx format:check
# Record with environment variables
npx nx-cloud record --env=MY_VAR=value -- nx test
```
## Cache Configuration
### GitHub Actions Cache
```yaml
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
```
### Nx Remote Cache
```bash
# Install Azure cache
nx add @nx/azure-cache
# Install AWS cache (custom setup required)
# See Nx docs for S3-based caching
```
## CI 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
references/generators.md
# Nx Generators Reference
## Application Generators
### React Application
```bash
# 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=scss
```
### Next.js Application
```bash
# 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.json
```
### NestJS Application
```bash
# 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/api
```
### Express Application
```bash
nx g @nx/node:app my-express-api --framework=express
```
## Library Generators
### React Library
```bash
# 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-ui
```
### TypeScript/JavaScript Library
```bash
# 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-fns
```
### Node Library
```bash
nx g @nx/node:lib my-node-lib
```
## Component Generators
### React Component
```bash
# 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 --skipTests
```
### Angular Component
```bash
nx g @nx/angular:component header --project=my-app
```
## Service/Class Generators
### NestJS Services
```bash
# 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-api
```
### TypeScript Interfaces/Classes
```bash
# Interface
nx g @nx/js:interface user --project=utils
# Class
nx g @nx/js:class validator --project=utils
```
## Specialized Generators
### Module Federation
```bash
# 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=4201
```
### Storybook Setup
```bash
# For React library
nx g @nx/react:storybook-configuration shared-ui
# For Angular library
nx g @nx/angular:storybook-configuration shared-ui
```
### Tailwind CSS
```bash
# 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.scss
```
### Testing Setup
```bash
# 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-lib
```
## Generator 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):
```bash
nx g lib my-lib # apps/my-lib
nx g lib my-lib --directory=libs/shared
# libs/shared/my-lib
```
**Derived** (legacy):
```bash
nx g lib my-lib # Creates directory based on workspace config
```
## Workflow Examples
### Create New Feature Library
```bash
# 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:build
```
### Add E2E Tests to App
```bash
# Add Cypress to existing app
nx g @nx/cypress:cypress-project web-app-e2e --bundler=vite --project=web-app
```
### Migrate Component
```bash
# Move component to library
nx g @nx/react:component button --project=shared-ui --export --flat
```
references/nestjs.md
# NestJS Backend Reference
## Create NestJS Application
### Basic Setup
```bash
# 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/api
```
### NestJS Library
```bash
# NestJS library
nx g @nx/nest:lib auth --directory=libs/backend
# With import path
nx g @nx/nest:lib shared-backend --importPath=@myorg/shared-backend
```
## Project Configuration
### project.json for NestJS App
```json
{
"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`:
```javascript
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)
```bash
# 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=products
```
### Individual Generators
```bash
# 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-api
```
### Subdirectory Structure
```bash
# Create in subdirectory
nx g @nx/nest:controller admin/users --project=my-api
# Creates: apps/api/src/admin/users/users.controller.ts
```
## Swagger Integration
### Setup Swagger
```typescript
// 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
```typescript
// 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
```bash
# Run tests
nx test my-api
# Watch mode
nx test my-api --watch
# Coverage
nx test my-api --coverage
```
### E2E Tests
```bash
# Add E2E to NestJS app
nx g @nx/jest:app my-api-e2e --project=my-api
# Run E2E
nx e2e my-api-e2e
```
### Example Test
```typescript
// 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
```bash
# Create microservice app
nx g @nx/node:app auth-microservice --framework=nest
```
Configuration:
```typescript
// 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
```bash
# 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
```typescript
// 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
```bash
# Install TypeORM
npm install @nestjs/typeorm typeorm
```
Configuration:
```typescript
// 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
```bash
# Development with watch
nx serve my-api
# Production build
nx build my-api --configuration=production
# Run production
node dist/apps/api/main.js
```
## Common Tasks
### Add Validation
```bash
npm install class-validator class-transformer
```
```typescript
// 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
```bash
nx g @nx/nest:guard auth --project=my-api
```
### Add Interceptor
```bash
nx g @nx/nest:interceptor logging --project=my-api
```
### Add Pipe
```bash
nx g @nx/nest:pipe validation --project=my-api
```
references/react.md
# React / Next.js / Expo Reference
## React Applications
### Create React App
```bash
# 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 --standalone
```
### React Library
```bash
# 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/ui
```
### React Component Generator
```bash
# 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 \
--flat
```
### Project Configuration
```json
{
"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
```bash
# 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/next
```
### Next.js Project Configuration
```json
{
"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
```bash
# Development
nx serve my-next-app
# Production build serve
nx start my-next-app
nx serve my-next-app --prod
```
## Expo / React Native
### Create Expo App
```bash
nx g @nx/expo:app my-mobile-app
```
### Serve Expo App
```bash
# Web
nx start my-mobile-app --web
# iOS
nx start my-mobile-app --ios
# Android
nx start my-mobile-app --android
```
## Module Federation
### Micro-Frontend Setup
```bash
# 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=module
```
### Module 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.tsx
```
Load remote module:
```tsx
// 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
```bash
# 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.scss
```
### Nx React Webpack Plugin
Configure for custom webpack:
```javascript
const { NxReactWebpackPlugin } = require('@nx/react/webpack-plugin');
module.exports = {
plugins: [
new NxReactWebpackPlugin({
svgr: false, // Disable SVGR
}),
],
};
```
## Storybook
### Setup Storybook for Library
```bash
# React library
nx g @nx/react:storybook-configuration shared-ui
# Run Storybook
nx storybook shared-ui
# Build Storybook
nx build-storybook shared-ui
```
### Storybook Composition
For composed Storybooks (multiple libraries):
```bash
# Start individual instances
nx storybook ui-lib-1 # Port: 4400
nx storybook ui-lib-2 # Port: 4401
```
## Testing
### Vitest (Recommended for Vite)
```bash
# 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 --coverage
```
### Component Testing
```bash
# Component with test
nx g @nx/react:component Button --project=shared-ui
```
Test example:
```tsx
// 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
```bash
# 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 --watch
```
## Common Patterns
### Shared UI Library
```bash
# 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
```bash
# 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:feature
```
### Library Dependencies
```json
// project.json for web-app
{
"targets": {
"build": {
"dependsOn": [
{ "projects": ["shared-ui"], "target": "build" }
]
}
}
}
```
references/typescript.md
# TypeScript Packages Reference
## TypeScript Library Setup
### Create Buildable Library
```bash
# 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/logger
```
### Publishable Package
```bash
# 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-package
```
## Package Configuration
### Buildable Library package.json
For buildable libraries, configure `package.json` with proper exports:
```json
{
"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
```json
{
"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):
```json
{
"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:
```json
{
"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
```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
```bash
# Create library with import path
nx g @nx/js:lib logger --importPath=@myorg/logger
```
Usage:
```typescript
// apps/web-app/src/app/app.ts
import { Logger } from '@myorg/logger';
```
### TS Path Mapping
Manual path mapping in `tsconfig.base.json`:
```json
{
"compilerOptions": {
"paths": {
"@myorg/utils": ["libs/utils/src/index.ts"],
"@myorg/ui": ["libs/ui/src/index.ts"]
}
}
}
```
## Publishing Packages
### Nx Release Commands
```bash
# 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 publish
```
### GitHub Actions Docker Publishing
```yaml
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 publish
```
## Testing TypeScript Packages
### Vitest
```bash
# Library with Vitest
nx g @nx/js:lib my-lib --unitTestRunner=vitest
# Run tests
nx test my-lib
# Watch mode
nx test my-lib --watch
```
### Jest
```bash
# Library with Jest
nx g @nx/js:lib my-lib --unitTestRunner=jest
# Run tests
nx test my-lib
# Coverage
nx test my-lib --coverage
```
### Example Test
```typescript
// 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
```bash
# 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
```bash
# 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
```bash
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
```bash
# 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
```json
// libs/pkg2/package.json
{
"name": "@myorg/pkg2",
"dependencies": {
"@myorg/pkg1": "*"
}
}
```
```json
// libs/pkg2/project.json
{
"targets": {
"build": {
"dependsOn": ["pkg1^build"]
}
}
}
```
### Import from Local Package
```typescript
// 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:
```bash
nx g @nx/js:ts-config
```
SKILL.md
---
name: nx-monorepo
description: Provides comprehensive Nx monorepo management guidance for TypeScript/JavaScript projects. Use when creating Nx workspaces, generating apps/libraries/components, running affected commands, setting up CI/CD, configuring Module Federation, or implementing NestJS backends within Nx
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---
# 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:**
```bash
npx create-nx-workspace@latest
```
Follow prompts to select preset (Integrated, Standalone, Package-based) and framework stack.
2. **Initialize Nx in an existing project:**
```bash
nx@latest init
```
3. **Create with specific preset (non-interactive):**
```bash
npx create-nx-workspace@latest my-workspace --preset=react
```
**Verify:** `nx show projects` lists the new workspace projects
### Project Generation
1. **Generate a React application:**
```bash
nx g @nx/react:app my-app
```
2. **Generate a library:**
```bash
# React library
nx g @nx/react:lib my-lib
# TypeScript library
nx g @nx/js:lib my-util
```
**Verify:** `nx show projects` lists the new lib
3. **Generate a component in lib:**
```bash
nx g @nx/react:component my-comp --project=my-lib
```
4. **Generate NestJS backend:**
```bash
nx g @nx/nest:app my-api
```
**Verify:** `nx show projects` lists `my-api` and `nx run my-api:build` succeeds
### Task Execution
1. **Run tasks for affected projects only:**
```bash
nx affected -t lint test build
```
2. **Run tasks across all projects:**
```bash
# 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=*-app
```
3. **Run specific target on single project:**
```bash
nx run my-app:build
```
4. **Visualize dependency graph:**
```bash
nx graph
```
### Project Configuration
Each project has a `project.json` defining targets, executor, and configurations:
```json
{
"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:**
```json
{
"targets": {
"build": {
"dependsOn": [
{ "projects": ["shared-ui"], "target": "build" }
]
}
}
}
```
2. **Use tags for organization:**
```json
{ "tags": ["type:ui", "scope:frontend", "platform:web"] }
```
### Module Federation (Nx 17+)
1. **Generate a remote (micro-frontend):**
```bash
nx g @nx/react:remote checkout --host=dashboard
```
2. **Generate a host:**
```bash
nx g @nx/react:host dashboard
```
### CI/CD Setup
Use affected commands in CI to only build/test changed projects:
```yaml
# .github/workflows/ci.yml
- run: npx nx affected -t lint --parallel
- run: npx nx affected -t test --parallel
- run: npx nx affected -t build --parallel
```
## Examples
### Example 1: Create New React Workspace
**Input:** "Create a new Nx workspace with React and TypeScript"
**Steps:**
```bash
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 app
- `libs/` directory for shared libraries
- `nx.json` with 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:**
```bash
nx affected -t test --base=main~1 --head=main
```
**Expected 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:**
```bash
# 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:**
```bash
# 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:serve
```
**Verify:** 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:**
```bash
# Show project graph
nx graph --focused=my-app
# Check implicit dependencies
nx show project my-app --json | grep implicitDependencies
```
**Solution:** 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 `workspaceLayout` boundaries in `nx.json`
- **Enable remote caching** with Nx Cloud for team productivity
- **Keep project.json simple** - use defaults from `nx.json` when 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/cache` can grow large; configure `cacheDirectory` in `nx.json` if needed
- **Circular dependencies** will cause build failures; use `nx graph` to 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](references/basics.md) |
| Generators (app, lib, component) | [references/generators.md](references/generators.md) |
| React, Next.js, Expo patterns | [references/react.md](references/react.md) |
| NestJS backend patterns | [references/nestjs.md](references/nestjs.md) |
| TypeScript packages | [references/typescript.md](references/typescript.md) |
| CI/CD (GitHub, CircleCI, etc.) | [references/ci-cd.md](references/ci-cd.md) |
| Caching, affected, advanced | [references/advanced.md](references/advanced.md) |