************************** ubuntu 安裝 type script 在 Ubuntu 上安裝 TypeScript 非常簡單。你可以按照以下步驟操作: --- ### ✅ 安裝 TypeScript 的步驟 1. **安裝 Node.js 和 npm(如果尚未安裝)** 打開終端機,執行以下命令來安裝 Node.js 和 npm: ```bash sudo apt update sudo apt install nodejs npm -y ``` 確認安裝成功: ```bash node -v npm -v ``` 2. **使用 npm 安裝 TypeScript** 接著安裝 TypeScript: ```bash sudo npm install -g typescript ``` 驗證是否安裝成功: ```bash tsc -v ``` 如果你看到類似 `Version 5.x.x` 的輸出,表示安裝成功。 --- ### 🛠️ 額外建議 - 如果你使用的是 `pnpm`,也可以這樣安裝: ```bash pnpm add -g typescript ``` - 建議安裝 `ts-node` 來直接執行 TypeScript 檔案: ```bash sudo npm install -g ts-node ``` --- 需要我幫你建立一個簡單的 TypeScript 專案範例嗎?還是你想設定 `tsconfig.json`? ************************** 幫我建立 TypeScript 專案範例。 我已經幫你建立了一個基本的 TypeScript 專案結構,內容包括: ### 📁 專案結構 ``` typescript_project/ ├── tsconfig.json └── src/ └── index.ts ``` ### 📄 檔案內容 - **`src/index.ts`**: ```ts console.log('Hello, TypeScript'); ``` - **`tsconfig.json`**: ```json { "compilerOptions": { "target": "ES6", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src"] } ``` --- ### ▶️ 如何執行 1. 進入專案資料夾: ```bash cd typescript_project ``` 2. 編譯 TypeScript: ```bash tsc ``` 3. 執行編譯後的 JavaScript: ```bash node dist/index.js ``` (你可以在 `tsconfig.json` 中加入 `"outDir": "dist"` 來指定輸出資料夾) --- 需要我幫你加上 `package.json` 和 `npm` 腳本來簡化流程嗎? ********************** 幫我加上 package.json。 我已經幫你建立好 `package.json`,內容如下: ### 📦 `package.json` ```json { "name": "typescript_project", "version": "1.0.0", "description": "A simple TypeScript project", "main": "dist/index.js", "scripts": { "build": "tsc", "start": "node dist/index.js" }, "dependencies": {}, "devDependencies": { "typescript": "^5.0.0", "ts-node": "^10.0.0" }, "author": "", "license": "ISC" } ``` --- ### ✅ 下一步建議 1. 進入專案資料夾: ```bash cd typescript_project ``` 2. 安裝依賴: ```bash npm install ``` 3. 編譯 TypeScript: ```bash npm run build ``` 4. 執行程式: ```bash npm start ``` --- 需要我幫你加上 `nodemon` 來自動重啟開發伺服器嗎?還是要加上 `eslint` 或 `prettier` 做程式碼格式檢查? ********************************* 可以解釋 npm 腳本的功能嗎? 當然可以!在 `package.json` 中的 **npm 腳本(scripts)** 是一種方便的方式來定義和執行常見的命令,例如編譯 TypeScript、啟動伺服器、執行測試等。這些腳本可以透過 `npm run <腳本名稱>` 來執行。 --- ### 🧩 你目前的腳本解釋 ```json "scripts": { "build": "tsc", "start": "node dist/index.js" } ``` #### 1. `"build": "tsc"` - **功能**:執行 TypeScript 編譯器(`tsc`),根據 `tsconfig.json` 的設定,把 `.ts` 檔案編譯成 `.js`。 - **執行方式**: ```bash npm run build ``` #### 2. `"start": "node dist/index.js"` - **功能**:使用 Node.js 執行編譯後的 JavaScript 程式。 - **執行方式**: ```bash npm start ``` --- ### 🛠️ 常見的其他腳本範例 你可以根據需要加入更多腳本,例如: ```json "scripts": { "dev": "ts-node src/index.ts", "watch": "tsc -w", "lint": "eslint . --ext .ts", "format": "prettier --write ." } ``` | 腳本名稱 | 功能說明 | |----------|----------| | `dev` | 使用 `ts-node` 直接執行 TypeScript 程式(不需先編譯) | | `watch` | 監聽檔案變更,自動重新編譯 | | `lint` | 使用 ESLint 檢查程式碼品質 | | `format` | 使用 Prettier 自動格式化程式碼 | --- 需要我幫你加上 `dev` 或 `watch` 腳本,並安裝相關工具嗎?還是你想了解如何部署這個 TypeScript 專案?