📝 TypeScript 全局 vs 局部安裝、更新、卸載完整指南
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/1175
在使用 Node.js + TypeScript 開發時,常常會遇到 TypeScript 是安裝在「全局」還是「局部」的問題,這篇文章將系統性整理相關指令與行為差異,幫助你理解並正確使用 tsc 與 npx tsc。
📦 全局 vs 局部安裝 TypeScript 對照表
| 操作項目 | 全局 (Global) | 局部 (Local / 專案內) |
|---|---|---|
| ✅ 安裝 | npm install -g typescript |
npm install --save-dev typescript |
| 🔄 更新 | npm install -g typescript(覆蓋安裝) |
npm update typescript或npm install typescript@latest --save-dev |
| ❌ 卸載 | npm uninstall -g typescript |
npm uninstall typescript |
| 🔍 檢查版本 | tsc --version(全局) |
npx tsc --version(本地,無則 fallback 全局) |
| 🔧 執行方式 | tsc(執行全局) |
npx tsc(優先執行本地) |
| 安裝路徑 | npm root -g(如:Roaming\npm) |
./node_modules/typescript |
| 使用時機 | 快速測試、非專案用途 | 專案開發,版本可控 |
| 配置檔案 | 無自動生成 | 搭配 tsconfig.json 一起使用 |
🚀 為何推薦使用局部 + npx tsc
雖然全局安裝後可直接執行 tsc,但這會造成以下風險:
-
無法保證與其他專案使用相同版本;
-
不同人開發可能出現版本差異導致錯誤;
-
環境無法還原(例如 CI/CD)。
所以最佳實務是:
🔒 「專案內局部安裝 TypeScript + 使用
npx tsc編譯」
⚙️ tsc vs npx tsc 差異解釋
| 指令 | 說明 |
|---|---|
tsc |
執行全局安裝的 TypeScript 編譯器。與當前專案無關 |
npx tsc |
會先查找當前專案 node_modules/.bin/tsc,無則 fallback 到全局版本 |
🔍 可能出現的迷思
❓「我沒裝全局也能直接打
tsc?」
✅ 可能是因為:
-
你的某個工具或 shell(如 VSCode、某些腳手架)幫你加了
node_modules/.bin到 PATH; -
你實際上裝了全局版本但忘了。
👉 檢查用:
where tsc # Windows
which tsc # macOS / Linux
📌 如何確認 npx 實際用的是誰
想知道 npx tsc 執行的到底是哪個版本,可以用這招:
npx --no-install tsc --version
這會:
-
只使用本地已安裝的
tsc; -
若本地沒安裝,會報錯,不會 fallback 到全局(可用來驗證)。
🧪 總結與建議實務流程
| 操作目標 | 推薦做法 |
|---|---|
| 建立 TypeScript 專案 | npm install --save-dev typescriptnpx tsc --init |
| 編譯 TypeScript 專案 | npx tsc |
| 檢查版本(不受全局干擾) | npx tsc --version |
| 快速測試 TS 功能 | 安裝全局版本 + 用 tsc |
| 移除 TypeScript(乾淨) | npm uninstall -g typescript 和/或 npm uninstall typescript |
🧰 Bonus:快速列出全局與局部的 tsc 路徑與版本
# Windows PowerShell 版本
Write-Host "Global tsc:"; where tsc
Write-Host "Local tsc (if any):"; if (Test-Path ".\node_modules\.bin\tsc") { .\node_modules\.bin\tsc --version }
# Unix/macOS 版本
echo "Global tsc:"; which tsc
echo "Local tsc (if any):"; [ -x "./node_modules/.bin/tsc" ] && ./node_modules/.bin/tsc --version
如果你覺得這篇實用,別忘了把它加入書籤,或轉發給還在糾結 tsc 和 npx tsc 的夥伴 😄
→返回目錄
This article was last edited at