Vite是一个基于原生ES模块的现代前端构建工具,它解决了传统构建工具在开发环境中的性能瓶颈问题。
| 特性 | 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.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拥有丰富的插件生态系统:
Vue 3单文件组件支持
npm i @vitejs/plugin-vue
Vue 3 JSX支持
npm i @vitejs/plugin-vue-jsx
PWA渐进式Web应用
npm i vite-plugin-pwa
自动导入组件
npm i unplugin-vue-components
SVG图标管理
npm i vite-plugin-svg-icons
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('生产环境')
}
启动开发服务器
构建生产版本
预览生产构建
{
"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
}
}
}
})
A: Vite原生支持Vue、React、Preact、Lit等主流框架。
A: 安装TypeScript后即可直接使用,无需额外配置。
A: 支持CSS Modules、PostCSS、Sass、Less、Stylus等。
A: 支持现代浏览器、旧版浏览器、Node.js等不同目标。