跳至主要內容
Skip to content

TypeScript 環境建置:Node、Vite、Playground

工欲善其事,必先利其器。本篇將帶你建立完整的 TypeScript 開發環境。


一、 Node.js + TypeScript

1.1 全域安裝 TypeScript

bash
# 安裝 TypeScript 編譯器
npm install -g typescript

# 檢查版本
tsc --version
# Version 5.x.x

1.2 第一個 TypeScript 檔案

typescript
// hello.ts
function greet(name: string): string {
  return `Hello, ${name}!`
}

console.log(greet('TypeScript'))

1.3 編譯與執行

bash
# 編譯成 JavaScript
tsc hello.ts

# 執行
node hello.js
# Hello, TypeScript!

1.4 使用 ts-node(直接執行)

bash
# 安裝 ts-node
npm install -g ts-node

# 直接執行 TypeScript
ts-node hello.ts
# Hello, TypeScript!

二、 專案初始化

2.1 建立專案

bash
mkdir my-ts-project
cd my-ts-project
npm init -y

2.2 安裝 TypeScript(專案內)

bash
npm install typescript --save-dev

2.3 初始化 tsconfig.json

bash
npx tsc --init

這會產生一個 tsconfig.json 配置檔。

2.4 基礎 tsconfig.json

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

2.5 目錄結構

my-ts-project/
├── src/
│   └── index.ts
├── dist/           # 編譯輸出
├── package.json
└── tsconfig.json

三、 Vite + TypeScript

3.1 建立 Vite + Vue + TS 專案

bash
# 建立專案
npm create vite@latest my-vue-app -- --template vue-ts

# 進入專案
cd my-vue-app

# 安裝依賴
npm install

# 啟動開發伺服器
npm run dev

3.2 專案結構

my-vue-app/
├── src/
│   ├── App.vue
│   ├── main.ts
│   ├── vite-env.d.ts
│   └── components/
├── public/
├── index.html
├── package.json
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts

3.3 tsconfig.json(Vite 專案)

json
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,

    /* Paths */
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

3.4 vite.config.ts

typescript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
    },
  },
})

四、 TypeScript Playground

4.1 線上練習

官方 Playground:typescriptlang.org/play

功能

  • 即時編譯預覽
  • 錯誤提示
  • 輸出 JavaScript 對照
  • 分享連結

4.2 使用場景

場景適用工具
快速測試語法Playground
學習新特性Playground
實際專案開發Vite / Node
分享程式碼Playground

五、 VSCode 配置

5.1 必備插件

插件用途
TypeScript Vue Plugin (Volar)Vue + TS 支援
ESLint程式碼檢查
Prettier程式碼格式化
Error Lens行內錯誤顯示

5.2 settings.json 推薦配置

json
{
  "typescript.preferences.includePackageJsonAutoImports": "on",
  "typescript.suggest.autoImports": true,
  "typescript.updateImportsOnFileMove.enabled": "always",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode"
}

六、 ts-node 開發模式

6.1 安裝

bash
npm install -D ts-node typescript @types/node

6.2 搭配 nodemon 熱重載

bash
npm install -D nodemon

6.3 package.json 腳本

json
{
  "scripts": {
    "dev": "nodemon --exec ts-node src/index.ts",
    "build": "tsc",
    "start": "node dist/index.js"
  }
}

6.4 nodemon.json 配置

json
{
  "watch": ["src"],
  "ext": "ts,json",
  "ignore": ["src/**/*.spec.ts"],
  "exec": "ts-node ./src/index.ts"
}

七、 常見問題

7.1 找不到模組

bash
# 安裝類型定義
npm install -D @types/node
npm install -D @types/express

7.2 ESM 模式

json
// package.json
{
  "type": "module"
}

// tsconfig.json
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Node"
  }
}

7.3 路徑別名不生效

除了 tsconfig.json,還需要在打包工具配置:

typescript
// vite.config.ts
import { resolve } from 'path'

export default {
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
    },
  },
}

總結

方式適用場景啟動速度
Playground學習、測試即時
ts-nodeNode.js 開發
Vite + TS前端專案極快
tsc 編譯生產環境

> **推薦**:

  • 學習用 Playground
  • 前端專案用 Vite
  • 後端開發用 ts-node + nodemon

進階挑戰

  1. 使用 npm create vite@latest 建立一個 Vue + TypeScript 專案
  2. 確認 .vue 檔案內可以使用 TypeScript
  3. 新增路徑別名 @,並測試是否正常運作

延伸閱讀與資源