跳转到内容

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 已经成为现代前端开发的标准配置,掌握它能让你的开发效率提升数倍。从今天开始,体验极速开发的乐趣吧!