Vite 是下一代前端开发工具,由 Vue 作者尤雨溪开发,提供极速的开发体验和高效的生产构建。以下是完整功能解析和实战示例:
闪电般冷启动
即时热更新(HMR)
开箱即用支持
优化构建
插件系统
my-vue-app/
├── public/
│ └── favicon.ico
├── src/
│ ├── assets/
│ ├── components/
│ ├── store/ # Pinia 状态管理
│ ├── router/ # Vue Router
│ ├── views/
│ ├── App.vue
│ ├── main.js
│ └── style.css
├── .env # 环境变量
├── vite.config.js # Vite 配置
└── package.json
npm create vite@latest
# 选择 Vue + TypeScript
cd my-vue-app
npm install
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')
}
},
server: {
port: 8080,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
},
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
}
}
},
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return 'vendor'
}
}
}
}
}
})
npm install vue-router@4
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
const routes = [
{ path: '/', component: Home },
{
path: '/user/:id',
component: () => import('@/views/User.vue'),
meta: { requiresAuth: true }
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
npm install pinia
// src/store/user.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: 'Guest',
isAdmin: false
}),
actions: {
login(userData) {
this.name = userData.name
this.isAdmin = userData.isAdmin
}
},
getters: {
welcomeMessage: (state) => `Hello, ${state.name}!`
}
})
{{ welcomeMsg }}
# .env.development
VITE_API_BASE=http://localhost:3000/api
VITE_DEBUG_MODE=true
# .env.production
VITE_API_BASE=https://api.example.com
// 使用环境变量
const apiBase = import.meta.env.VITE_API_BASE
const UserProfile = defineAsyncComponent(() =>
import('@/components/UserProfile.vue')
)
<img src="@/assets/logo.png" alt="Vite logo">
import largeImage from '@/assets/bg.jpg?url'
// src/styles/main.scss
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
// vite.config.js 中全局引入
SSR 支持 (vite-plugin-ssr)
npm install vite-plugin-ssr
// vite.config.js
import ssr from 'vite-plugin-ssr/plugin'
export default defineConfig({
plugins: [vue(), ssr()]
})
PWA 支持
npm install vite-plugin-pwa
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
VitePWA({
registerType: 'autoUpdate',
manifest: {
name: 'My Vue App',
short_name: 'VueApp',
theme_color: '#ffffff'
}
})
]
})
// package.json
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "vitest",
"coverage": "vitest run --coverage"
}
// 静态部署 (GitHub Pages)
build: {
outDir: 'docs',
assetsDir: 'static'
}
// SPA 路由处理
export default defineConfig({
build: {
rollupOptions: {
input: {
main: path.resolve(__dirname, 'index.html'),
404: path.resolve(__dirname, '404.html')
}
}
}
})
特性 | Vite | Webpack |
---|---|---|
启动速度 | 毫秒级 | 随项目增长线性下降 |
HMR 更新 | 局部更新 <50ms | 全量更新 >1s |
构建原理 | ESM 按需编译 + Rollup | Bundle 打包 |
配置复杂度 | 极简配置 | 复杂配置 |
TS 支持 | 原生支持 | 需要 loader |
开发体验 | 接近原生开发 | 有打包等待 |
// 自动导入示例 (vite.config.js)
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
AutoImport({
imports: [
'vue',
'vue-router',
'pinia'
],
dts: 'src/auto-imports.d.ts'
})
]
})
通过以上配置和示例,你可以快速构建一个现代化的 Vue 3 应用,享受 Vite 带来的极致开发体验!