TypeScript 專案的基本文件結構
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/1167
以下是 TypeScript 項目的基本文件結構 以及 常用的命令行工具與用法,不講語法,只講你作為開發者需要掌握的結構與操作。
📁 TypeScript 專案的基本文件結構
一個典型的 TypeScript 項目會像這樣:
your-project/
├── src/ # 原始 TypeScript 檔案目錄
│ └── index.ts # 入口檔案
├── dist/ # 編譯後輸出的 JavaScript(自動生成)
│ └── index.js
├── node_modules/ # 依賴包(npm install 後生成)
├── tsconfig.json # TypeScript 設定檔
├── package.json # 項目描述與依賴
└── package-lock.json # 鎖定依賴版本(自動生成)
⚙️ tsconfig.json(最基本配置)
這是 TypeScript 的核心設定檔。初始化時使用:
npx tsc --init
常見的內容如下:
{
"compilerOptions": {
"target": "ES2020", // 輸出 JS 的語法版本
"module": "CommonJS", // Node.js 模組系統
"outDir": "dist", // 編譯後的輸出資料夾
"rootDir": "src", // 原始碼目錄
"strict": true, // 嚴格模式
"esModuleInterop": true, // 允許導入 CommonJS 模組
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}
📦 package.json 典型內容
{
"name": "your-project",
"version": "1.0.0",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node src/index.ts"
},
"devDependencies": {
"typescript": "^5.4.0",
"ts-node": "^10.9.2"
}
}
🧪 常用命令行總結
📁 初始化 TypeScript 專案
npm init -y # 建立 package.json
npm install typescript -D # 安裝 TypeScript(開發依賴)
npx tsc --init # 建立 tsconfig.json
🔧 編譯 TypeScript
npx tsc # 根據 tsconfig.json 編譯整個專案
npx tsc src/foo.ts # 單個文件編譯
🚀 執行 TypeScript(不經編譯)
npx ts-node src/index.ts # 直接執行 .ts 檔案(需安裝 ts-node)
👷 常用 NPM 命令(在 package.json 中定義)
npm run build # 執行編譯
npm run start # 執行編譯後的 JS
npm run dev # 直接執行 TS 檔(快速開發)
🔍 安裝型別定義(如用到第三方 JS 套件)
npm install lodash
npm install @types/lodash -D
✅ 常見實用工具
工具 | 功能說明 |
---|---|
ts-node |
直接執行 .ts 檔案(免編譯) |
nodemon |
自動重啟(搭配 ts-node ) |
rimraf |
刪除資料夾(類似 rm -rf ) |
eslint |
靜態檢查 |
prettier |
程式碼格式化 |
如果你是在 Node.js 項目中用 TypeScript,這裏是其結構差異→Node.js 專案中的 TypeScript 結構
→「純 TypeScript 專案」與「Node.js + TypeScript 專案」的區別
→🧨 差別總覽:Node.js vs TypeScript 在命令行的運行方式
→返回目錄
This article was last edited at