icon

개발 환경 설정


 NestJS 개발을 위한 효율적인 환경 설정은 생산성 향상과 원활한 프로젝트 진행의 기반이 됩니다.

 이 절에서는 NestJS 개발에 필요한 도구 설치부터 프로젝트 설정까지 상세히 다룹니다.

필수 도구 설치

 1. Node.js

 2. npm/yarn

  • npm은 Node.js와 함께 설치됨
  • yarn 선호 시 : npm install -g yarn

 3. TypeScript

  • npm install -g typescript
  • 최신 안정 버전 권장 (예 : 5.x)

NestJS CLI 설치 및 사용

 1. 설치

npm install -g @nestjs/cli

 2. 주요 명령어

  • 새 프로젝트 생성 : nest new project-name
  • 컨트롤러 생성 : nest generate controller users
  • 서비스 생성 : nest generate service users
  • 모듈 생성 : nest generate module users

 예시

nest new my-nest-project
cd my-nest-project
nest generate controller users

 결과

CREATE src/users/users.controller.spec.ts (485 bytes)
CREATE src/users/users.controller.ts (99 bytes)
UPDATE src/app.module.ts (322 bytes)

ID E/ 편집기 설정 (VS Code 기준)

 1. 추천 확장 프로그램

  • ESLint
  • Prettier
  • NestJS Snippets
  • Docker

 2. 디버깅 설정 (launch.json)

{
   "version": "0.2.0",
   "configurations": [
      {
      "type": "node",
      "request": "launch",
      "name": "Debug NestJS",
      "args": ["${workspaceFolder}/src/main.ts"],
      "runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}",
      "protocol": "inspector"
      }
   ]
}

프로젝트 유형별 초기 설정

  1. REST API
nest new my-rest-api
  1. GraphQL
nest new my-graphql-api
cd my-graphql-api
nest add @nestjs/graphql
  1. 마이크로서비스
nest new my-microservice
cd my-microservice
nest add @nestjs/microservices

 각 유형별 main.ts 차이

  • REST API
async function bootstrap() {
   const app = await NestFactory.create(AppModule);
   await app.listen(3000);
}
  • GraphQL
async function bootstrap() {
   const app = await NestFactory.create(AppModule);
   app.useGlobalPipes(new ValidationPipe());
   await app.listen(3000);
}
  • 마이크로서비스
async function bootstrap() {
   const app = await NestFactory.createMicroservice(AppModule, {
   transport: Transport.TCP,
   });
   await app.listen();
}

환경별 설정

 1. 환경 변수 관리

  • npm install dotenv
  • .env 파일 생성
.env
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
JWT_SECRET=mysecretkey

 2. 환경별 설정 파일

src/config/configuration.ts
export default () => ({
   port: parseInt(process.env.PORT, 10) || 3000,
   database: {
   url: process.env.DATABASE_URL,
   },
   jwt: {
   secret: process.env.JWT_SECRET,
   },
});
  1. 설정 모듈 생성
nest generate module config
nest generate service config

버전 관리 (Git)

  1. 초기화
git init
  1. .gitignore 설정
.gitignore
node_modules
dist
.env
*.log
  1. 첫 커밋
git add .
git commit -m "Initial commit"

효율적인 개발 환경을 위한 팁

 1. 일관된 코드 스타일 유지

  • ESLint와 Prettier 설정으로 자동 포맷팅
  • .eslintrc.js.prettierrc 파일 프로젝트에 포함

 2. 환경 변수 관리

  • .env.example 파일 생성하여 필요한 환경 변수 목록 공유
  • 민감한 정보는 절대 버전 관리에 포함시키지 않음

 3. 의존성 관리

  • package.json의 버전을 구체적으로 지정 (예 : "@nestjs/core": "^8.0.0")
  • 정기적으로 의존성 업데이트 및 호환성 확인

 4. 테스트 자동화

  • Jest 설정 최적화
  • CI/CD 파이프라인에 테스트 통합 **
  1. 문서화**
  • Swagger 통합으로 API 문서 자동 생성
  • README.md 파일에 프로젝트 설정 및 실행 방법 상세히 기록

 6. 개발 서버 자동 재시작

  • nest start --watch 명령어 활용

 7. 디버깅 환경 최적화

  • VS Code의 "Auto Attach" 기능 활성화

 8. 컨테이너화 고려

  • Docker 사용 시 개발, 테스트, 프로덕션 환경 일관성 유지

 주의사항

  • 프로덕션 환경의 보안 설정 철저히 관리
  • 성능에 영향을 미치는 개발 도구들은 프로덕션 빌드에서 제외
  • 정기적으로 의존성 및 Node.js 버전 업데이트 검토

 NestJS 개발 환경을 효과적으로 설정함으로써, 개발자는 핵심 비즈니스 로직 구현에 더 집중할 수 있습니다.

 위의 가이드를 따라 설정하면, 생산성 높고 유지보수가 용이한 NestJS 프로젝트를 시작할 수 있습니다.