Node.js 專案中的 TypeScript 結構

| Node.js | 4 Reads

針對 Node.js 專案中的 TypeScript 結構,會稍微不一樣,重點在於:

  • 模組系統通常是 CommonJS(或 ESM)

  • 入口是 src/index.ts

  • 通常會使用 ts-node-devnodemon + ts-node 來做開發時的即時執行

  • 常見會搭配 eslint, prettier 做格式與靜態檢查

  • 若有用到 Express、dotenv、第三方模組,還會搭配型別檔 (@types/xxx)


📁 Node.js + TypeScript 的推薦結構

your-node-app/
├── src/
│   ├── index.ts              # 入口檔
│   ├── routes/               # 路由(若用 Express)
│   └── services/             # 商業邏輯
├── dist/                     # 編譯後的 JS(不要手動修改)
├── .eslintrc.json            # ESLint 設定(可選)
├── .prettierrc               # Prettier 設定(可選)
├── .gitignore
├── package.json
├── tsconfig.json
└── README.md

⚙️ tsconfig.json 推薦設定(Node.js 專用)

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "outDir": "dist",
    "rootDir": "src",
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}

📦 package.json 的常見 script 與依賴

{
  "name": "my-node-ts-app",
  "version": "1.0.0",
  "main": "dist/index.js",
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "dev": "ts-node-dev --respawn src/index.ts",
    "lint": "eslint . --ext .ts"
  },
  "devDependencies": {
    "typescript": "^5.x",
    "ts-node-dev": "^2.x",
    "@types/node": "^20.x",
    "eslint": "^8.x",
    "prettier": "^3.x"
  }
}

ts-node-dev 是針對開發環境的工具,支援 hot reload。


👇 安裝步驟(一次到位)

npm init -y
npm install typescript ts-node-dev @types/node -D
npx tsc --init

🧪 常用命令(Node.js 專案)

命令 說明
npx tsc 編譯整個專案到 dist/
npm run dev 使用 ts-node-dev 啟動並監視變更
npm run build && npm start 正式編譯並執行
npx ts-node src/index.ts 快速測試單檔(不建議用於大型專案)

📌 其他常見搭配(選用)

套件 用途
express Web 框架(配合 @types/express
dotenv 環境變數支援
axios HTTP 請求工具
eslint, prettier 格式與靜態檢查
jest, ts-jest 單元測試

✅ 範例:最小可執行專案

// src/index.ts
console.log('Hello from Node + TypeScript!');

啟動:

npm run dev

TypeScript 專案的基本文件結構

「純 TypeScript 專案」與「Node.js + TypeScript 專案」的區別

🧨 差別總覽:Node.js vs TypeScript 在命令行的運行方式

返回目錄

This article was last edited at