요 근래 타입스크립트 입지가 계속해서 확산되고있습니다. 보통 타입스크립트로 웹 서버를 작성하기 위해서 NestJS
라는 프레임워크를 사용했지만, Epxress
에서도 사용하도록 타입을 지원하는 라이브러리들이 많이 추가되었습니다.
npm i -g typescript
타입스크립트 프로젝트를 시작하기 위해 전역에 typescript
를 설치 해 줍니다.
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
: 서버 파일을 수정할 때마다 자동으로 재실행 해줍니다.
프로젝트 디렉토리내에서 터미널에 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"]
}
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
를 출력 해 봅시다.
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
로 웹 서버를 실행해봅시다.