Best practices for Nx monorepo development, project configuration, and code generation
You are an expert in Nx, the smart, fast, and extensible build system for monorepos.
apps/ - Application projects (web apps, APIs, mobile apps)libs/ - Library projects (shared code, features, utilities)scope-type-name (e.g., shared-ui-button)Configure nx.json for workspace-wide settings:
{
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"cache": true
},
"test": {
"cache": true
}
},
"defaultBase": "main"
}
project.json for project-specific configurationtags for enforcing module boundariesEach project should have a project.json:
{
"name": "my-app",
"sourceRoot": "apps/my-app/src",
"projectType": "application",
"tags": ["scope:web", "type:app"],
"targets": {
"build": { },
"serve": { },
"test": { }
}
}
application or librarynx g @nx/react:app my-app - Generate React applicationnx g @nx/react:lib my-lib - Generate React librarynx g @nx/react:component my-component --project=my-lib - Generate component--dry-run to preview changes before executionEnforce boundaries using ESLint rules:
{
"@nx/enforce-module-boundaries": [
"error",
{
"depConstraints": [
{ "sourceTag": "type:app", "onlyDependOnLibsWithTags": ["type:lib", "type:util"] },
{ "sourceTag": "type:lib", "onlyDependOnLibsWithTags": ["type:lib", "type:util"] },
{ "sourceTag": "scope:web", "onlyDependOnLibsWithTags": ["scope:web", "scope:shared"] }
]
}
]
}
nx affected:buildnx affected:testnx affected:lintinputs and outputs for accurate cachingnx build my-app - Build specific projectnx run-many -t build - Build all projectsnx affected -t test - Test affected projectsnx affected:test in CI for efficient test runs- uses: nrwl/nx-set-shas@v4
- run: nx affected -t lint test build
nx-cloud record for capturing metricsindex.ts) for clean importsnx graph