Vite

什么是 Vite?

Vite 是一个由 Vue.js 作者尤雨溪开发的前端构建工具,它提供了极速的开发服务器和优化的构建输出。Vite 利用浏览器的 ES 模块支持和 Node.js 的原生模块系统,实现了按需编译,大大提高了开发效率。

1. 安装 Vite

使用 npm 或 yarn 安装 Vite。

示例:安装 Vite

# 使用 npm
npm create vite@latest

# 使用 yarn
yarn create vite

# 使用 pnpm
pnpm create vite

2. 创建 Vite + Vue3 项目

使用 Vite 脚手架创建一个 Vue3 项目。

示例:创建 Vite + Vue3 项目

# 交互式创建
npm create vite@latest my-vue3-app -- --template vue

# 非交互式创建
npm create vite@latest my-vue3-app -- --template vue

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

# 安装依赖
npm install

# 启动开发服务器
npm run dev

3. Vite 项目结构

了解 Vite 项目的基本结构。

示例:Vite 项目结构

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

4. Vite 配置文件

了解 Vite 配置文件的基本配置项。

示例:Vite 配置文件

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

export default defineConfig({
  // 插件配置
  plugins: [vue()],
  
  // 服务器配置
  server: {
    port: 3000, // 开发服务器端口
    open: true, // 自动打开浏览器
    proxy: {
      // 代理配置
      '/api': {
        target: 'http://localhost:5000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
  
  // 构建配置
  build: {
    outDir: 'dist', // 输出目录
    assetsDir: 'assets', // 静态资源目录
    sourcemap: false, // 是否生成 sourcemap
    minify: 'terser', // 压缩方式
    rollupOptions: {
      // Rollup 配置
      output: {
        manualChunks: {
          // 代码分割
          vue: ['vue'],
          'vue-router': ['vue-router'],
          pinia: ['pinia']
        }
      }
    }
  },
  
  // 解析配置
  resolve: {
    alias: {
      // 路径别名
      '@': resolve(__dirname, 'src')
    }
  },
  
  // CSS 配置
  css: {
    preprocessorOptions: {
      // CSS 预处理器配置
      scss: {
        additionalData: '@import "@/styles/variables.scss";'
      }
    }
  }
})

5. Vite 插件

Vite 支持丰富的插件生态,用于扩展 Vite 的功能。

示例:常用 Vite 插件

# Vue 插件
npm install @vitejs/plugin-vue --save-dev

# Vue JSX 插件
npm install @vitejs/plugin-vue-jsx --save-dev

# TypeScript 插件
npm install @rollup/plugin-typescript --save-dev

# ESLint 插件
npm install vite-plugin-eslint --save-dev

# Stylelint 插件
npm install vite-plugin-stylelint --save-dev

# SVG 插件
npm install vite-plugin-svg-icons --save-dev

# 压缩插件
npm install vite-plugin-compression --save-dev

6. Vite 开发服务器

Vite 提供了极速的开发服务器,支持热模块替换(HMR)。

示例:开发服务器命令

# 启动开发服务器
npm run dev

# 指定端口启动
npm run dev -- --port 3001

# 禁止自动打开浏览器
npm run dev -- --no-open

# 以 HTTPS 模式启动
npm run dev -- --https

7. Vite 构建命令

使用 Vite 构建生产版本。

示例:构建命令

# 构建生产版本
npm run build

# 构建开发版本(不压缩)
npm run build -- --mode development

# 构建并预览
npm run build && npm run preview

# 预览构建结果
npm run preview

8. Vite 环境变量

Vite 支持环境变量配置,用于区分不同环境。

示例:环境变量配置

// .env                # 所有环境通用
VITE_APP_TITLE = "Vue3 App"

// .env.development    # 开发环境
VITE_APP_API_BASE_URL = "http://localhost:3000/api"

// .env.production     # 生产环境
VITE_APP_API_BASE_URL = "https://api.example.com"

// 在组件中使用环境变量
console.log(import.meta.env.VITE_APP_TITLE) // "Vue3 App"
console.log(import.meta.env.VITE_APP_API_BASE_URL) // 根据环境不同而不同

9. Vite 与 TypeScript

Vite 对 TypeScript 有很好的支持。

示例:创建 Vite + Vue3 + TypeScript 项目

# 创建 TypeScript 项目
npm create vite@latest my-vue3-ts-app -- --template vue-ts

# 安装依赖
cd my-vue3-ts-app
npm install

# 启动开发服务器
npm run dev

10. Vite 与 Vue Router

在 Vite + Vue3 项目中使用 Vue Router。

示例:使用 Vue Router

# 安装 Vue Router
npm install vue-router@4

# 创建路由配置
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

export default router

// 在 main.js 中使用
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app')

// 在 App.vue 中添加路由出口
<template>
  <div>
    <router-view />
  </div>
</template>

11. Vite 与 Pinia

在 Vite + Vue3 项目中使用 Pinia。

示例:使用 Pinia

# 安装 Pinia
npm install pinia

# 创建 Pinia 实例
// src/main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.mount('#app')

// 创建 store
// src/stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count++
    }
  }
})

// 在组件中使用
// src/components/Counter.vue
<template>
  <div>
    <p>Count: {{ counter.count }}</p>
    <button @click="counter.increment">Increment</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '../stores/counter'
const counter = useCounterStore()
</script>

12. Vite 最佳实践

  • 使用 Vite 官方模板创建项目,避免手动配置
  • 合理使用环境变量,区分开发、测试和生产环境
  • 使用路径别名简化导入路径
  • 配置代码分割,优化构建输出
  • 使用 Vite 插件扩展功能
  • 合理配置静态资源处理
  • 使用 TypeScript 提高代码质量
  • 配置 ESLint 和 Prettier 保证代码风格一致
  • 使用 Git 进行版本控制
  • 定期更新依赖包