--- Nx Monorepo Seri 1: Pengenalan & Integrasi Spring Boot
Beranda โ†’ Blog โ†’ Nx Monorepo Seri 1: Pengenalan & Integrasi Spring Boot

Nx Monorepo Seri 1: Pengenalan & Integrasi Spring Boot

Pelajari cara setup monorepo modern menggunakan Nx dan mengintegrasikan aplikasi Spring Boot - arsitektur yang sama digunakan oleh Google, Facebook, dan tech giants lainnya.

Nx Monorepo Seri 1: Pengenalan & Integrasi Spring Boot

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

  1. Multiple Related Applications

    • Platform e-commerce dengan web, mobile, admin panel
    • Produk SaaS dengan customer app + admin dashboard
    • Microservices yang share kode
  2. Shared Libraries

    • UI component library yang digunakan di berbagai app
    • Common utilities dan functions
    • Shared data models
  3. Full-Stack Development

    • Frontend + Backend dalam repo yang sama
    • Type sharing antara client dan server
    • API contracts di satu tempat
  4. Platform Products

    • Multiple products sharing infrastructure
    • White-label applications
    • Multi-tenant systems
  5. Enterprise Applications

    • Organisasi besar dengan banyak team
    • Kebutuhan akan consistency
    • Complex dependencies

โŒ Kapan Menghindari Monorepo

  1. Produk yang Benar-Benar Independen

    • Tidak ada shared code
    • Team berbeda, stack berbeda
    • Tidak perlu koordinasi
  2. Beberapa Open Source Projects

    • Contributor mungkin hanya peduli satu bagian
    • Release cycle terpisah
    • Model governance berbeda
  3. 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

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.