NestJS 시작하기
NestJS는 효율적이고 확장 가능한 Node.js 서버 사이드 애플리케이션을 구축하기 위한 프레임워크입니다. TypeScript를 기본으로 사용하며, Express 또는 Fastify를 기반으로 동작합니다.
특징
- TypeScript 완벽 지원
- 의존성 주입(Dependency Injection) 패턴
- 모듈 기반 아키텍처
- 데코레이터를 활용한 간결한 코드
- 테스트 친화적인 구조
사전 요구사항
NestJS를 사용하기 위해서는 다음이 설치되어 있어야 합니다:
- Node.js (v16 이상)
- npm 또는 yarn, pnpm
NestJS CLI 설치
NestJS CLI는 프로젝트 생성 및 관리를 쉽게 해주는 도구입니다.
전역 설치
npm install -g @nestjs/cli
yarn global add @nestjs/cli
pnpm add -g @nestjs/cli
|
설치 확인
프로젝트 생성 방법
1. NestJS CLI로 프로젝트 생성
가장 권장되는 방법으로, CLI를 사용하면 모든 설정이 자동으로 완료됩니다.
nest new project-name
nest new project-name --package-manager npm nest new project-name --package-manager yarn nest new project-name --package-manager pnpm
|
프로젝트 생성 시 다음을 선택할 수 있습니다:
- 사용할 패키지 매니저 (npm, yarn, pnpm)
- Git 저장소 초기화 여부
2. Git을 사용한 프로젝트 생성
git clone https://github.com/nestjs/typescript-starter.git project-name cd project-name npm install
git clone https://github.com/nestjs/javascript-starter.git project-name cd project-name npm install
|
3. 수동으로 프로젝트 생성
처음부터 직접 설정하고 싶다면:
mkdir project-name cd project-name
npm init -y
npm install @nestjs/core @nestjs/common @nestjs/platform-express reflect-metadata rxjs
npm install -D @nestjs/cli @nestjs/schematics typescript @types/node ts-node
|
프로젝트 구조
CLI로 생성된 프로젝트의 기본 구조:
project-name/ ├── src/ │ ├── app.controller.spec.ts # 컨트롤러 테스트 │ ├── app.controller.ts # 기본 컨트롤러 │ ├── app.module.ts # 루트 모듈 │ ├── app.service.ts # 기본 서비스 │ └── main.ts # 애플리케이션 진입점 ├── test/ │ ├── app.e2e-spec.ts # E2E 테스트 │ └── jest-e2e.json # Jest E2E 설정 ├── node_modules/ ├── .eslintrc.js # ESLint 설정 ├── .prettierrc # Prettier 설정 ├── nest-cli.json # NestJS CLI 설정 ├── package.json ├── tsconfig.json # TypeScript 설정 └── tsconfig.build.json # 빌드용 TypeScript 설정
|
애플리케이션 실행
개발 모드 실행
npm run start
npm run start:dev
npm run start:debug
|
프로덕션 빌드 및 실행
npm run build
npm run start:prod
|
기본 포트 확인
기본적으로 http://localhost:3000에서 실행됩니다.
기본 파일 설명
main.ts - 애플리케이션 진입점
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module';
async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap();
|
app.module.ts - 루트 모듈
import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service';
@Module({ imports: [], controllers: [AppController], providers: [AppService], }) export class AppModule {}
|
app.controller.ts - 컨트롤러
import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service';
@Controller() export class AppController { constructor(private readonly appService: AppService) {}
@Get() getHello(): string { return this.appService.getHello(); } }
|
app.service.ts - 서비스
import { Injectable } from '@nestjs/common';
@Injectable() export class AppService { getHello(): string { return 'Hello World!'; } }
|
추가 패키지 설치
프로젝트 개발 시 자주 사용하는 패키지들:
데이터베이스 (TypeORM)
npm install @nestjs/typeorm typeorm mysql2
npm install @nestjs/typeorm typeorm pg
npm install @nestjs/mongoose mongoose
|
설정 관리
npm install @nestjs/config
|
검증 (Validation)
npm install class-validator class-transformer
|
Swagger (API 문서화)
npm install @nestjs/swagger swagger-ui-express
|
JWT 인증
npm install @nestjs/jwt @nestjs/passport passport passport-jwt npm install -D @types/passport-jwt
|
테스트 실행
npm run test
npm run test:e2e
npm run test:cov
npm run test:watch
|
CLI 명령어
프로젝트 생성 후 자주 사용하는 CLI 명령어:
nest generate module users
nest g mo users
nest g controller users
nest g service users
nest g resource users
nest g middleware auth
nest g guard auth
nest g interceptor logging
nest g pipe validation
nest g filter http-exception
|
다음 단계
프로젝트를 성공적으로 생성했다면:
- 모듈 구조 이해하기
- 컨트롤러와 라우팅 학습
- 서비스와 의존성 주입 이해
- 데이터베이스 연결 설정
- 미들웨어, 가드, 인터셉터 활용
참고 자료
마무리
NestJS는 강력한 아키텍처와 TypeScript의 장점을 활용하여 확장 가능한 서버 애플리케이션을 만들 수 있게 해줍니다. CLI를 통해 쉽게 시작할 수 있으며, 모듈 기반 구조로 체계적인 코드 관리가 가능합니다.