TypeScript 自動編譯與自動執行實戰:深入理解 tsc --watch + nodemon
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1178
在用 TypeScript 開發 Node.js 應用時,你是否曾經覺得很煩:
-
每次改完
.ts
檔案還要手動編譯? -
.js
編譯完之後還得自己重新執行一次 Node? -
能不能像 Visual Studio 那樣「邊改邊執行」?
答案是 —— 可以,但要靠兩個好工具幫忙:tsc --watch
和 nodemon
。
🔧 一、tsc --watch
是什麼?
tsc
是 TypeScript 的編譯器指令。
加入 --watch
選項後,會開啟「監聽模式」:
tsc --watch
✅ 它會做什麼?
-
持續監控你所有
.ts
檔案 -
一旦檔案改變,就自動重新編譯成
.js
-
編譯後的結果會輸出到你在
tsconfig.json
中設定的outDir
,如dist/
❌ 它不會做什麼?
-
不會執行你的程式
-
不會重新啟動 Node.js
也就是說,它只解決了「自動編譯」的問題,還不夠。
🚀 二、nodemon
是什麼?
nodemon
是一個 Node.js 應用監視器,全名是 Node Monitor。
安裝方式:
npm install --save-dev nodemon
✅ 它會做什麼?
-
監控
.js
檔案變化 -
一旦檔案有變動,就自動重新啟動 Node.js 應用
❌ 它不會做什麼?
-
不會編譯
.ts
→.js
-
它不認識 TypeScript,需要配合已經編譯好的
.js
來執行
🔁 三、為什麼要搭配使用?
因為 TypeScript 是 .ts
,而 Node.js 執行的是 .js
。
所以開發過程中我們需要:
工具 | 負責的任務 |
---|---|
tsc --watch |
持續編譯 .ts → .js |
nodemon |
監聽 .js 改動並自動執行 |
兩者結合,才能實現我們夢寐以求的「改一行程式 → 自動編譯 → 自動執行」的效果。
🛠️ 四、實戰配置:怎麼用?
📁 假設專案結構如下:
my-app/
├── src/
│ └── index.ts
├── dist/
├── tsconfig.json
└── package.json
✅ tsconfig.json 設定(重點是 outDir)
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDir": "./src",
"outDir": "./dist",
"strict": true
},
"include": ["src"]
}
✅ index.ts 範例
// src/index.ts
console.log("Hello, TypeScript + nodemon!");
👣 開兩個終端機:
1️⃣ 終端機 A:監聽 TypeScript 變更並編譯
npx tsc --watch
2️⃣ 終端機 B:監聽 JavaScript 執行並重啟
npx nodemon dist/index.js
🎉 現在你只要一改 index.ts
,整個流程就會自動跑起來!
🧠 五、懶人一鍵啟動:用 npm scripts 整合
安裝額外套件:
npm install --save-dev concurrently
然後在 package.json
加入:
"scripts": {
"dev:ts": "tsc --watch",
"dev:run": "nodemon dist/index.js",
"dev": "concurrently \"npm run dev:ts\" \"npm run dev:run\""
}
✅ 執行時只需要:
npm run dev
就會同時開啟兩個監聽流程:一邊編譯、一邊執行,乾淨俐落。
📦 延伸選項:用 ts-node-dev
一體化處理
如果你想連 .js
都不產生,只寫 .ts
就能跑,推薦:
npm install --save-dev ts-node-dev
在 package.json
裡加:
"scripts": {
"dev": "ts-node-dev --respawn src/index.ts"
}
執行:
npm run dev
✅ 就能做到「即時編譯 + 即時執行」,甚至不用生成
dist/
✅ 總結一下
工具 | 功能 | 備註 |
---|---|---|
tsc --watch |
自動編譯 .ts → .js |
不會執行程式 |
nodemon |
自動執行 .js ,並監聽變更 |
不會編譯 .ts |
concurrently |
同時執行兩個命令 | 搭配 npm run 更方便 |
ts-node-dev |
一體式即時編譯 + 執行 | 不產生 .js ,適合開發階段 |
📘 給初學者的小建議
-
想清楚你是要編譯
.ts
後部署,還是只在本地跑.ts
-
如果你要輸出
.js
給其他人用(如伺服器、打包),就用tsc --watch
+nodemon
-
如果你只是自己開發測試工具,想省事,就用
ts-node-dev
→返回目錄
This article was last edited at