티스토리 뷰

Node.js/Nest.js

[NestJS] 1. NestJS 시작하기

angieveloper 2022. 5. 22. 12:48

⛳️ NestJS란?

NestJS 로고

공식문서 (https://docs.nestjs.com/)​ 번역

 

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 Progamming), FP (Functional Programming), and FRP (Functional Reac

docs.nestjs.com

 

NestJS는 효율적이고, 확장 가능한 Node.js 서버사이드 어플리케이션을 만들기 위한 프레임워크 입니다. NestJS는 발전된 Javascript인 TypeScript를 지원합니다. 그리고 OOP(Object Oriented Promgramming, 객체 지향 프로그래밍), FP (Functional Programming, 함수형 프로그래밍), FRP (Functional Reactive Programming, 함수형 반응형 프로그래밍)의 요소들과 결합되어 있습니다.

 

NestJS의 안을 들여다보면, NestJS는 Express.js와 같은 강력한 HTTP 서버 프레임워크를 기본적으로 사용하며 선택적으로 Fastify를 사용하도록 구성할 수도 있습니다.

 

NestJS는 이런 보통의 Node.js 프레임워크들(Exrpess/Fastify) 위에서 추상화 단계를 지원하지만, 개발자들에게 API를 직접 노출하기도 합니다. 이는 개발자들로 하여금 기본 플랫폼에 사용할 수 있는 많은 써드파티 모듈들을 자유롭게 사용할 수 있게 해줍니다.

 

💡 NestJS의 철학

최근 몇 년동안, Node.js 덕분에 Javascript는 프론트엔드와 백엔드 모두에서 국제 공용어(lingua franca)가 됐습니다. 이는 Angular, React, Vue와 같은 개발자들의 생산성을 높여주고, 빠르게 만들 수 있고, 테스트 가능하고, 확장 가능한 프론트엔드 어플리케이션을 만들 수 있는 좋은 프로젝트들이 부상하게 했습니다. 그러나, Node와 서버 사이드 Javascript트를 위한 좋은 라이브러리, 헬퍼, 도구들이 정말 많이 존재하는데 비해, 그 어떤 것도 가장 중요한 문제인 구조(Architecture)를 효율적으로 해결해주지 못했습니다.

 

NestJS는 개발자들과 팀이 테스트 하기 좋고, 확장성이 있고, 느슨하게 결합됐고, 쉽게 유지할 수 있는 어플리케이션을 만들 수 있게 해주는 즉시 사용할 수 있는(out-of-the-box) 어플리케이션 구조를 제공합니다. 구조는 Angular에서 크게 영감 받았습니다.

 

⛳️  1. Node.js 최신버전 설치

 

Node.js 홈페이지에서 최신 버전을 다운로드하고 컴퓨터에 설치해주자

https://nodejs.org/ko/

 

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

잘 설치되었는지 아래 명령어를 터미널에 입력해서 확인!

$ node --version

설치된 노드의 버전 정보가 뜨면 잘 설치된 것이다.

 

⛳️  2. Nest.js CLI 설치

 

CLI를 설치하면 Nest.js 프로젝트를 쉽게 시작할 수 있다.

$ sudo npm install -g @nestjs/cli

 

⛳️  3. 프로젝트 생성하기

 

NestJS의 프로젝트를 생성해주자.

프로젝트를 생성하려는 디렉토리에서 아래 명령어를 실행해준다.

$ nest new {project-name}

그러면 {project-name} 이라는 디렉토리가 생성되고 그 아래에 NestJS 프로젝트에 해당하는 파일들이 생성된다.

 

만약 디렉토리를 별도로 생성하지 않고, 현재 디렉토리에 파일들을 생성하고 싶으면

$ nest new ./

를 실행해주면 된다.

 

그러면 아래와 같이 패키지 매니저를 선택하라고 나오는데 상황에 맞게 선택하면 된다

저는 npm이 익숙해서 npm을 선택했습니다

? Which package manager would you ❤️  to use? (Use arrow keys)
❯ npm 
  yarn 
  pnpm

 

그러면 아래 명령어 같이 설치한다는 문구가 나오고..

▹▹▹▹▹ Installation in progress... ☕

 

아래처럼 나오면 프로젝트 첫 실행 성공!

🚀  Successfully created project {proeject-name}
👉  Get started with the following commands:

$ cd {project-name}
$ 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

 

아래와 같이 프로젝트에 필요한 파일들이 생성된다.

eslint, tsconfig 같이 Typescript를 작성하는데 도움되는 라이브러리도 모두 기본으로 생성되는 걸 볼 수 있다.

 



위의 파일들을 조금 더 알아보면

 

.eslintrc.js

코드의 규칙을 구성하는 파일, 가이드라인, 문법 오류 알림 등

module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    tsconfigRootDir : __dirname, 
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint/eslint-plugin'],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  root: true,
  env: {
    node: true,
    jest: true,
  },
  ignorePatterns: ['.eslintrc.js'],
  rules: {
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
  },
};

 

.prettierrc

코드 스타일 형식을 구성하는 파일, 따옴표 설정, 인덴트 설정 등

{
  "singleQuote": true,
  "trailingComma": "all"
}

 

nest-cli.json

NestJS 프로젝트 구성 파일

{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src"
}

 

tsconfig.json

어떻게 타입스크립트를 컴파일 할 지 설정하는 파일

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}

 

tsconfig.build.json

build를 할 때 필요한 설정들과 필요 없는 파일들 명시

{
  "extends": "./tsconfig.json",
  "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

 

package.json

Node.js의 구성과 의존성 패키지 파일

  • build : 운영 환경을 위한 빌드
  • format : 린트 에러가 나면 prettierrc 파일에 따라 수정
  • start : 앱 시작
{
  "name": "{project-name}",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },
  "dependencies": {
    "@nestjs/common": "^8.0.0",
    "@nestjs/core": "^8.0.0",
    "@nestjs/platform-express": "^8.0.0",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^7.2.0"
  },
  "devDependencies": {
    "@nestjs/cli": "^8.0.0",
    "@nestjs/schematics": "^8.0.0",
    "@nestjs/testing": "^8.0.0",
    "@types/express": "^4.17.13",
    "@types/jest": "27.5.0",
    "@types/node": "^16.0.0",
    "@types/supertest": "^2.0.11",
    "@typescript-eslint/eslint-plugin": "^5.0.0",
    "@typescript-eslint/parser": "^5.0.0",
    "eslint": "^8.0.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "jest": "28.0.3",
    "prettier": "^2.3.2",
    "source-map-support": "^0.5.20",
    "supertest": "^6.1.3",
    "ts-jest": "28.0.1",
    "ts-loader": "^9.2.3",
    "ts-node": "^10.0.0",
    "tsconfig-paths": "4.0.0",
    "typescript": "^4.3.5"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

 

 

위 파일 설명은 따라하면서 배우는 NestJS 강의 (https://youtu.be/3JminDpCJNE) 참고

 

'Node.js > Nest.js' 카테고리의 다른 글

NestJS에서 DTO를 class로 선언하는 이유  (0) 2022.08.25
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함