본문으로 건너뛰기
Advertisement

13.1 Node.js TS 환경 — tsx, ts-node, @types/node 설정

Node.js TypeScript 환경 구성

Node.js에서 TypeScript를 사용하는 방법은 크게 세 가지입니다.

방법설명추천 시기
tsxesbuild 기반, 빠름, 타입 체크 없음개발 서버, 스크립트
ts-nodetsc 기반, 타입 체크 포함, 느림간단한 실행
tsc + node빌드 후 실행, 프로덕션 안전프로덕션 배포

@types/node 설치

npm install --save-dev @types/node typescript
// tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS", // 또는 NodeNext
"moduleResolution": "node", // 또는 NodeNext
"lib": ["ES2022"],
"types": ["node"], // Node.js 타입 포함
"strict": true,
"esModuleInterop": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}

tsx로 개발 환경 구성

npm install --save-dev tsx
// package.json
{
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"typecheck": "tsc --noEmit"
}
}
// src/index.ts
import { createServer } from 'http'
import { readFileSync } from 'fs'
import path from 'path'

// @types/node 덕분에 타입 완전 지원
const port = parseInt(process.env.PORT ?? '3000')

const server = createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ message: 'Hello TypeScript!' }))
})

server.listen(port, () => {
console.log(`서버 실행 중: http://localhost:${port}`)
})

ESM Node.js 설정

// package.json
{
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}
}
// tsconfig.json (ESM)
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"outDir": "./dist"
}
}
// ESM에서는 .js 확장자 필수
import { helper } from './utils/helper.js'
import express from 'express'

모듈 해석 설정 비교

// CJS (전통적인 Node.js)
{
"module": "CommonJS",
"moduleResolution": "node"
}

// ESM (최신 Node.js)
{
"module": "NodeNext",
"moduleResolution": "NodeNext"
}

package.json의 exports 필드

{
"name": "my-package",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts"
},
"./utils": {
"import": "./dist/utils.mjs",
"require": "./dist/utils.cjs"
}
}
}

실전 Node.js 프로젝트 구조

my-api/
├── src/
│ ├── index.ts # 진입점
│ ├── config/
│ │ └── env.ts # 환경변수
│ ├── middleware/
│ │ ├── auth.ts
│ │ └── error.ts
│ ├── routes/
│ │ └── user.ts
│ ├── services/
│ │ └── user.service.ts
│ ├── repositories/
│ │ └── user.repo.ts
│ └── types/
│ └── index.ts
├── tsconfig.json
└── package.json
// src/index.ts
import express from 'express'
import { env } from './config/env'
import { userRouter } from './routes/user'
import { errorMiddleware } from './middleware/error'

const app = express()

app.use(express.json())
app.use('/api/users', userRouter)
app.use(errorMiddleware)

app.listen(env.PORT, () => {
console.log(`🚀 서버 실행: http://localhost:${env.PORT}`)
})

고수 팁

Node.js 버전별 내장 ESM 지원

Node.js 12+: 실험적 ESM 지원
Node.js 16+: 안정적 ESM 지원
Node.js 18+: fetch API 내장
Node.js 20+: 권장 LTS

타입 버전 일치

# Node.js 버전에 맞는 @types/node 설치
npm install --save-dev @types/node@20 # Node.js 20 LTS
Advertisement