✅ Express + TypeScript 적용 방법
1️⃣ TypeScript 환경 설정
프로젝트 디렉토리에서 TypeScript 및 필요한 패키지 설치
npm init -y # (선택) package.json 생성 npm install express cors dotenv # Express 및 필수 라이브러리 npm install --save-dev typescript ts-node @types/node @types/express @types/cors
2️⃣ tsconfig.json 설정
루트 디렉토리에 tsconfig.json 파일 생성
{ "compilerOptions": { "target": "ES6", "module": "CommonJS", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "resolveJsonModule": true }, "include": ["src"] }
3️⃣ Express TypeScript 서버 코드 (src/server.ts)
import express, { Request, Response, Application } from "express"; import cors from "cors"; import dotenv from "dotenv"; dotenv.config(); const app: Application = express(); const PORT = process.env.PORT || 5000; // 미들웨어 설정 app.use(express.json()); app.use(cors()); // 기본 API 라우트 app.get("/", (req: Request, res: Response) => { res.json({ status: 200, success: true, message: "Express with TypeScript!" }); }); // 서버 실행 app.listen(PORT, () => { console.log(`???? Server running on http://localhost:${PORT}`); });
4️⃣ 실행 스크립트 추가 (package.json)
"scripts": { "dev": "ts-node src/server.ts", "build": "tsc", "start": "node dist/server.js" }
5️⃣ 서버 실행
npm run dev # 개발 모드 실행 npm run build # TypeScript 코드 컴파일 npm start # 빌드된 JS 파일 실행
✅ Express에서 TypeScript를 사용해야 하는 이유
- 타입 안정성 → Request, Response, NextFunction 타입 지원
- 자동 완성 & 코드 가이드 → 개발 생산성 향상
- 유지보수 용이 → 대규모 프로젝트에서 코드 품질 유지
- 에러 방지 → 런타임 오류를 컴파일 단계에서 방지
댓글 ( 0)
댓글 남기기