Nx 완벽 가이드 | 모노레포·빌드 시스템·캐싱·플러그인·실전 활용
이 글의 핵심
Nx로 고성능 모노레포를 구축하는 완벽 가이드입니다. Workspace, Computation Caching, Distributed Task Execution, Plugins까지 실전 예제로 정리했습니다.
실무 경험 공유: Lerna에서 Nx로 전환하면서, 빌드 시간이 80% 단축되고 개발 경험이 크게 향상된 경험을 공유합니다.
들어가며: “모노레포가 느려요”
실무 문제 시나리오
시나리오 1: 빌드가 너무 느려요
전체 빌드에 30분이 걸립니다. Nx는 캐싱으로 5분으로 단축합니다.
시나리오 2: 의존성 관리가 복잡해요
수동 관리가 어렵습니다. Nx는 자동으로 분석합니다.
시나리오 3: CI/CD가 비효율적이에요
모든 프로젝트를 빌드합니다. Nx는 변경된 것만 빌드합니다.
1. Nx란?
핵심 특징
Nx는 차세대 모노레포 빌드 시스템입니다.
주요 장점:
- Computation Caching: 로컬 + 원격 캐싱
- Affected Commands: 변경된 것만 실행
- Distributed Task Execution: 병렬 실행
- Plugins: Angular, React, Next.js, Nest
- Dependency Graph: 시각화
2. 설치 및 Workspace 생성
새 Workspace 생성
npx create-nx-workspace@latest my-workspace
# 옵션 선택
# - Integrated monorepo
# - React / Angular / Next.js
# - Nx Cloud (Yes/No)
기존 프로젝트에 추가
npx nx@latest init
3. 프로젝트 생성
React 앱
nx generate @nx/react:app my-app
React 라이브러리
nx generate @nx/react:lib my-lib
Next.js 앱
nx generate @nx/next:app my-next-app
Nest.js 앱
nx generate @nx/nest:app my-api
4. 프로젝트 구조
my-workspace/
├── apps/
│ ├── web/ # Next.js 앱
│ ├── mobile/ # React Native 앱
│ └── api/ # Nest.js API
├── libs/
│ ├── shared/ui/ # 공유 UI 컴포넌트
│ ├── shared/utils/ # 공유 유틸리티
│ └── feature/auth/ # Auth 기능
├── nx.json
├── package.json
└── tsconfig.base.json
5. 라이브러리 사용
라이브러리 생성
nx generate @nx/react:lib shared-ui
컴포넌트 생성
nx generate @nx/react:component button --project=shared-ui --export
사용
// apps/web/src/app/page.tsx
import { Button } from '@my-workspace/shared-ui';
export default function Home() {
return <Button>Click me</Button>;
}
6. Task 실행
단일 프로젝트
# 빌드
nx build web
# 테스트
nx test web
# Lint
nx lint web
# Dev 서버
nx serve web
Affected Commands
# 변경된 프로젝트만 빌드
nx affected:build
# 변경된 프로젝트만 테스트
nx affected:test
# 변경된 프로젝트만 Lint
nx affected:lint
7. nx.json 설정
{
"tasksRunnerOptions": {
"default": {
"runner": "nx/tasks-runners/default",
"options": {
"cacheableOperations": ["build", "test", "lint"],
"parallel": 3
}
}
},
"targetDefaults": {
"build": {
"dependsOn": [^build],
"inputs": ["production", "^production"],
"outputs": [{projectRoot}/dist]
},
"test": {
"inputs": ["default", "^production", "{workspaceRoot}/jest.preset.js"],
"cache": true
}
},
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": [
"default",
"!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)",
"!{projectRoot}/tsconfig.spec.json"
],
"sharedGlobals": []
}
}
8. Dependency Graph
# 의존성 그래프 시각화
nx graph
# 특정 프로젝트의 의존성
nx graph --focus=web
# Affected 그래프
nx affected:graph
9. Nx Cloud
설정
nx connect-to-nx-cloud
원격 캐싱
{
"tasksRunnerOptions": {
"default": {
"runner": "@nrwl/nx-cloud",
"options": {
"cacheableOperations": ["build", "test", "lint"],
"accessToken": "YOUR_TOKEN"
}
}
}
}
10. 실전 예제: 풀스택 앱
구조
my-workspace/
├── apps/
│ ├── web/ # Next.js
│ └── api/ # Nest.js
└── libs/
├── shared/types/ # 공유 타입
└── shared/utils/ # 공유 유틸
공유 타입
// libs/shared/types/src/lib/user.ts
export interface User {
id: number;
email: string;
name: string;
}
API
// apps/api/src/app/users/users.controller.ts
import { Controller, Get } from '@nestjs/common';
import { User } from '@my-workspace/shared-types';
@Controller('users')
export class UsersController {
@Get()
getUsers(): User[] {
return [
{ id: 1, email: '[email protected]', name: 'John' },
];
}
}
Web
// apps/web/src/app/page.tsx
import { User } from '@my-workspace/shared-types';
export default async function Home() {
const response = await fetch('http://localhost:3000/api/users');
const users: User[] = await response.json();
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
정리 및 체크리스트
핵심 요약
- Nx: 모노레포 빌드 시스템
- Computation Caching: 로컬 + 원격
- Affected Commands: 변경된 것만
- Distributed Execution: 병렬 실행
- Plugins: 다양한 프레임워크
- Dependency Graph: 시각화
구현 체크리스트
- Nx 설치
- Workspace 생성
- 프로젝트 생성
- 라이브러리 생성
- Task 실행
- Affected Commands 사용
- Nx Cloud 설정
- Dependency Graph 확인
같이 보면 좋은 글
- Turborepo 완벽 가이드
- pnpm 완벽 가이드
- Monorepo 가이드
이 글에서 다루는 키워드
Nx, Monorepo, Build System, Caching, TypeScript, Angular, React
자주 묻는 질문 (FAQ)
Q. Turborepo와 비교하면 어떤가요?
A. Nx가 더 많은 기능을 제공하고 플러그인이 풍부합니다. Turborepo는 더 간단합니다.
Q. Lerna와 비교하면 어떤가요?
A. Nx가 훨씬 빠르고 현대적입니다. Lerna는 더 이상 활발히 개발되지 않습니다.
Q. Nx Cloud가 필수인가요?
A. 아니요, 로컬 캐싱만으로도 충분히 빠릅니다. Nx Cloud는 팀 협업 시 유용합니다.
Q. 프로덕션에서 사용해도 되나요?
A. 네, Google, Microsoft 등 대기업에서 사용하고 있습니다.