Programming language/Typescript

Typescript 맛보기 2 - 백엔드 Koa 개발환경 설정

iKay 2019. 11. 1. 23:06
반응형

0. 서론

 

지난 번 Typescript 맛보기 1(https://kay0426.tistory.com/39?category=822492)에 이어, 이번에는 Typescript로 백엔드 개발환경을 간단히 구축해 보겠다. 백엔드 웹 프레임워크로 Koa(https://koajs.com/)를 사용할 예정이다.  

 

 

1. Koa란?

 

Koa는 node.js 환경 웹 프레임워크로써 express에 이어 요즘 주목을 받고 있다. 그래서 node.js 백엔드 개발자라면 한 번 쯤은 Koa에 대해 들어봤을 것이고, 못 들어 봤다면 한 번쯤 관심을 가져보는 것도 좋을 듯 하다.

 

Koa 웹페이지에서 다음과 같이 Koa를 소개하고 있다.

 

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within its core, and it provides an elegant suite of methods that make writing servers fast and enjoyable.

 

이번 포스팅은 Koa에 관한 내용이 아니라서 이만 줄이도록 한다. Koa와 관련해서는 따로 포스팅하는 것도 좋을 것 같다. 

 

2. Koa 설치

a. node.js 프로젝트를 초기화

$ npm init -y

 

b. koa를 설치

$ npm i -S koa

 

c. 소스코드 작성

src/index.js를 만들고, 아래 내용을 copy & paste 한다. 

// src/index.js

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);
console.log('start koa server at http://localhost:3000');

 

코드가 제대로 동작하는지 확인해보자. 먼저 웹 서버를 실행시키자

$ node src/index.js
>> start koa server at http://localhost:3000

 

웹 브라우저에서 'http://localhost:3000'으로 접속해보자. 아래와 같이 웹 브라우저가 Hello World를 출력한다면 정상이다. 

[그림1] http://localhost:3000 

 

3. Typescript 환경 설정하기

$ npm i -D typscript ts-node @types/koa

- typescript: 프로젝트에서 Typescript를 사용할 수 있게 한다.

- ts-node: Typescript 코드를 Javascript로 컴파일 시키지 않고도 실행할 수 있게 한다. 따라서 개발 환경에서 번거롭게 웹팩 등으로 빌드하지 않아도 된다. ts-node에 대해 더 알고 싶다면, https://www.npmjs.com/package/ts-node 를 살펴보자. 

- @types/koa: koa에 대한 type check를 한다. 

 

그 후에 Typescript 설정을 한다.

$ tsc --init
// tsconfig.json

{
  "compilerOptions": {
      "module": "commonjs",
      "target": "es6",
      "noImplicitAny": true,
      "removeComments": true,
      "preserveConstEnums": true,
      "sourceMap": true
  },
  "include": [
      "src/**/*"
  ],
  "exclude": [
      "node_modules",
      "**/*.spec.ts"
  ]
}

 

src/index.js 파일을 아래와 같이 typescript 코드로 수정하고, src/index.ts로 변경한다. 

// src/index.ts

import * as Koa from 'koa';
const app = new Koa();

app.use(async (ctx: { body: string }, next: () => void ) => {
  const msg: string = 'Hello World';
  ctx.body = msg;
  next();
});

app.listen(3000);
console.log('start koa server at http://localhost:3000');

아래 명령어를 입력하면 typescript 코드를 바로 실행시킬 수 있다. 

$ npx ts-node src/index/ts
>> start koa server at http://localhost:3000

조금 더 간편한 개발환경을 갖추기 위해서는 nodemon을 사용하는 것도 좋다. nodemon은 watch하고 있어, 소스코드 파일이 변경 후 저장될 때 마다 재실행 시켜준다. 

 

nodemon을 설치하자.

$ npm i -D nodemon // nodemon을 devDependencies에 설치

 

nodemon을 간편하게 실행시키기 위해 package.json의 scripts에 아래와 같이 start 속성을 등록해 주자. 

 // package.json
 
 "scripts": {
    "start": "nodemon --watch src --delay 500ms --exec 'ts-node' src/index.ts",
    ...
 },

- watch : 디렉토리의 변경을 감지. 위의 경우는 src 디렉토리의 변경을 감지한다.

- delay: 재시작 시키는 delay. 위와 같은 경우는 서버 재시작은 500ms 뒤에 한다.

- exec: 실행 명령어. ts-node가 동작하도록 등록함.

 

 

만약 Typescript를 설치하고 설정하는 더 자세한 방법이 궁금하다면 여기(https://kay0426.tistory.com/39?category=822492)를 보면 될 것 같다. 

 

 

4, 결론

nodejs 백엔드에 Typescipt 환경을 설정하는 것은 생각보다 간단하다. Javascript보다 Typescript를 사용함으로써 얻는 이득이 더 많으므로 프로젝트 초반에 손이 좀 가더라도 Typescript 설정을 하는 것을 추천한다. 

 

반응형