본문 바로가기
Study/NestJS

[NestJS] 1. 프로젝트 개발환경 구성

by DevJaewoo 2023. 12. 19.
반응형

NestJS 프로젝트 개발환경 구성

조현영님의 Slack 클론 코딩 강의를 따라 NestJS 공부를 시작했다.

대부분 강의 내용대로 세팅했지만, 그렇지 않은 부분도 있기에 세팅한 내용을 정리해두려 한다.

 

Slack 클론 코딩[백엔드 with NestJS + TypeORM] 강의 - 인프런

Node.js의 스프링이라고 불리는 NestJS를 배우고, Dependency Injection의 편리함을 맛봅시다. API 개발부터, 익스프레스와의 비교, 배포, 테스팅까지 모두 배워봅시다., 내 손으로 만드는 채팅 앱, 서버 개

www.inflearn.com


Node.js 설치

강의에선 Node.js 14를 사용한다.

당시엔 Node 14가 가장 최신의 LTS였는데, 현재는 최신 버전이 Node 20이라 충돌이 생길 우려가 있었다. 때문에 여차하면 버전을 바꿀 수 있도록 nvm을 통해 Node를 설치했다.

 

NVM (Node Version Manager) 은 Node의 버전 관리를 도와주는 프로그램으로, 원하는 버전의 Node를 설치하고 작업 환경의 Node 버전을 손쉽게 변경할 수 있게 해준다.

 

최신 버전의 NVM은 아래 링크에서 다운받을 수 있다.

 

Releases · coreybutler/nvm-windows

A node.js version management utility for Windows. Ironically written in Go. - coreybutler/nvm-windows

github.com

 

nvm-setup.exe 다운로드 후 설치가 완료되었다면, CMD에서 아래 명령어를 실행해 Node 버전을 20으로 설정할 수 있다.

20으로 해보고 문제가 생기면 nvm install 14로 변경하여 진행하면 될것 같다.

nvm install 20
nvm use 20

 

Node가 잘 설치되었는지 확인해보자.

node --version
v14.21.3

MySQL 설치

NestJS + TypeORM 강의이기 때문에 DB 환경도 구축해야 한다.

강의에선 MySQL을 홈페이지에서 직접 다운로드 받았지만, Docker로 띄워도 될것 같아 MySQL 이미지만 받아 실행했다.

 

Docker 설치 방법은 아래 글에서 확인할 수 있다.

 

[Docker] 도커 설치하기

Intro 이번 시간에는 이전 글에 이어 Docker를 설치하는 방법에 대해 알아보도록 하자. [Docker] Docker는 무엇이고, 왜 사용해야 할까? Docker는 무엇이고, 왜 사용해야 할까? 요즘 개발 공부를 하면서 개

devjaewoo.tistory.com

 

도커가 설치되었다면, 아래 명령어를 통해 이미지를 다운로드하고 컨테이너를 실행시키자.

docker run --name mysql_sleact -p 3306:3306 -e MYSQL_ROOT_PASSWORD=[root 계정 비밀번호] -itd mysql:8.0

 

이후 CMD에서 MySQL 서버에 로그인하여 정상적으로 설정되었는지 확인할 수 있다.

mysql -u root -p
Enter password: *********

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.35 MySQL Community Server - GPL

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

NestJS 프로젝트 세팅

이제 실제 작업을 진행할 NestJS 프로젝트 폴더를 만들어야 한다.

보통의 Node 프로젝트라면 npm init으로 생성했겠지만, Nest는 CLI를 미리 설치해야 한다.

npm i -g @nestjs/cli
nest new [프로젝트 이름]

 

이후 Package Manager를 npm, yarn, pnpm 중 어느것을 사용하겠냐고 묻는데, npm으로 선택하면 된다.

설치가 완료되면 아래와 같은 메시지가 나온다.

? Which package manager would you ❤️ to use? npm
CREATE sleact/.eslintrc.js (663 bytes)
CREATE sleact/.prettierrc (51 bytes)
CREATE sleact/nest-cli.json (171 bytes)
CREATE sleact/package.json (1947 bytes)
CREATE sleact/README.md (3340 bytes)
CREATE sleact/tsconfig.build.json (97 bytes)
CREATE sleact/tsconfig.json (546 bytes)
CREATE sleact/src/app.controller.ts (274 bytes)
CREATE sleact/src/app.module.ts (249 bytes)
CREATE sleact/src/app.service.ts (142 bytes)
CREATE sleact/src/main.ts (208 bytes)
CREATE sleact/src/app.controller.spec.ts (617 bytes)
CREATE sleact/test/jest-e2e.json (183 bytes)
CREATE sleact/test/app.e2e-spec.ts (630 bytes)

- Installation in progress... ☕
√ Installation in progress... ☕

🚀  Successfully created project sleact
👉  Get started with the following commands:

$ cd sleact
$ npm run start


                          Thanks for installing Nest 🙏
                 Please consider donating to our open collective
                        to help us maintain this package.


                   🍷  Donate: https://opencollective.com/nest

 

설치가 완료되면 프로젝트를 실행해보자.

npm run start

 

localhost:3000에 접속했을 때, 아래와 같이 'Hello World!'가 보이면 된다.


Hot Reload

프로젝트 규모가 커짐에 따라, 서버를 시작되는데 걸리는 시간이 점점 증가한다.

때문에 개발 시 서버를 껐다 켰다 할 경우, 재시작하는데 걸리는 시간이 매번 낭비된다.

 

이를 위해 Nest엔 Hot Reload 기능이 존재한다. 서버를 재시작하지 않고도 수정내용을 반영해주는 기능으로, 디버깅을 매우 편하게 할 수 있게 해준다.

 

Hot Reload 적용 방법은 공식문서에 자세히 나와있다.

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

우선 Hot Reload 관련 패키지를 설치한다.

npm i --save-dev webpack-node-externals run-script-webpack-plugin webpack

 

이후 프로젝트 폴더에 webpack-hmr.config.js 파일을 생성하고, 아래 내용을 붙여넣는다.

const nodeExternals = require('webpack-node-externals');
const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');

module.exports = function (options, webpack) {
  return {
    ...options,
    entry: ['webpack/hot/poll?100', options.entry],
    externals: [
      nodeExternals({
        allowlist: ['webpack/hot/poll?100'],
      }),
    ],
    plugins: [
      ...options.plugins,
      new webpack.HotModuleReplacementPlugin(),
      new webpack.WatchIgnorePlugin({
        paths: [/\.js$/, /\.d\.ts$/],
      }),
      new RunScriptWebpackPlugin({
        name: options.output.filename,
        autoRestart: false,
      }),
    ],
  };
};

 

이후 main.ts의 내용을 아래와 같이 변경한다.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

declare const module: any;

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const port = process.env.port ?? 3000;
  await app.listen(3000);
  console.log(`Listening on port ${port}`);

  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
}

bootstrap();

 

package.json - script의 start:dev 명령어를 아래와 같이 변경한다.

"start:dev": "nest build --webpack --webpackPath webpack-hmr.config.js --watch"

 

설정이 완료되었다면 서버를 실행해 이전과 같이 'Hello World'가 잘 표시되는지 확인해보자.

npm run start:dev

이렇게 프로젝트 개발환경 구성이 완료되었다.

 

참고자료

반응형

'Study > NestJS' 카테고리의 다른 글

[NestJS] 2. 환경변수 적용 (ConfigModule)  (1) 2023.12.21