BelajarKoding Logobelajarkoding

Platform belajar web development Indonesia. Artikel, cheat sheets, roadmap, dan code challenges untuk developer Indonesia.

Navigasi

  • Artikel
  • Cheat Sheets
  • Roadmap
  • Challenges
  • Pricing
  • Search

Produk Lain

  • JagoHermes
  • KelasClaude
  • KilatKoding
  • BelajarVibeCoding
  • JualanKoding

Support

  • Privacy Policy
  • Terms of Service
  • Email

© 2026 BelajarKoding. All rights reserved.

Galih PratamaBagian dari ekosistem Galih Pratama
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade

Daftar Isi

Core ConceptsWorkspace Setupnx.json ConfigurationNamed Inputsproject.jsonCommon CommandsGenerate ProjectsGenerate Code Inside ProjectsTags dan EnforcementCachingAffected CommandsTask PipelineExecutorsCustom ExecutorGeneratorsNx DaemonBuildable vs Non-Buildable LibrariesTypeScript Path MappingNx CloudMigration dan UpdateProject CrystalNx GraphGlossary
NxMonorepoBuild ToolsTypeScript

Nx Cheat Sheet

Referensi cepat Nx monorepo. Workspace setup, generators, executors, caching, affected commands, dan task pipeline. Perfect buat developer TypeScript yang kelola multiple apps dan libs.

TypeScript10 min read1.988 kata
Silakan login atau daftar untuk membaca cheat sheet ini.

#Core Concepts

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.

ConceptDescription
WorkspaceRoot monorepo yang berisi semua apps dan libs
ProjectApp atau library di dalam workspace
TargetTask yang bisa dijalankan (build, test, lint, serve)
ExecutorImplementasi dari sebuah target (bagaimana task dijalankan)
GeneratorScaffolding tool untuk create atau modify code
PluginPaket Nx yang menyediakan executors, generators, dan preset
Task GraphDependency graph antar targets yang dipakai untuk parallel execution

#Workspace Setup

Bikin monorepo baru dengan Nx. Pilih preset berdasarkan kebutuhan project kamu.

bash
# 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 app

Struktur folder yang dihasilkan:

plaintext
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.json

#nx.json Configuration

File konfigurasi utama Nx. Di sini kamu atur caching, task pipeline, dan plugin defaults.

json
{
  "$schema": "./node_modules/nx/schemas/nx-schema.json",
  "defaultBase": "main",
  "nxCloudAccessToken": "",
  "cache": {
    "enabled": true,
    "path": ".nx/cache",
    "environmentActivation": {
      "preset": "nx"
    }
  },
  "namedInputs": {
    "default": [
      "{projectRoot}/**/*",
      "sharedGlobals"
    ],
    "sharedGlobals": [
      "{workspaceRoot}/tsconfig.base.json",
      "{workspaceRoot}/package.json"
    ],
    "production": [
      "default",
      "!{projectRoot}/**/*.spec.ts",
      "!{projectRoot}/.eslintrc.json"
    ]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production"],
      "cache": true
    },
    "test": {
      "inputs": ["default", "^production"],
      "cache": true
    },
    "lint": {
      "inputs": [
        "default",
        "{workspaceRoot}/.eslintrc.json"
      ],
      "cache": true
    }
  },
  "plugins": [
    {
      "plugin": "@nx/webpack/plugin",
      "options": {
        "buildTargetName": "build",
        "serveTargetName": "serve"
      }
    }
  ]
}

#Named Inputs

Named inputs memungkinkan kamu definisikan set of files yang menentukan cache key untuk task. Ini inti dari caching yang akurat.

InputScope
{projectRoot}Path ke project saat ini
{workspaceRoot}Path ke root workspace
{projectName}Nama project
{plugin}Output dari plugin

#project.json

Setiap project bisa punya project.json yang mendefinisikan targets. Ini lebih granular daripada targetDefaults di nx.json.

json
{
  "$schema": "../node_modules/nx/schemas/project-schema.json",
  "name": "web-app",
  "$schema": "../node_modules/nx/schemas/project-schema.json",
  "projectType": "application",
  "sourceRoot": "apps/web-app/src",
  "tags": ["scope:frontend", "type:app"],
  "targets": {
    "build": {
      "executor": "@nx/webpack:webpack",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/apps/web-app",
        "main": "apps/web-app/src/main.ts",
        "tsConfig": "apps/web-app/tsconfig.app.json",
        "assets": [
          "apps/web-app/src/favicon.ico",
          "apps/web-app/src/assets"
        ]
      },
      "configurations": {
        "production": {
          "optimization": true,
          "extractLicenses": true,
          "sourceMap": false
        },
        "development": {
          "extractLicenses": false,
          "sourceMap": true
        }
      },
      "defaultConfiguration": "production"
    },
    "serve": {
      "executor": "@nx/webpack:webpack",
      "options": {
        "buildTarget": "web-app:build",
        "devServer": {
          "port": 4200
        }
      }
    },
    "test": {
      "executor": "@nx/jest:jest",
      "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
      "options": {
        "jestConfig": "apps/web-app/jest.config.ts"
      }
    }
  }
}

#Common Commands

Perintah-perintah Nx yang paling sering kamu pakai sehari-hari.

bash
# 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
 
# Dengan filter
nx run-many --target=build --projects=web-app,api-server
 
# Run langsung tanpa prefix
nx serve web-app --port=3000
nx build web-app --configuration=development
 
# Lihat dependency graph
nx graph
 
# Lihat project details
nx show project web-app
 
# Reset cache dan daemon
nx reset

#Generate Projects

Generators bikin boilerplate secara otomatis. Ini menghemat banyak waktu setup.

bash
# 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 ui-components --directory=libs/ui
 
# Generate library yang publishable ke npm
nx g @nx/js:lib my-lib --publishable --importPath=@my-org/my-lib
 
# Move atau remove project
nx g @nx/workspace:move --projectName=old-name --destination=libs/new-name
nx g @nx/workspace:remove --projectName=old-name
 
# Convert project jadi buildable library
nx g @nx/js:setup-buildable --project=shared-utils

#Generate Code Inside Projects

Setelah app atau lib ada, kamu bisa generate komponen, services, dan modul di dalamnya.

bash
# 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-components

#Tags dan Enforcement

Tags memungkinkan kamu enforce boundaries antar projects. Misalnya, frontend app gak boleh import dari backend service.

jsonc
// 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", "type:service"]
}
jsonc
// .eslintrc.json
{
  "rules": {
    "@nx/enforce-module-boundaries": [
      "error",
      {
        "enforceBuildableLibDependency": true,
        "allow": [],
        "depConstraints": [
          {
            "sourceTag": "scope:frontend",
            "onlyDependOnLibsWithTags": ["scope:frontend", "scope:shared"]
          },
          {
            "sourceTag": "scope:backend",
            "onlyDependOnLibsWithTags": ["scope:backend", "scope:shared"]
          },
          {
            "sourceTag": "type:app",
            "onlyDependOnLibsWithTags": [
              "type:feature",
              "type:ui",
              "type:util",
              "type:data"
            ]
          }
        ]
      }
    ]
  }
}

#Caching

Nx cache task output berdasarkan input hash. Kalau input gak berubah, Nx skip task dan restore dari cache.

bash
# 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 FlagEffect
--skip-nx-cacheSelalu jalankan task ulang
--verbosePrint detail runtime info
--parallel=NRun 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

Affected commands hanya menjalankan task untuk projects yang terkena perubahan. Ini powerful untuk CI/CD biar build jadi cepat.

bash
# 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 --base=main --head=HEAD
 
# Basis tag atau commit
nx affected --target=build --base=v1.0.0
nx affected --target=test --base=origin/main
 
# Affected di CI (lebih akurat)
nx affected --target=build --base=$NX_BASE --head=$NX_HEAD
 
# Run affected dengan parallel
nx affected --target=test --parallel=3
ModeDescription
--baseBranch, tag, atau commit sebagai baseline
--headPerubahan di mana yang dihitung (default HEAD)
--uncommittedBandingkan dengan working tree
--unpushedBandingkan dengan origin

#Task Pipeline

Task pipeline menjelaskan dependencies antar targets. Property dependsOn mengontrol urutan eksekusi.

json
{
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production"]
    },
    "test": {
      "dependsOn": ["build"]
    }
  }
}

Arti dari prefix ^:

SyntaxMeaning
buildJalankan target build dari project yang sama dulu
^buildJalankan target build dari semua dependency project dulu
^productionGunakan 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.

#Executors

Executor adalah function yang menjalankan task. Beberapa executor populer dari plugin resmi:

ExecutorPluginDescription
@nx/webpack:webpack@nx/webBuild dengan Webpack
@nx/vite:build@nx/viteBuild dengan Vite
@nx/jest:jest@nx/jestRun Jest tests
@nx/eslint:lint@nx/eslintLint dengan ESLint
@nx/rollup:rollup@nx/rollupBuild library dengan Rollup
@nx/esbuild:esbuild@nx/esbuildBuild cepat dengan esbuild
@nx/js:tsc@nx/jsCompile dengan tsc (untuk library)

#Custom Executor

Kamu bisa bikin executor sendiri kalau kebutuhan spesifik.

jsonc
// 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": {
    "name": {
      "type": "string",
      "description": "Name to greet"
    }
  },
  "required": ["name"]
}
typescript
// 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: HelloExecutorSchema,
  context: ExecutorContext
) {
  console.log(`Hello, ${options.name}!`);
  console.log(`Project: ${context.projectName}`);
 
  return {
    success: true,
  };
}

#Generators

Generator bikin code scaffolding. Kamu bisa bikin generator custom untuk patterns yang sering diulang di tim.

typescript
// libs/my-plugin/src/generators/my-generator/generator.ts
import {
  Tree,
  formatFiles,
  generateFiles,
  joinPathFragments,
  names,
} from '@nx/devkit';
 
export interface MyGeneratorSchema {
  name: string;
}
 
export default async function (tree: Tree, options: MyGeneratorSchema) {
  const { name, className, fileName } = names(options.name);
  const projectRoot = `libs/${fileName}`;
 
  generateFiles(
    tree,
    joinPathFragments(__dirname, 'files'),
    projectRoot,
    {
      name,
      className,
      fileName,
      tmpl: '', // hapus suffix .tmpl dari template files
    }
  );
 
  await formatFiles(tree);
}
typescript
// Jalankan generator
// nx g @my-org/my-plugin:my-generator --name=my-feature

#Nx Daemon

Nx daemon menjalankan Nx server di background biar startup lebih cepat. Cocok untuk project besar.

bash
# Disable daemon untuk command tertentu
NX_DAEMON=false nx build web-app
 
# Stop daemon
nx daemon --stop
 
# Lihat daemon status
nx daemon
Env VariableEffect
NX_DAEMON=falseDisable daemon
NX_CACHE_PROJECT_GRAPH=falseRe-compute graph tiap kali
NX_DAEMON_LOG_LEVEL=debugVerbose daemon logs

#Buildable vs Non-Buildable Libraries

FeatureBuildableNon-Buildable
Compile outputYa, ke dist/Tidak
Bisa publish ke npmYaTidak
Lebih cepat di devTidak (perlu rebuild)Ya
Cocok untukLibrary yang di-publishInternal shared code
Setup--buildable flagDefault

#TypeScript Path Mapping

Nx otomatis maintain path mappings di tsconfig.base.json supaya import antar projects gampang.

jsonc
// 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"]
    }
  }
}
typescript
// apps/web-app/src/main.ts
import { formatDate } from '@my-org/shared-utils';
import { Button } from '@my-org/ui-components';

#Nx Cloud

Nx Cloud bikin remote caching dan distributed task execution antar machines. Ini mempercepat CI signifikan.

bash
# 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 nx-cloud finish-ci-run
FeatureDescription
Remote CacheShare cache antar machines
DTEDistribusi task ke multiple agents
Nx ReplayReplay flaky tasks
Nx AgentsEphemeral CI agents

#Migration dan Update

bash
# Migrate ke versi Nx terbaru
nx migrate latest
 
# Apply migrations
nx migrate --run-migrations=migrations.json
 
# Fix configuration issues
nx repair

#Project Crystal

Nx 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.

jsonc
// 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

Nx graph visualisasi dependency antar projects. Sangat berguna untuk memahami struktur monorepo besar.

bash
# 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

#Glossary

TermDefinition
AffectedProjects yang berubah relatif terhadap baseline
Buildable LibraryLibrary yang di-compile ke output terpisah
CachePenyimpanan output task untuk reuse
DaemonBackground process untuk startup cepat
DTEDistributed Task Execution, split task ke banyak agents
ExecutorImplementasi bagaimana target dijalankan
GeneratorTool scaffolding untuk create atau modify code
Named InputSet of files yang menentukan cache key
PluginPaket yang berisi executors, generators, dan preset
ProjectApp atau library di workspace
TargetTask yang runnable (build, test, lint)
Task GraphDependency graph antar targets
WorkspaceRoot monorepo yang berisi semua projects

Happy building dengan Nx! 🏗️

Baca Cheat Sheet Lengkap

Login atau daftar akun gratis untuk membaca cheat sheet ini.

LoginDaftar Gratis
Share: