Vue.js构建工具(Vite)

Vite(法语意为"快速")是下一代前端构建工具,由Vue.js作者尤雨溪开发,专为现代Web项目设计,提供极速的开发服务器和高效的构建输出。

什么是Vite?

Vite是一个基于原生ES模块的现代前端构建工具,它解决了传统构建工具在开发环境中的性能瓶颈问题。

主要特点
  • 极速启动 - 秒级启动开发服务器
  • 快速热更新 - 毫秒级模块热替换
  • 按需编译 - 只编译请求的模块
  • 开箱即用 - 支持TypeScript、JSX等
  • 优化的构建 - 使用Rollup进行生产构建
性能对比
特性 Vite Webpack
启动时间 0.5-2秒 30-60秒
热更新 ~50ms 500ms-2s
构建速度 快速 一般

快速开始

使用Vite创建Vue项目非常简单:

命令行
# 使用npm
npm create vite@latest my-vue-app -- --template vue

# 或使用yarn
yarn create vite my-vue-app --template vue

# 或使用pnpm
pnpm create vite my-vue-app --template vue

# 进入项目目录
cd my-vue-app

# 安装依赖
npm install

# 启动开发服务器
npm run dev

项目结构

Vite创建的Vue项目结构清晰简洁:

项目目录结构
my-vue-app/
├── node_modules/     # 依赖包
├── public/           # 静态资源
│   └── vite.svg
├── src/              # 源代码
│   ├── assets/       # 资源文件
│   ├── components/   # Vue组件
│   │   └── HelloWorld.vue
│   ├── App.vue       # 根组件
│   ├── main.js       # 应用入口
│   └── style.css     # 全局样式
├── .gitignore        # Git忽略配置
├── index.html        # 主HTML文件
├── package.json      # 项目配置
├── vite.config.js    # Vite配置
└── README.md         # 项目说明

Vite配置文件

Vite的配置文件vite.config.js非常灵活:

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

// https://vitejs.dev/config/
export default defineConfig({
  // 插件配置
  plugins: [vue()],

  // 开发服务器配置
  server: {
    host: 'localhost',
    port: 3000,
    open: true, // 自动打开浏览器
    proxy: {
      // 代理配置
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },

  // 构建配置
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: true,
    rollupOptions: {
      // 多入口配置
      input: {
        main: resolve(__dirname, 'index.html'),
        admin: resolve(__dirname, 'admin.html')
      },
      // 代码分割配置
      output: {
        chunkFileNames: 'js/[name]-[hash].js',
        entryFileNames: 'js/[name]-[hash].js',
        assetFileNames: '[ext]/[name]-[hash].[ext]'
      }
    }
  },

  // 路径别名
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
      'components': resolve(__dirname, 'src/components')
    }
  },

  // CSS配置
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/styles/variables.scss";`
      }
    }
  }
})

插件系统

Vite拥有丰富的插件生态系统:

@vitejs/plugin-vue

Vue 3单文件组件支持

npm i @vitejs/plugin-vue
@vitejs/plugin-vue-jsx

Vue 3 JSX支持

npm i @vitejs/plugin-vue-jsx
vite-plugin-pwa

PWA渐进式Web应用

npm i vite-plugin-pwa
unplugin-vue-components

自动导入组件

npm i unplugin-vue-components
vite-plugin-svg-icons

SVG图标管理

npm i vite-plugin-svg-icons
vite-plugin-compression

gzip/brotli压缩

npm i vite-plugin-compression

环境变量

Vite使用.env文件管理环境变量:

环境变量配置
# .env.development
VITE_API_BASE_URL=http://localhost:3000/api
VITE_APP_TITLE=开发环境

# .env.production
VITE_API_BASE_URL=https://api.example.com
VITE_APP_TITLE=生产环境
// 在代码中使用环境变量
const apiUrl = import.meta.env.VITE_API_BASE_URL
const appTitle = import.meta.env.VITE_APP_TITLE

// 环境判断
if (import.meta.env.DEV) {
  console.log('开发环境')
}

if (import.meta.env.PROD) {
  console.log('生产环境')
}

开发工作流

常用命令
npm run dev

启动开发服务器

npm run build

构建生产版本

npm run preview

预览生产构建

package.json示例:
{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs",
    "lint:fix": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs --fix",
    "format": "prettier --write src/",
    "type-check": "vue-tsc --noEmit"
  }
}

构建优化

// 动态导入实现代码分割
const Login = () => import('./views/Login.vue')
const Dashboard = () => import('./views/Dashboard.vue')

// 使用webpackChunkName命名
const UserProfile = () => import(/* webpackChunkName: "user" */ './views/UserProfile.vue')

import { defineConfig } from 'vite'
import viteImagemin from 'vite-plugin-imagemin'

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

// vite.config.js
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          // 将node_modules中的包拆分到单独的chunk
          if (id.includes('node_modules')) {
            if (id.includes('vue')) {
              return 'vue-vendor'
            }
            if (id.includes('element-plus')) {
              return 'element-vendor'
            }
            return 'vendor'
          }
        }
      }
    },
    // 启用terser压缩
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  }
})
常见问题解答
Q: Vite支持哪些框架?

A: Vite原生支持Vue、React、Preact、Lit等主流框架。

Q: 如何在Vite中使用TypeScript?

A: 安装TypeScript后即可直接使用,无需额外配置。

Q: Vite如何处理CSS?

A: 支持CSS Modules、PostCSS、Sass、Less、Stylus等。

Q: 生产构建支持哪些目标?

A: 支持现代浏览器、旧版浏览器、Node.js等不同目标。