[NodeJS]TypeScript를 활용한 웹서버 준비

캡틴 노드랭크·2022년 8월 9일
0

NodeJS

목록 보기
11/12

요 근래 타입스크립트 입지가 계속해서 확산되고있습니다. 보통 타입스크립트로 웹 서버를 작성하기 위해서 NestJS라는 프레임워크를 사용했지만, Epxress에서도 사용하도록 타입을 지원하는 라이브러리들이 많이 추가되었습니다.

타입스크립트 설치

npm i -g typescript

타입스크립트 프로젝트를 시작하기 위해 전역에 typescript를 설치 해 줍니다.

Express 웹 서버 준비

npm i -D express ts-node nodemon @types/node @types/express

express: 웹 서버를 더욱 쉽게 구현가능한 NodeJS의 특별한 프레임워크입니다.
ts-node: TypeScript 프로젝트를 컴파일하지 않고, 직접 실행시키는 라이브러리입니다.
@types/express: TypeScript 프로젝트에서 Express의 타입을 가진 라이브러리입니다.
@types/node: TypeScript 프로젝트에서 Node의 타입을 가진 라이브러리입니다.
nodemon: 서버 파일을 수정할 때마다 자동으로 재실행 해줍니다.

tsconfig.json

프로젝트 디렉토리내에서 터미널에 tsc --init 을 입력해주면, tsconfig.json이 생성됩니다. 다 지우고 필요한 옵션을 작성해줍니다.

{
  "compilerOptions": {
    "target": "es2022",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": ".",
    "baseUrl": "./src",
    "paths": {},
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "strict": true,
    "moduleResolution": "node",
    "skipLibCheck": true
  },
  "include": ["src/server.ts", "src/*/*.d.ts"],
  "exclude": ["node_modules"]
}

package.json

Script 부분이 test만 작성되어있습니다. 나머지 부분을 추가해보도록 합니다.

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc -b",
    "start": "node dist/sserver.js",
    "dev": "nodemon --exec \"ts-node\" ./server.ts"
  },

이 프로젝트의 실행 파일은 "main": "server.ts",입니다.

server.ts 파일을 생성 후 Hello World를 출력 해 봅시다.

Server.ts

import express, { Request, Response, NextFunction } from 'express';
const app = express();

app.get('/', (req: Request, res: Response) => {
  res.send('Hello World!');
});

app.listen(8888, () => {
  console.log(`타입스크립트 서버 시작`);
});

이제 npm run dev 혹은 npm run start로 웹 서버를 실행해봅시다.

profile
다시 처음부터 천천히... 급할필요가 없다.

0개의 댓글