오늘은 TypeScript로 express 환경설정을 해보았다.
TypeScript는 평소에 많이 들었지만 한 번도 사용해본 적이 없었습니다.
그래서 이번 기회를 통해 직접 환경설정을 해보고 TypeScript를 이해해 보려고 합니다.
우선 typescript를 global로 설치를 한다. 만약 global로 설치를 원치 않는다면 넘어가도 됩니다.
$ npm install -g typescript
$ mkdir ts-express && cd ts-express
$ npm init -y
이렇게 프로젝트를 만들고 해당 디렉터리에 package.json을 만들었다면 TypeScript와 express를 위한 모듈을 설치할 차례입니다.
우선 express와 로그를 콘솔로 확인 할 수 있는 morgan을 설치하고 TypeScript를 사용하기 위해 필요한 모듈들을 설치합니다.
$ npm install express morgan
$ npm install -D typescript ts-node @types/express @types/node @types/morgan
모듈들의 설치가 모두 끝났다면 tsConfig.json를 root 디렉터리에 만들어 설정을 해 줘야합니다.
$ tsc -init
//글로벌로 설치하지 않았다면 아래 방법으로 하면된다.
$ npx tsc -init
tsConfig.json파일이 생성되었다면 열어서 설정해야 합니다.
여기서 tsConfig.json이 해주는 역할은 TypeScript는 브라우저가 이해할 수 없습니다. 하지만 JavaScript는 브라우저가 이해할 수 있는 언어이죠. 그래서 TypeScript를 브라우저가 이해할 수 있도록 JavaScript로 컴파일링 해줘야 합니다. 이때 필요한 게 tsConfig.json입니다.
즉, tsConfig.json은 TypeScript를 JavaScript로 컴파일해 주는 컴파일러의 역할을 수행하게 됩니다.
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true
},
"include": ["src/*.ts"]
}
{
"name": "ts-express",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node dist/app.js", // npm run build 후 컴파일된 dist 디렉토리에 app.js를 실행 시킵니다.
"start:dev": "nodemon src/app.ts", // app.ts파일을 실행합니다.
"build": "tsc -p ."// npm run build실행시 컴파일을 실행합니다.
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^8.2.0",
"express": "^4.17.1",
"morgan": "^1.10.0"
},
"devDependencies": {
"@types/express": "^4.17.8",
"@types/morgan": "^1.9.2",
"@types/node": "^14.14.6",
"nodemon": "^2.0.6",
"ts-node": "^9.0.0",
"typescript": "^4.0.5"
}
}
이제 모든 기본적인 설정은 모두 끝이 났습니다. 그럼 이제 서버를 만들어야 합니다.
// src/app.ts
import 'dotenv/config';
import * as express from 'express';
import * as morgan from 'morgan';
const app: express.Application = express();
const {PORT} = process.env
app.use(morgan('dev'));
app.get('/', (req: express.Request, res: express.Response) => {
res.json({
message: 'Hello TypeScript!',
});
});
app.listen(PORT, () => {
console.log(`Example app listening at http://localhost:${PORT}`);
});
실행하기 전 최상위 디렉토리에 .env파일을 만들어 PORT를 지정해 놨습니다.
// .env
PORT=8080
$ npm run start:dev
app.ts를 실행하게 되면 콘솔에 아래와 같이 보이게 됩니다.
이후 브라우저나 Postman에서 http://localhost:8080
으로 접속을 하면 아래와 같이 입력한 데이터가 보이게 됩니다.
이상으로 TypeScript를 사용하여 express로 서버를 만들어 보았습니다!