반응형

Yarn이란?

npm을 보완하여 나온 패키지 매니저

 

Express란?

Node.js를 위한 서버 프레임워크

 

 

 

 

1. 설치

npm install yarn -g

yarn --version

yarn을 글로벌로 설치하고, 설치 완료 여부 확인을 위해 버전을 확인한다.

package.json 파일이 설치되었을 것이다.

 

 

2. 초기 세팅

폴더를 생성한 후 디렉토리를 이동한 다음, yarn --init 을 실행한다.

name만 입력해주고 나머지는 enter로 넘긴다.

 

3. Express 설치

yarn add express	// express 설치
yarn add -D @types/node @types/express	// typescript용 모듈 설치
yarn add -D nodemon	// 서버 코드 변경 시 자동 재시작을 도와줌
tsc --init 	// tsconfig.json 파일 생성, TS를 JS로 컴파일하는 옵션 설정

기본으로 생성되는 tsconfig.json을 수정할 필요가 있다. (검색 참고)

// tsconfig.json

{
  "compilerOptions": {
    "target": "es6", // 어떤 버전으로 컴파일
    "allowSyntheticDefaultImports": true, // default export가 없는 모듈에서 default imports를 허용
    "experimentalDecorators": true, // decorator 실험적 허용
    "emitDecoratorMetadata": true, // 데코레이터가 있는 선언에 대해 특정 타입의 메타 데이터를 내보내는 실험적인 지원
    "skipLibCheck": true, // 정의 파일 타입 체크 여부
    "moduleResolution": "node", // commonJS -> node 에서 동작
    "module": "commonjs", // import 문법
    "strict": true, // 타입 검사 엄격하게 
    "pretty": true, // error 메시지 예쁘게
    "sourceMap": true, // 소스맵 파일 생성 -> .ts가 .js 파일로 트랜스 시 .js.map 생성
    "outDir": "./dist", // 트랜스 파일 (.js) 저장 경로
    "allowJs": true, // js 파일 ts에서 import 허용
    "esModuleInterop": true, // ES6 모듈 사양을 준수하여 CommonJS 모듈을 가져올 수 있게 허용
    "typeRoots": [
      "./src/types/express.d.ts", // 타입(*.d.ts)파일을 가져올 디렉토리 설정
      "./node_modules/@types" // 설정 안할시 기본적으로 ./node_modules/@types
    ]
  },
  "include": [
    "./src/**/*" // build 시 포함
  ],
  "exclude": [
    "node_modules", // build 시 제외
    "tests"
  ]
}

 

 

4. nodemon.json 생성

// nodemon.json

{
    "watch": [
        "src",
        ".env"
    ],
    "ext": "js,ts,json",
    "ignore": [
        "src/**/*.spec.ts"  
    ],
    "exec": "ts-node  --transpile-only ./src/index.ts"
}

watch : 변경 감지 경로

ext : 변경 감지 확장자

ignore : 변경 감지 제외

exec : nodemon 수행 명령

 

5. package.json 수정

// package.json

{
  "name": "express-example",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "dev": "nodemon",
    "build": "tsc && node dist"
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^17.0.25",
    "nodemon": "^2.0.15"
  }
}

 

6. src폴더와 그 내부에 index.ts 생성

// index.ts

import express, { Request, Response, NextFunction } from 'express';

const app = express();

app.get('/', (req: Request, res: Response, next: NextFunction) => {
    res.send('Hi! This is my first express server');
});

app.listen('8000', () => {
    console.log(`
        #############################################
        🛡️ Server listening on port: 8000 🛡️
        #############################################  
    `);
})

 

7. 서버 실행 및 프로젝트 빌드

yarn run dev	// package.json에 따라 nodemon 실행

yarn run build	// package.json에 따라 tsc && node dist 실행

build 명령어 실행 시 'dist' 폴더가 생성된다.

그 안에는 ts를 js로 변환한 트랜스 파일, sourceMap 파일이 생성된다.

 

지금까지 세팅한 결과로 위와 같은 디렉토리 구조가 생성된다.

반응형

+ Recent posts