跳至主要內容
Skip to content

Vue3 + Vite + TypeScript 專案建置

本篇將帶你從零開始建立一個 Vue3 + Vite + TypeScript 專案,並解析所有重要配置。


一、 建立專案

1.1 使用 create-vite

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

# 進入專案目錄
cd my-vue-app

# 安裝依賴
npm install

# 啟動開發伺服器
npm run dev

1.2 專案結構

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

二、 tsconfig.json 配置

2.1 完整配置

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

    'moduleResolution': 'bundler',
    'allowImportingTsExtensions': true,
    'resolveJsonModule': true,
    'isolatedModules': true,
    'noEmit': true,
    'jsx': 'preserve',

    'strict': true,
    'noUnusedLocals': true,
    'noUnusedParameters': true,
    'noFallthroughCasesInSwitch': true,

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

2.2 重要選項說明

選項說明
target編譯目標版本
module模組系統
strict嚴格模式
moduleResolution模組解析策略
paths路徑別名
include包含的檔案

三、 vite.config.ts 配置

3.1 基本配置

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"),
    },
  },
});

3.2 完整配置範例

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"),
      '@components': resolve(__dirname, 'src/components"),
      '@views': resolve(__dirname, 'src/views"),
      '@stores': resolve(__dirname, 'src/stores"),
    },
  },

  server: {
    port: 3000,
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '"),
      },
    },
  },

  build: {
    outDir: 'dist',
    sourcemap: true,
  },
});

四、 vite-env.d.ts

4.1 環境變數類型

typescript
/// <reference types='vite/client' />

interface ImportMetaEnv {
  readonly VITE_API_URL: string;
  readonly VITE_APP_TITLE: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

4.2 Vue 單檔元件類型

typescript
/// <reference types='vite/client' />

declare module '*.vue' {
  import type { DefineComponent } from "vue';
  const component: DefineComponent<{}, {}, any>;
  export default component;
}

五、 main.ts 入口

5.1 基本設定

typescript
import { createApp } from "vue';
import App from "./App.vue';

const app = createApp(App);

app.mount('#app");

5.2 完整設定

typescript
import { createApp } from "vue';
import { createPinia } from "pinia';
import router from "./router';
import App from "./App.vue';

import './style.css';

const app = createApp(App);

app.use(createPinia());
app.use(router);

app.mount('#app");

六、 目錄結構建議

6.1 推薦結構

src/
├── api/              # API 請求
│   └── index.ts
├── assets/           # 靜態資源
├── components/       # 共用元件
│   ├── common/
│   └── ui/
├── composables/      # 組合函式
│   └── useCounter.ts
├── layouts/          # 版面配置
│   └── DefaultLayout.vue
├── router/           # 路由
│   └── index.ts
├── stores/           # Pinia stores
│   └── user.ts
├── types/            # 類型定義
│   └── index.ts
├── utils/            # 工具函式
│   └── index.ts
├── views/            # 頁面
│   ├── Home.vue
│   └── About.vue
├── App.vue
├── main.ts
└── vite-env.d.ts

6.2 類型檔案

typescript
// src/types/index.ts
export interface User {
  id: number;
  name: string;
  email: string;
}

export interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

七、 ESLint + Prettier 配置

7.1 安裝依賴

bash
npm install -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
npm install -D eslint-plugin-vue
npm install -D prettier eslint-config-prettier eslint-plugin-prettier

7.2 .eslintrc.cjs

javascript
module.exports = {
  root: true,
  env: {
    browser: true,
    node: true,
    es2021: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:vue/vue3-recommended',
    'prettier',
  ],
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint', 'vue'],
  rules: {
    'vue/multi-word-component-names': 'off',
    '@typescript-eslint/no-unused-vars': 'warn',
  },
};

7.3 .prettierrc

json
{
  'semi': false,
  'singleQuote': true,
  'tabWidth': 2,
  'trailingComma': 'none',
  'printWidth': 100
}

八、 常見問題

8.1 路徑別名不生效

確保 tsconfig.jsonvite.config.ts 都有配置:

typescript
// vite.config.ts
resolve: {
  alias: {
    '@': resolve(__dirname, 'src')
  }
}
json
// tsconfig.json
{
  'compilerOptions': {
    'baseUrl': '.',
    'paths': {
      '@/*': ['src/*']
    }
  }
}

8.2 Vue 類型錯誤

安裝 Vue 語言服務:

bash
npm install -D vue-tsc

8.3 自動匯入

使用 unplugin-auto-import

bash
npm install -D unplugin-auto-import unplugin-vue-components
typescript
// vite.config.ts
import AutoImport from "unplugin-auto-import/vite';
import Components from "unplugin-vue-components/vite';

export default defineConfig({
  plugins: [
    vue(),
    AutoImport({
      imports: ['vue', 'vue-router', 'pinia'],
      dts: 'src/auto-imports.d.ts',
    }),
    Components({
      dts: 'src/components.d.ts',
    }),
  ],
});

總結

檔案用途
tsconfig.jsonTypeScript 配置
vite.config.tsVite 打包配置
vite-env.d.ts環境變數類型
main.ts應用入口
.eslintrc.cjsESLint 配置
.prettierrcPrettier 配置

> **推薦工具**:

  • VS Code + Volar 擴充
  • vue-tsc 類型檢查
  • unplugin-auto-import 自動匯入

進階挑戰

  1. 配置多個環境(development、staging、production)
  2. 設定 GitHub Actions CI/CD
  3. 加入 Vitest 測試框架

延伸閱讀與資源