跳轉到內容

Vite 構建工具完全指南 2026

Vite 構建工具

💡 什麼是 Vite? Vite 是新一代前端構建工具,由 Vue.js 作者尤雨溪開發。它利用瀏覽器原生 ES 模塊支持,實現了極速的開發服務器啟動和熱更新,生產環境則使用 Rollup 進行打包。Vite 的出現,徹底改變了前端開發的體驗。

本文將帶你從 0 到 1 掌握 Vite:

  • ✅ Vite 核心原理與優勢
  • ✅ 項目創建與基礎配置
  • ✅ 常用功能與插件使用
  • ✅ 性能優化最佳實踐
  • ✅ 生產構建與部署
  • ✅ 從 Webpack 遷移指南
  • ✅ 常見問題與解決方案

一、Vite 基礎

1.1 為什麼選擇 Vite

傳統構建工具(如 Webpack)在開發時需要打包整個應用,項目越大,啟動越慢。Vite 從根本上改變了這一模式。

特性ViteWebpack說明
啟動速度⚡ 毫秒級🐢 秒級甚至分鐘級Vite 無需打包,按需編譯
熱更新速度⚡ 即時更新🐢 隨項目增大變慢Vite 只更新變更模塊
構建速度⚡ Rollup 驅動🐢 較慢Rollup 比 Webpack 更快
配置複雜度📝 簡單📝📝📝 複雜Vite 開箱即用
生態成熟度📦 快速增長📦📦📦 非常成熟Webpack 生態更豐富
ESM 支持✅ 原生支持⚠️ 需要配置Vite 基於 ESM 設計

1.2 Vite 核心原理

開發環境:

  • 利用瀏覽器原生 ES Modules 支持
  • 啟動時不打包,按需編譯文件
  • 模塊熱替換(HMR)在原生 ESM 上執行
  • 預構建依賴,提升頁面加載速度

生產環境:

  • 使用 Rollup 打包代碼
  • 高度優化的輸出
  • 支持代碼分割、Tree Shaking 等

💡 關鍵區別: Webpack 是「先打包,再服務」;Vite 是「先服務,按需編譯」。

1.3 瀏覽器支持

  • 開發環境: 支持原生 ESM 的現代瀏覽器(Chrome 61+、Firefox 60+、Safari 11+、Edge 16+)
  • 生產環境: 通過配置可支持到傳統瀏覽器(需要 @vitejs/plugin-legacy)

二、快速開始

2.1 環境要求

  • Node.js: 18+ 或 20+(推薦 LTS 版本)
  • 包管理器: npm / yarn / pnpm(推薦 pnpm)
  • 操作系統: Windows / macOS / Linux
bash
# 檢查 Node.js 版本
node -v

# 如果版本過低,使用 nvm 升級
nvm install --lts
nvm use --lts

2.2 創建項目

bash
npm create vite@latest
bash
yarn create vite
bash
pnpm create vite
bash
bun create vite

交互式創建流程:

bash
# 1. 輸入項目名
Project name: my-vite-app

# 2. 選擇框架
Select a framework:
  Vanilla
  Vue
  React
  Preact
  Lit
  Svelte
  Solid
  Qwik
  React TypeScript
  Vue TypeScript
  ...

# 3. 選擇語言變體
Select a variant:
  JavaScript
  TypeScript
  TypeScript + SWC

# 4. 完成創建,進入項目並運行
cd my-vite-app
npm install
npm run dev

命令行直接創建:

bash
# 創建 Vue 3 + TypeScript 項目
npm create vite@latest my-vue-app -- --template vue-ts

# 創建 React + TypeScript 項目
npm create vite@latest my-react-app -- --template react-ts

# 可用模板:vanilla, vue, react, preact, lit, svelte, solid
# 加 -ts 後綴為 TypeScript 版本

2.3 項目結構

my-vite-app/
├── node_modules/       # 依賴包
├── public/             # 靜態資源(不參與構建)
│   └── favicon.ico
├── src/                # 源碼目錄
│   ├── assets/         # 資源文件
│   ├── components/     # 組件
│   ├── App.vue         # 根組件
│   ├── main.js         # 入口文件
│   └── style.css       # 全局樣式
├── index.html          # HTML 入口
├── package.json        # 項目配置
├── vite.config.js      # Vite 配置
└── .gitignore

2.4 常用命令

bash
# 啟動開發服務器
npm run dev

# 構建生產版本
npm run build

# 本地預覽生產構建
npm run preview

# 運行開發服務器並指定端口
npm run dev -- --port 3000

# 構建並輸出分析報告
npm run build -- --report

三、核心配置

3.1 配置文件

Vite 使用 vite.config.js(或 .ts)作為配置文件:

js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  
  // 開發服務器配置
  server: {
    port: 3000,
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
  
  // 構建配置
  build: {
    outDir: 'dist',
    sourcemap: true,
    minify: 'esbuild'
  },
  
  // 路徑別名
  resolve: {
    alias: {
      '@': '/src'
    }
  }
})

3.2 路徑別名配置

js
// vite.config.js
import { defineConfig } from 'vite'
import path from 'path'

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      '@components': path.resolve(__dirname, './src/components'),
      '@utils': path.resolve(__dirname, './src/utils')
    }
  }
})

如果使用 TypeScript,還需要在 tsconfig.json 中配置:

json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"]
    }
  }
}

3.3 開發服務器配置

js
export default defineConfig({
  server: {
    // 端口號
    port: 3000,
    
    // 啟動時自動打開瀏覽器
    open: true,
    
    // 主機名(設置為 0.0.0.0 可被外部訪問)
    host: '0.0.0.0',
    
    // 嚴格端口(端口被佔用時直接退出)
    strictPort: false,
    
    // HTTPS 配置
    https: false,
    
    // 代理配置
    proxy: {
      // 字符串簡寫
      '/api': 'http://localhost:8080',
      
      // 完整配置
      '/api2': {
        target: 'http://localhost:8081',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api2/, '')
      },
      
      // WebSocket 代理
      '/socket.io': {
        target: 'ws://localhost:3001',
        ws: true
      }
    },
    
    // CORS
    cors: true,
    
    // 自定義響應頭
    headers: {
      'X-Custom-Header': 'Vite'
    }
  }
})

3.4 環境變量

Vite 使用 dotenv 加載環境變量,變量需要以 VITE_ 前綴開頭才會暴露到客戶端。

.env 文件:

.env                # 所有環境加載
.env.local          # 所有環境加載(git 忽略)
.env.development    # 開發環境
.env.production     # 生產環境
.env.staging        # 預發佈環境

示例 .env.development:

# 只有 VITE_ 前綴的變量才會暴露給前端
VITE_API_BASE_URL=http://localhost:3000/api
VITE_APP_TITLE=My App (Development)

# 這個變量不會暴露給前端(服務器端可用)
DB_PASSWORD=secret123

代碼中使用:

js
console.log(import.meta.env.VITE_API_BASE_URL)
console.log(import.meta.env.VITE_APP_TITLE)

// 內置變量
console.log(import.meta.env.MODE)        // 模式:development/production
console.log(import.meta.env.DEV)         // 是否開發環境
console.log(import.meta.env.PROD)        // 是否生產環境
console.log(import.meta.env.SSR)         // 是否 SSR

TypeScript 類型支持:

ts
// src/vite-env.d.ts
interface ImportMetaEnv {
  readonly VITE_API_BASE_URL: string
  readonly VITE_APP_TITLE: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

四、資源處理

4.1 靜態資源

public 目錄: 放在 public 目錄的文件會被原樣複製到輸出目錄,不參與構建。

public/
  robots.txt
  favicon.ico
  images/
    logo.png

引用方式:

html
<!-- 直接用根路徑引用 -->
<img src="/images/logo.png" />

src/assets 目錄: 放在 src 中的資源會被 Vite 處理(哈希、壓縮等)。

js
// 直接導入
import logo from './assets/logo.png'

// 在 CSS 中使用
.logo {
  background: url('./assets/logo.png');
}

4.2 CSS 處理

Vite 原生支持 CSS、CSS Modules、Sass/Less/Stylus。

CSS Modules:

css
/* Button.module.css */
.button {
  padding: 8px 16px;
  border-radius: 4px;
}

.primary {
  background: blue;
  color: white;
}
jsx
import styles from './Button.module.css'

function Button() {
  return <button className={`${styles.button} ${styles.primary}`}>Click</button>
}

CSS 預處理器:

bash
# 安裝 Sass
npm install -D sass

# 安裝 Less
npm install -D less

# 安裝 Stylus
npm install -D stylus
js
// vite.config.js
export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/styles/variables.scss";`
      }
    }
  }
})

PostCSS 配置:

Vite 自動應用 PostCSS 配置,創建 postcss.config.js 即可:

js
export default {
  plugins: {
    'postcss-px-to-viewport-8-plugin': {
      viewportWidth: 375
    },
    autoprefixer: {}
  }
}

4.3 JSON 處理

js
// 導入整個 JSON
import data from './data.json'

// 具名導入(Tree Shaking)
import { name, version } from './data.json'

4.4 Web Workers

js
// 普通導入
import MyWorker from './worker?worker'

const worker = new MyWorker()

五、插件系統

5.1 常用插件

插件功能
@vitejs/plugin-vueVue 3 支持
@vitejs/plugin-reactReact 支持
@vitejs/plugin-legacy傳統瀏覽器支持
@vitejs/plugin-basic-sslHTTPS 開發證書
vite-plugin-pwaPWA 支持
unplugin-auto-import自動導入 API
unplugin-vue-components自動註冊組件
vite-plugin-compressiongzip/br 壓縮
rollup-plugin-visualizer包大小分析

5.2 Vue 插件配置

js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

export default defineConfig({
  plugins: [
    vue({
      // 響應性語法糖
      reactivityTransform: true
    }),
    vueJsx()
  ]
})

5.3 React 插件配置

js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()]
})

5.4 自動導入插件

js
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'

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

5.5 開發自己的插件

js
// my-plugin.js
export default function myPlugin() {
  return {
    name: 'my-plugin',
    
    // 構建開始時
    buildStart() {
      console.log('Build started')
    },
    
    // 轉換代碼
    transform(code, id) {
      if (id.endsWith('.custom.js')) {
        return {
          code: code.replace('__PLACEHOLDER__', 'replaced'),
          map: null
        }
      }
    },
    
    // 構建結束
    buildEnd() {
      console.log('Build ended')
    }
  }
}

六、性能優化

6.1 依賴預構建

Vite 會自動預構建依賴,提升頁面加載速度。

js
export default defineConfig({
  optimizeDeps: {
    // 強制預構建的依賴
    include: ['lodash-es', 'dayjs'],
    
    // 排除預構建的依賴
    exclude: ['some-esm-package'],
    
    // 自定義 esbuild 配置
    esbuildOptions: {
      target: 'es2020'
    }
  }
})

6.2 構建優化

js
export default defineConfig({
  build: {
    // 輸出目錄
    outDir: 'dist',
    
    // 資源目錄
    assetsDir: 'assets',
    
    // 源碼映射
    sourcemap: false,
    
    // 壓縮方式:esbuild | terser | false
    minify: 'esbuild',
    
    // chunk 大小警告(單位 KB)
    chunkSizeWarningLimit: 500,
    
    // Rollup 配置
    rollupOptions: {
      output: {
        // 代碼分割策略
        manualChunks: {
          vendor: ['vue', 'vue-router', 'pinia'],
          utils: ['lodash-es', 'dayjs']
        },
        
        // 靜態資源文件名
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
      }
    },
    
    // 小於此大小的資源內聯為 base64(單位 KB)
    assetsInlineLimit: 4096
  }
})

6.3 打包分析

bash
# 安裝 rollup-plugin-visualizer
npm install -D rollup-plugin-visualizer
js
import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig({
  plugins: [
    visualizer({
      open: true,
      filename: 'dist/stats.html'
    })
  ]
})

6.4 圖片壓縮

bash
npm install -D vite-plugin-imagemin
js
import viteImagemin from 'vite-plugin-imagemin'

export default defineConfig({
  plugins: [
    viteImagemin({
      gifsicle: { optimizationLevel: 7 },
      optipng: { optimizationLevel: 7 },
      mozjpeg: { quality: 80 },
      pngquant: { quality: [0.8, 0.9] },
      svgo: {
        plugins: [{ name: 'removeViewBox' }]
      }
    })
  ]
})

七、生產構建與部署

7.1 構建命令

bash
# 構建生產版本
npm run build

# 預覽構建結果
npm run preview

# 預覽時指定端口
npm run preview -- --port 8080

7.2 傳統瀏覽器兼容

如果需要支持 IE11 等舊瀏覽器:

bash
npm install -D @vitejs/plugin-legacy
js
import legacy from '@vitejs/plugin-legacy'

export default defineConfig({
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11'],
      additionalLegacyPolyfills: ['regenerator-runtime/runtime']
    })
  ]
})

7.3 部署到靜態託管

Nginx 配置:

nginx
server {
    listen 80;
    server_name your-domain.com;
    root /var/www/dist;
    index index.html;

    # SPA 路由回退
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 靜態資源緩存
    location /assets/ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

GitHub Pages 部署:

yaml
# .github/workflows/deploy.yml
name: Deploy
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npm run build
      - uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./dist

Vercel 部署:

直接連接 GitHub 倉庫,Vercel 會自動檢測 Vite 項目並部署。

Netlify 部署:

創建 netlify.toml

toml
[build]
  command = "npm run build"
  publish = "dist"

[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

八、從 Webpack 遷移

8.1 主要差異

功能WebpackVite
配置文件webpack.config.jsvite.config.js
開發服務器webpack-dev-servervite dev server
模塊系統CommonJS + ESM原生 ESM
打包工具webpackRollup(生產)
熱更新整個模塊重打包精確到組件

8.2 遷移步驟

1. 創建 Vite 配置文件

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

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    },
    extensions: ['.mjs', '.js', '.ts', '.vue', '.json']
  },
  server: {
    port: 8080,
    proxy: {
      '/api': 'http://localhost:3000'
    }
  }
})

2. 更新入口 HTML

Vite 使用 index.html 作為入口:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>My App</title>
</head>
<body>
  <div id="app"></div>
  <script type="module" src="/src/main.js"></script>
</body>
</html>

3. 更新 package.json 腳本

json
{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  }
}

4. 處理 require 語法

Vite 不支持 require(),需要改為 import

js
// 舊寫法
const lodash = require('lodash')

// 新寫法
import lodash from 'lodash'

5. 環境變量適配

js
// Webpack
process.env.VUE_APP_API_URL

// Vite
import.meta.env.VITE_API_URL

九、常見問題

9.1 開發相關

Q: 啟動後局域網無法訪問?

js
// vite.config.js
export default defineConfig({
  server: {
    host: '0.0.0.0'
  }
})

Q: 代理不生效?

檢查路徑匹配和 changeOrigin 設置:

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

9.2 構建相關

Q: 打包後路徑不對?

設置正確的 base

js
export default defineConfig({
  // 部署在根路徑
  base: '/',
  
  // 部署在子路徑
  base: '/my-app/'
})

Q: 打包體積太大?

  • 使用 rollup-plugin-visualizer 分析
  • 配置 manualChunks 拆分代碼
  • 開啟 Tree Shaking
  • 使用 CDN 加載大型庫

9.3 依賴相關

Q: 某些依賴報錯?

可能是依賴預構建的問題,嘗試手動添加:

js
export default defineConfig({
  optimizeDeps: {
    include: ['problematic-package']
  }
})

十、總結與速查

10.1 核心命令速查

bash
# 創建項目
pnpm create vite

# 開發
pnpm dev
pnpm dev --port 3000
pnpm dev --host 0.0.0.0

# 構建
pnpm build
pnpm build --watch

# 預覽
pnpm preview
pnpm preview --port 8080

10.2 配置速查

js
export default defineConfig({
  // 基礎路徑
  base: '/',
  
  // 插件
  plugins: [],
  
  // 路徑別名
  resolve: { alias: {} },
  
  // 開發服務器
  server: { port: 3000, proxy: {} },
  
  // 構建配置
  build: { outDir: 'dist', sourcemap: false },
  
  // CSS 配置
  css: { preprocessorOptions: {} },
  
  // 依賴預構建
  optimizeDeps: { include: [] }
})

10.3 Vite 生態系統

  • VitePress: 靜態站點生成器(本站使用)
  • Nuxt 3: Vue 全棧框架(基於 Vite)
  • SvelteKit: Svelte 全棧框架
  • Astro: 內容驅動的靜態站點
  • Qwik City: Qwik 全棧框架

相關文章推薦:

🎯 Vite 已經成為現代前端開發的標準配置,掌握它能讓你的開發效率提升數倍。從今天開始,體驗極速開發的樂趣吧!

最後更新於: