Nx Monorepo Seri 1: Pengenalan & Integrasi Spring Boot
Bagian 1 dari 5: Membangun Monorepo Enterprise-Grade dengan Nx
Pelajari cara setup monorepo modern menggunakan Nx dan mengintegrasikan aplikasi Spring Boot - arsitektur yang sama digunakan oleh Google, Facebook, dan tech giants lainnya.
Apa Itu Monorepo?
Monorepo (monolithic repository) adalah strategi pengembangan software dimana kode untuk berbagai proyek disimpan dalam satu repository. Alih-alih memiliki repository terpisah untuk setiap proyek, aplikasi, atau library, semuanya hidup bersama dalam satu codebase terpadu.
Karakteristik Utama
- Single Repository: Semua kode berada dalam satu Git repository
- Multiple Projects: Berisi berbagai aplikasi, service, dan library
- Shared Dependencies: Kode dan dependency umum dibagikan antar proyek
- Unified Versioning: Single source of truth untuk versi dan konfigurasi
- Atomic Commits: Perubahan di berbagai proyek bisa di-commit bersamaan
Contoh Struktur
my-company-monorepo/
โโโ apps/
โ โโโ web-app/ # React frontend
โ โโโ mobile-app/ # React Native app
โ โโโ api-service/ # Node.js backend
โ โโโ admin-dashboard/ # Angular admin panel
โโโ libs/
โ โโโ shared-ui/ # Shared UI components
โ โโโ auth/ # Authentication library
โ โโโ data-models/ # Shared data models
โ โโโ utils/ # Utility functions
โโโ tools/
โโโ scripts/ # Build and deployment scripts
Apa Itu Nx?
Nx adalah open-source build system dan monorepo management tool yang powerful, membawa pengembangan monorepo ke level berikutnya.
Fitur Utama
1. Smart Build System
- Hanya rebuild yang berubah
- Distributed task execution
- Computation caching (lokal dan remote)
2. Dependency Graph
- Memahami hubungan antar proyek
- Visualisasi dependencies
- Menjalankan task dalam urutan optimal
3. Code Generators
- Scaffold proyek baru dengan cepat
- Memastikan konsistensi di seluruh codebase
- Mengurangi boilerplate
4. Integrated Tooling
- Dukungan built-in untuk testing, linting, building
- Plugin ecosystem untuk framework populer
- Integrasi IDE
5. Scalability
- Menangani ratusan proyek
- CI/CD pipeline yang efisien
- Distributed caching dengan Nx Cloud
Teknologi yang Didukung
- Frontend: React, Angular, Vue, Next.js, React Native
- Backend: Node.js, NestJS, Express
- Mobile: React Native, Expo, Ionic
- Build Tools: Webpack, Vite, esbuild, Rollup
- JVM: Java (Gradle, Maven), Kotlin, Scala
- Lainnya: Python, Go, .NET
Mengapa Menggunakan Monorepo?
1. Code Sharing yang Mudah
Sebelum Monorepo (Polyrepo):
- Publish library ke npm
- Update package.json di 5 repo berbeda
- Menangani konflik versi
- Menunggu CI/CD pipeline
Dengan Monorepo:
- Import langsung dari shared library
- Perubahan langsung tersedia
- Single version, tanpa konflik
- Refactor di semua proyek sekaligus
2. Atomic Changes
// Single commit bisa update:
// - API endpoint di backend
// - API client di shared library
// - UI component yang menggunakan API
// - Tests untuk semua kode yang terpengaruh
// - Dokumentasi
// Ini tidak mungkin di polyrepo tanpa:
// - Multiple PR di berbagai repo
// - Coordinated merges
// - Version management yang rumit
3. Tooling yang Konsisten
- Satu ESLint config untuk semua proyek
- Satu TypeScript config
- Satu testing framework setup
- Satu CI/CD pipeline
- Satu set dependencies untuk dikelola
4. Refactoring yang Lebih Baik
- IDE bisa refactor di semua proyek
- Find all usages dari function di seluruh codebase
- Rename dengan aman dan percaya diri
- Tidak ada broken dependencies antar repo
5. CI/CD yang Lebih Efisien
# Nx hanya menjalankan task untuk proyek yang terpengaruh
nx affected -t test # Hanya test proyek yang berubah
nx affected -t build # Hanya build yang diperlukan
nx affected -t lint # Hanya lint kode yang berubah
# Lihat proyek mana saja yang terpengaruh
nx show projects --affected
# Visualisasi dependency graph untuk proyek yang terpengaruh
nx graph --affected
# Pendekatan tradisional: Jalankan semuanya, setiap waktu
6. Developer Experience yang Lebih Baik
- Clone sekali, kerjakan semuanya
- Single onboarding process
- Lebih mudah menemukan dan reuse kode
- Coding standards yang konsisten
Monorepo vs Polyrepo
Polyrepo (Multiple Repositories)
company-frontend/ (repo terpisah)
company-backend/ (repo terpisah)
company-mobile/ (repo terpisah)
company-shared-lib/ (repo terpisah, di-publish ke npm)
Kelebihan:
- โ Boundaries ownership yang jelas
- โ Independent deployment
- โ Ukuran repository lebih kecil
- โ Team autonomy
Kekurangan:
- โ Sulit share kode
- โ Kompleksitas version management
- โ Coordinated changes butuh multiple PR
- โ Duplicate dependencies
- โ Tooling yang tidak konsisten
- โ Sulit refactor antar proyek
Monorepo (Single Repository)
company-monorepo/
โโโ apps/
โ โโโ frontend/
โ โโโ backend/
โ โโโ mobile/
โโโ libs/
โโโ shared/
Kelebihan:
- โ Code sharing yang mudah
- โ Atomic changes
- โ Single source of truth
- โ Tooling yang konsisten
- โ Refactoring yang lebih baik
- โ Dependency management yang disederhanakan
Kekurangan:
- โ Membutuhkan tooling yang tepat (Nx menyelesaikan ini)
- โ Repository lebih besar (dimitigasi dengan Nx caching)
- โ Perlu praktik monorepo yang baik
- โ Potensi tight coupling (jika tidak hati-hati)
Contoh Real-World
Google - Monorepo Terbesar di Dunia
Statistik:
- 86 TB data (per 2015)
- 2 miliar baris kode
- 35 juta commit
- Ribuan developer
- Jutaan file
Tool yang Digunakan: Google menciptakan Bazel (sekarang open-source)
Mengapa Google Menggunakan Monorepo:
- Code reuse di seluruh perusahaan
- Unified tooling dan standards
- Kemampuan large-scale refactoring
- Atomic changes antar service
- Single version untuk setiap dependency
- Kolaborasi yang lebih mudah
Facebook/Meta
- Ratusan ribu file
- React, React Native, Jest dikembangkan di sini
- Code sharing antara Facebook, Instagram, WhatsApp
- Tool: Custom Mercurial + Buck build system
Microsoft
- Windows operating system
- Office suite
- Banyak internal tools
- Tool: Git dengan Virtual File System (VFS for Git)
Perusahaan Notable Lainnya
- Uber: Bazel (ribuan microservices)
- Airbnb: Bazel + Custom tooling
- Twitter: Bazel + Pants
Kapan Menggunakan Monorepo
โ Use Case yang Ideal
-
Multiple Related Applications
- Platform e-commerce dengan web, mobile, admin panel
- Produk SaaS dengan customer app + admin dashboard
- Microservices yang share kode
-
Shared Libraries
- UI component library yang digunakan di berbagai app
- Common utilities dan functions
- Shared data models
-
Full-Stack Development
- Frontend + Backend dalam repo yang sama
- Type sharing antara client dan server
- API contracts di satu tempat
-
Platform Products
- Multiple products sharing infrastructure
- White-label applications
- Multi-tenant systems
-
Enterprise Applications
- Organisasi besar dengan banyak team
- Kebutuhan akan consistency
- Complex dependencies
โ Kapan Menghindari Monorepo
-
Produk yang Benar-Benar Independen
- Tidak ada shared code
- Team berbeda, stack berbeda
- Tidak perlu koordinasi
-
Beberapa Open Source Projects
- Contributor mungkin hanya peduli satu bagian
- Release cycle terpisah
- Model governance berbeda
-
Tech Stack yang Sangat Berbeda
- Tidak ada overlap di dependencies
- Tidak ada shared tooling
- Tidak ada benefit dari unified workflow
Arsitektur Nx
Komponen Inti
1. Struktur Nx Workspace
my-workspace/
โโโ nx.json # Konfigurasi Nx
โโโ package.json # Dependencies (opsional)
โโโ apps/ # Aplikasi
โโโ libs/ # Library
โโโ .nx/ # Nx cache dan metadata
2. Konfigurasi Project
// apps/my-app/project.json
{
"name": "my-app",
"projectType": "application",
"targets": {
"build": { "executor": "@nx/webpack:webpack" },
"serve": { "executor": "@nx/webpack:dev-server" },
"test": { "executor": "@nx/jest:jest" }
}
}
3. Dependency Graph
Nx menyediakan visualisasi dependencies antar proyek:
nx graph # Membuka browser dengan graph interaktif
4. Computation Caching
# Run pertama: Benar-benar build
nx build my-app # Membutuhkan 30 detik
# Run kedua: Dari cache
nx build my-app # Membutuhkan 0.1 detik โก
Step-by-Step: Membuat Nx Monorepo dari Awal
Prasyarat
Pastikan Anda memiliki yang berikut terinstall:
# Node.js v18 atau lebih tinggi
node --version
# npm
npm --version
# Java 17+ (untuk Spring Boot)
java -version
# Git
git --version
Step 1: Buat Empty Git Repository
# Buat directory
mkdir my-monorepo
cd my-monorepo
# Initialize git
git init
# Buat initial README
echo "# My Monorepo" > README.md
git add README.md
git commit -m "Initial commit"
Step 2: Initialize Nx
# Initialize Nx dengan npm preset
npx nx@latest init --preset=npm --workspaceType=integrated --nxCloud=skip
Penjelasan Command:
nx@latest init- Initialize Nx di directory saat ini--preset=npm- Menggunakan npm untuk package management--workspaceType=integrated- Membuat integrated monorepo--nxCloud=skip- Skip Nx Cloud setup (bisa ditambahkan nanti)
Step 3: Verifikasi Instalasi
# Check file yang dibuat
ls -la
# Anda seharusnya melihat:
# - nx.json (Konfigurasi Nx)
# - .gitignore (Git ignore file)
# - nx / nx.bat (Nx wrapper scripts)
# - .nx/ (Nx cache dan installation)
# Check versi Nx
./nx --version
# List plugin yang tersedia
./nx list
Step 4: Memahami Struktur yang Di-generate
my-monorepo/
โโโ .git/ # Git repository
โโโ .gitignore # Git ignore patterns
โโโ .nx/ # Nx installation dan cache
โ โโโ nxw.js # JavaScript wrapper
โ โโโ installation/ # Nx packages
โโโ nx # Unix wrapper script
โโโ nx.bat # Windows wrapper script
โโโ nx.json # Konfigurasi Nx
โโโ README.md # Dokumentasi
Step 5: Konfigurasi nx.json Awal
{
"installation": {
"version": "22.2.3"
},
"$schema": "./node_modules/nx/schemas/nx-schema.json"
}
Step 6: Commit Setup Awal
git add .
git commit -m "Initialize Nx monorepo"
Menambahkan Spring Boot ke Nx
Sekarang mari kita integrasikan Spring Boot dengan Nx workspace kita.
Step 1: Install Gradle Plugin
# Method A: Menggunakan Nx (mungkin lebih lambat)
./nx add @nx/gradle
# Method B: Direct installation (lebih cepat)
cd .nx/installation
npm install @nx/gradle@22.2.3
cd ../..
Step 2: Update nx.json
{
"installation": {
"version": "22.2.3",
"plugins": {
"@nx/gradle": "22.2.3"
}
},
"$schema": "./node_modules/nx/schemas/nx-schema.json"
}
Step 3: Initialize Gradle Support
./nx generate @nx/gradle:init
Ini akan update nx.json Anda dengan konfigurasi Gradle plugin:
{
"installation": {
"version": "22.2.3",
"plugins": {
"@nx/gradle": "22.2.3"
}
},
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"plugins": [
{
"plugin": "@nx/gradle",
"options": {
"testTargetName": "test",
"classesTargetName": "classes",
"buildTargetName": "build"
}
}
],
"namedInputs": {
"default": ["{projectRoot}/**/*"],
"production": ["default", "!{projectRoot}/src/test/**/*"]
}
}
Step 4: Buat Apps Directory
mkdir -p apps
Step 5: Generate Spring Boot Project
Gunakan Spring Initializr untuk membuat proyek:
curl https://start.spring.io/starter.zip \
-d dependencies=web,data-jpa,h2,actuator \
-d type=gradle-project \
-d language=java \
-d bootVersion=3.4.0 \
-d javaVersion=21 \
-d groupId=com.example \
-d artifactId=spring-api \
-d name=SpringApi \
-d packageName=com.example.springapi \
-o apps/spring-api.zip
# Extract proyek
cd apps
unzip spring-api.zip -d spring-api
rm spring-api.zip
cd ..
Step 6: Buat Nx Project Configuration
Buat apps/spring-api/project.json:
{
"name": "spring-api",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"sourceRoot": "apps/spring-api/src",
"targets": {
"build": {
"executor": "@nx/gradle:gradle",
"outputs": ["{projectRoot}/build"],
"options": {
"taskName": "build"
}
},
"serve": {
"executor": "@nx/gradle:gradle",
"options": {
"taskName": "bootRun"
}
},
"test": {
"executor": "@nx/gradle:gradle",
"outputs": ["{projectRoot}/build/test-results"],
"options": {
"taskName": "test"
}
},
"clean": {
"executor": "@nx/gradle:gradle",
"options": {
"taskName": "clean"
}
}
},
"tags": ["type:app", "platform:jvm"]
}
Step 7: Verifikasi Project Setup
# List semua proyek
./nx show projects
# Output: spring-api
# Build proyek
./nx build spring-api
# Jalankan aplikasi
./nx serve spring-api
Step 8: Buat REST Controller
Buat apps/spring-api/src/main/java/com/example/springapi/HelloController.java:
package com.example.springapi;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello from Spring Boot in Nx Monorepo! ๐";
}
@GetMapping("/")
public String home() {
return "Welcome to Spring API - Powered by Nx";
}
}
Step 9: Test API Anda
# Jalankan server
./nx serve spring-api
# Di terminal lain, test endpoint
curl http://localhost:8080/hello
# Output: Hello from Spring Boot in Nx Monorepo! ๐
curl http://localhost:8080/
# Output: Welcome to Spring API - Powered by Nx
Step 10: Commit Pekerjaan Anda
git add .
git commit -m "Add Spring Boot API with Nx integration"
Command Nx yang Penting
Berikut command-command penting yang akan Anda gunakan secara regular:
# Check versi Nx
./nx --version
# List semua proyek
./nx show projects
# Tampilkan detail proyek
./nx show project spring-api
# Build proyek
./nx build spring-api
# Run/serve proyek
./nx serve spring-api
# Jalankan tests
./nx test spring-api
# Bersihkan build artifacts
./nx clean spring-api
# Lihat dependency graph
./nx graph
# Hapus Nx cache
./nx reset
# Jalankan command untuk multiple proyek
./nx run-many -t build -p spring-api,another-app
# Lihat proyek mana yang terpengaruh oleh perubahan
./nx show projects --affected
# Visualisasi dependency graph untuk proyek yang terpengaruh
./nx graph --affected
# Jalankan command hanya untuk proyek yang terpengaruh
./nx affected -t test
./nx affected -t build
./nx affected -t lint
# Command affected lanjutan
# Run affected dengan base branch tertentu
./nx affected -t test --base=origin/main
# Run affected membandingkan dengan commit tertentu
./nx affected -t test --base=HEAD~1
# Dry run (lihat apa yang akan terpengaruh tanpa eksekusi)
./nx affected -t test --dry-run
# Run affected secara parallel
./nx affected -t test --parallel=3
# Skip cache untuk affected
./nx affected -t test --skip-nx-cache
๐ Selamat!
Anda telah berhasil menyelesaikan Seri 1 dari tutorial Nx Monorepo!
Yang Telah Anda Capai
- โ Memahami arsitektur monorepo yang digunakan tech giants
- โ Setup Nx monorepo dari awal
- โ Install dan konfigurasi @nx/gradle plugin
- โ Integrasi Spring Boot 3.4 dengan Java 21
- โ Membuat REST API endpoints
- โ Berhasil build dan run Spring Boot menggunakan Nx
Spring Boot API Anda sekarang berjalan di enterprise-grade Nx monorepo dengan:
- ๐ Smart caching untuk builds yang lebih cepat
- ๐ Dependency tracking
- ๐๏ธ Arsitektur yang scalable
- ๐ ๏ธ Professional tooling
๐ Yang Akan Datang di Seri 2: Full-Stack Development
Di bagian selanjutnya dari seri ini, kita akan memperluas monorepo kita:
Whatโs Next
- ๐ฑ Menambahkan React/Next.js Frontend
- ๐ Integrasi Frontend-Backend
- ๐ฆ Code Sharing Antar Proyek
- ๐ฏ Menjalankan Full-Stack Bersama
- ๐งช Testing Full-Stack Applications
Teaser Commands
# Yang akan datang di Seri 2:
./nx add @nx/react
./nx generate @nx/react:application web
./nx run-many -t serve -p spring-api,web
Nantikan Seri 2! ๐โจ
Sumber Belajar Tambahan
Dokumentasi Resmi
Konsep Monorepo
- Monorepo.tools
- Why Google Stores Billions of Lines of Code in a Single Repository
- Bazel - Googleโs Build Tool
Komunitas
Kesimpulan
Anda telah mempelajari fundamental dari arsitektur monorepo dan berhasil mengintegrasikan Spring Boot dengan Nx! Foundation ini akan sangat berguna saat kita mengeksplorasi topik yang lebih advanced di seri-seri mendatang.
Poin-Poin Penting
- ๐๏ธ Monorepo memungkinkan code sharing dan consistency yang lebih baik
- ๐ Nx menyediakan enterprise-grade tooling
- โ Spring Boot terintegrasi seamlessly via Gradle plugin
- ๐ Tech giants mempercayai arsitektur monorepo karena alasan yang bagus
Di Seri 2, kita akan menambahkan aplikasi frontend dan mengeksplorasi full-stack development di Nx monorepo!
Tentang Seri Ini
Ini adalah Bagian 1 dari Seri Nx Monorepo:
- โ Seri 1: Pengenalan Nx & Integrasi Spring Boot (Anda di sini)
- ๐ Seri 2: Full-Stack Development dengan React/Next.js
- ๐ Seri 3: Shared Libraries & Code Reuse
- ๐ Seri 4: Fitur Nx Advanced & CI/CD
- ๐ Seri 5: Multi-Technology Monorepo
Repository: github.com/kreasipositif/demo-monorepository
Siap menguasai arsitektur monorepo modern? Bergabunglah dengan kursus pengembangan komprehensif kami di Kreasi Positif Indonesia dan pelajari best practices industri dari software engineers berpengalaman.