Referensi cepat Nx monorepo. Workspace setup, generators, executors, caching, affected commands, dan task pipeline. Perfect buat developer TypeScript yang kelola multiple apps dan libs.
Login atau daftar akun gratis untuk membaca cheat sheet ini.
Nx adalah build system smart yang mengelola monorepo. Dia melacak dependency graph antar projects, meng-cache task results, dan menjalankan only what perlu berubah. Berikut konsep inti yang harus kamu pahami.
| Concept | Description |
|---|---|
| Workspace | Root monorepo yang berisi semua apps dan libs |
| Project | App atau library di dalam workspace |
| Target | Task yang bisa dijalankan (build, test, lint, serve) |
| Executor | Implementasi dari sebuah target (bagaimana task dijalankan) |
| Generator | Scaffolding tool untuk create atau modify code |
| Plugin | Paket Nx yang menyediakan executors, generators, dan preset |
| Task Graph | Dependency graph antar targets yang dipakai untuk parallel execution |
Bikin monorepo baru dengan Nx. Pilih preset berdasarkan kebutuhan project kamu.
# Bikin workspace baru (interactive)
npx create-nx-workspace@latest my-org
# Dengan preset spesifik
npx create-nx-workspace@latest my-org --preset=apps
# Preset yang tersedia:
# apps - Empty workspace dengan packages folder
# ts - Empty TypeScript workspace
# react - React app dengan Vite
# next - Next.js app
# node - Node app dengan Express/Fastify
# npm - Publishable library
# react-native - React Native appStruktur folder yang dihasilkan:
my-org/
apps/ # Aplikasi yang bisa deploy
web-app/
api-server/
libs/ # Shared libraries
shared-utils/
ui-components/
nx.json # Konfigurasi global Nx
package.json
tsconfig.base.jsonFile konfigurasi utama Nx. Di sini kamu atur caching, task pipeline, dan plugin defaults.
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"defaultBase": "main",
"nxCloudAccessToken": "",
"cache"
Named inputs memungkinkan kamu definisikan set of files yang menentukan cache key untuk task. Ini inti dari caching yang akurat.
| Input | Scope |
|---|---|
{projectRoot} | Path ke project saat ini |
{workspaceRoot} | Path ke root workspace |
{projectName} | Nama project |
{plugin} | Output dari plugin |
Setiap project bisa punya project.json yang mendefinisikan targets. Ini lebih granular daripada targetDefaults di nx.json.
{
"$schema": "../node_modules/nx/schemas/project-schema.json",
"name": "web-app",
"$schema":
Perintah-perintah Nx yang paling sering kamu pakai sehari-hari.
# Run target untuk project spesifik
nx build web-app
nx serve web-app
nx test web-app
nx lint web-app
# Run target untuk semua projects
nx run-many --target=build
nx run-many --target=test --parallel=5
Generators bikin boilerplate secara otomatis. Ini menghemat banyak waktu setup.
# Generate app
nx g @nx/node:app api-server
nx g @nx/react:app dashboard
nx g @nx/next:app marketing-site
# Generate library
nx g @nx/js:lib shared-utils
nx g @nx/react:lib
Setelah app atau lib ada, kamu bisa generate komponen, services, dan modul di dalamnya.
# React component
nx g @nx/react:component button --project=ui-components
# Node service
nx g @nx/node:lib auth-service --directory=libs/services
# TypeScript interface generator
nx g @nx/workspace:tsdoc
# Setup Storybook untuk library
nx g @nx/react:storybook-configuration ui-componentsTags memungkinkan kamu enforce boundaries antar projects. Misalnya, frontend app gak boleh import dari backend service.
// apps/web-app/project.json
{
"tags": ["scope:frontend", "type:app"]
}
// libs/api-types/project.json
{
"tags": ["scope:shared", "type:types"]
}
// libs/api-server/project.json
{
"tags": ["scope:backend"
// .eslintrc.json
{
"rules": {
"@nx/enforce-module-boundaries": [
"error",
{
"enforceBuildableLibDependency": true,
"allow": [],
"depConstraints": [
Nx cache task output berdasarkan input hash. Kalau input gak berubah, Nx skip task dan restore dari cache.
# Force skip cache
nx build web-app --skip-nx-cache
# Disable cache via env
NX_DAEMON=false nx build web-app
# Cache directory default: .nx/cache atau node_modules/.cache/nx| Cache Flag | Effect |
|---|---|
--skip-nx-cache | Selalu jalankan task ulang |
--verbose | Print detail runtime info |
--parallel=N | Run N tasks secara bersamaan |
Cara kerja cache key: Nx hash semua input files, environment variables, command args, dan dependency outputs. Kalau hash cocok dengan entry di cache, output dan terminal output langsung di-restore.
Affected commands hanya menjalankan task untuk projects yang terkena perubahan. Ini powerful untuk CI/CD biar build jadi cepat.
# Affected by changes vs main branch
nx affected --target=build
nx affected --target=test
nx affected --target=lint
# Print projects yang affected (dry run)
nx affected --target=build --print-affected
# Basis branch spesifik
nx affected --target=build
| Mode | Description |
|---|---|
--base | Branch, tag, atau commit sebagai baseline |
--head | Perubahan di mana yang dihitung (default HEAD) |
--uncommitted | Bandingkan dengan working tree |
--unpushed | Bandingkan dengan origin |
Task pipeline menjelaskan dependencies antar targets. Property dependsOn mengontrol urutan eksekusi.
{
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": ["production", "^production"]
},
"test": {
"dependsOn": ["build"]
}
}
}Arti dari prefix ^:
| Syntax | Meaning |
|---|---|
build | Jalankan target build dari project yang sama dulu |
^build | Jalankan target build dari semua dependency project dulu |
^production | Gunakan named input production dari dependency |
Contoh pipeline real: kalau api-server bergantung pada shared-utils, maka saat kamu build api-server, Nx otomatis build shared-utils lebih dulu karena ^build.
Executor adalah function yang menjalankan task. Beberapa executor populer dari plugin resmi:
| Executor | Plugin | Description |
|---|---|---|
@nx/webpack:webpack | @nx/web | Build dengan Webpack |
@nx/vite:build | @nx/vite | Build dengan Vite |
@nx/jest:jest | @nx/jest | Run Jest tests |
@nx/eslint:lint | @nx/eslint | Lint dengan ESLint |
@nx/rollup:rollup | @nx/rollup | Build library dengan Rollup |
@nx/esbuild:esbuild | @nx/esbuild | Build cepat dengan esbuild |
@nx/js:tsc | @nx/js | Compile dengan tsc (untuk library) |
Kamu bisa bikin executor sendiri kalau kebutuhan spesifik.
// libs/my-plugin/src/executors/hello.executor.json
{
"$schema": "https://json-schema.org/schema",
"version": 2,
"title": "Hello Executor",
"description": "Prints hello message",
"type": "object",
"properties"
// libs/my-plugin/src/executors/hello/hello.impl.ts
import { ExecutorContext } from '@nx/devkit';
export interface HelloExecutorSchema {
name: string;
}
export default async function runExecutor(
options
Generator bikin code scaffolding. Kamu bisa bikin generator custom untuk patterns yang sering diulang di tim.
// libs/my-plugin/src/generators/my-generator/generator.ts
import {
Tree,
formatFiles,
generateFiles,
joinPathFragments,
names,
} from '@nx/devkit';
export interface MyGeneratorSchema {
name
// Jalankan generator
// nx g @my-org/my-plugin:my-generator --name=my-featureNx daemon menjalankan Nx server di background biar startup lebih cepat. Cocok untuk project besar.
# Disable daemon untuk command tertentu
NX_DAEMON=false nx build web-app
# Stop daemon
nx daemon --stop
# Lihat daemon status
nx daemon| Env Variable | Effect |
|---|---|
NX_DAEMON=false | Disable daemon |
NX_CACHE_PROJECT_GRAPH=false | Re-compute graph tiap kali |
NX_DAEMON_LOG_LEVEL=debug | Verbose daemon logs |
| Feature | Buildable | Non-Buildable |
|---|---|---|
| Compile output | Ya, ke dist/ | Tidak |
| Bisa publish ke npm | Ya | Tidak |
| Lebih cepat di dev | Tidak (perlu rebuild) | Ya |
| Cocok untuk | Library yang di-publish | Internal shared code |
| Setup | --buildable flag | Default |
Nx otomatis maintain path mappings di tsconfig.base.json supaya import antar projects gampang.
// tsconfig.base.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@my-org/shared-utils": ["libs/shared-utils/src/index.ts"],
"@my-org/ui-components": ["libs/ui-components/src/index.ts"],
"@my-org/api-types": ["libs/api-types/src/index.ts"]
}
// apps/web-app/src/main.ts
import { formatDate } from '@my-org/shared-utils';
import { Button } from '@my-org/ui-components';Nx Cloud bikin remote caching dan distributed task execution antar machines. Ini mempercepat CI signifikan.
# Connect workspace ke Nx Cloud
nx connect
# Atau via CLI saat create workspace
npx create-nx-workspace@latest my-org --nx-cloud
# Distributed Task Execution (DTE) di CI
npx nx-cloud start-ci-run --distribute-on="3 linux-medium-js"
nx affected --target=build
nx affected --target=test
npx| Feature | Description |
|---|---|
| Remote Cache | Share cache antar machines |
| DTE | Distribusi task ke multiple agents |
| Nx Replay | Replay flaky tasks |
| Nx Agents | Ephemeral CI agents |
# Migrate ke versi Nx terbaru
nx migrate latest
# Apply migrations
nx migrate --run-migrations=migrations.json
# Fix configuration issues
nx repairNx versi modern (15.8+) memperkenalkan "Project Crystal" dimana plugin otomatis infer targets dari package.json scripts dan config files. Ini berarti kamu gak perlu tulis project.json manual untuk banyak kasus.
// apps/web-app/package.json
{
"name": "web-app",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"nx": {
"tags": ["scope:frontend", "type:app"]
}
}Dengan plugin @nx/vite aktif, target build dan dev otomatis terdeteksi. Property nx di package.json jadi tempat project-specific config.
Nx graph visualisasi dependency antar projects. Sangat berguna untuk memahami struktur monorepo besar.
# Buka graph di browser
nx graph
# Focus ke project tertentu
nx graph --focus=web-app
# Filter berdasarkan target
nx graph --targets=build
# Export sebagai file
nx graph --file=graph.json
nx graph --file=graph.html| Term | Definition |
|---|---|
| Affected | Projects yang berubah relatif terhadap baseline |
| Buildable Library | Library yang di-compile ke output terpisah |
| Cache | Penyimpanan output task untuk reuse |
| Daemon | Background process untuk startup cepat |
| DTE | Distributed Task Execution, split task ke banyak agents |
| Executor | Implementasi bagaimana target dijalankan |
| Generator | Tool scaffolding untuk create atau modify code |
| Named Input | Set of files yang menentukan cache key |
| Plugin | Paket yang berisi executors, generators, dan preset |
| Project | App atau library di workspace |
| Target | Task yang runnable (build, test, lint) |
| Task Graph | Dependency graph antar targets |
| Workspace | Root monorepo yang berisi semua projects |
Happy building dengan Nx! 🏗️