# TypeScript로 개발하는 Express

- Author: @baealex
- Published: 2020-06-18
- Updated: 2021-06-03
- Source: http://blex.me/@baealex/typescript%EB%A1%9C-%EA%B0%9C%EB%B0%9C%ED%95%98%EB%8A%94-express
- Tags: 백엔드, 타입스크립트

---

얼마전 장고에서 `typescript`를 사용하기 시작했는데 상당히 맘에드는 친구라서 본격적으로 `typescript`를 활용하고 싶어졌다. 일단 가장 만만한 `express`의 개발 환경을 `ts`로 구축해보면 다른 것도 대강은 구축이 수월할 것이라 생각된다.

<br>

#### 패키지 설치

```bash
npm install -g typescript
npm init -y
npm install --save express
npm install --save-dev @types/node @types/express
``` 

> `@types`가 붙은 패키지는 `/`뒤에 나열된 패키지의 `type`을 제공하므로 유용하다. 가령 `express`의 응답는 다음과 같은 type을 가지고 있다고 알려준다.

```ts
interface Response<ResBody = any> import Response
```

<br>

#### 타입스크립트 설정

```bash
tsc --init
```

위 명령을 시도하면 `tsconfig.json` 파일이 생성되는데 열어보면 엄청난 옵션들이 주석처리 되어있다. 자세한 설정은 잘 모르겠고 지금 당장 필요한 부분은

```ts
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": [
    "src/**/*"
  ]
}
```

이정도다. 이제 `tsc`라는 명령어를 입력하면 `src`에 있는 `ts` 파일들은 컴파일 후 `es5` 문법으로 `dist`에 생성된다. 이와같은 환경을 만든 뒤 `package.json`의 `script`에 다음 내용을 추가한다.

```ts
"start": "tsc && node dist"
```

`tsc` 명령으로 모두 컴파일하고 `node dist`의 `index.js`를 실행하게 된다. 간단하게 `src` 디렉터리에 다음 `index.ts` 파일을 생성해보자.

```ts
import express, { Request, Response } from 'express';

let server = express();

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

server.listen(3000, () => {
    console.log('http server listen on :3000');
});
```

이제 아래 명령어를 입력하여 `express` 서버를 실행할 수 있다.

```ts
npm start
```

<br>

#### 패키지 추가

코드를 변경할때 마다 수시로 컴파일 후 실행하는 건 상당히 귀찮은 일이다. `React`와 같은 프레임워크는 소스를 수정하면 자동으로 반영되고 브라우저가 리프레시 되는데 `nodemon`이라는 패키지를 활용하면 우리의 프로젝트에서도 비슷한 느낌을 받을 수 있다.

```bash
npm install --save-dev nodemon ts-node
```

위 두가지 패키지를 추가적으로 받아준 뒤 아까 만들었던 `package.json`의 `script`의 내용을 수정해주자.

```js
"start": "nodemon --watch src --delay 1 --exec ts-node src/index.ts"
```

아까와 똑같이 프로젝트를 실행한 뒤 소스를 수정하면 서버가 스스로 재시작되는 것을 확인할 수 있다.

@gif[https://static.blex.me/images/content/2020/6/9/baealex/21_f4kqXi4pYYrMHDjLjyyl.mp4]
