Vite 使用说明和示例演示
📌 什么是 Vite?
Vite (法语意为"快速",发音 /vit/)是由 Vue.js 作者尤雨溪开发的新一代前端构建工具。它利用浏览器原生的 ES Modules 实现了极速冷启动和即时热更新,特别适合 Vue、React 等现代框架项目。
⚡️ Vite 的核心优势
| 特性 | 描述 |
|---|---|
| 极速启动 | 几秒内即可启动开发服务器 |
| 模块化加载 | 原生支持 ES Module,无需打包 |
| HMR 支持 | 热更新响应速度极快 |
| 生产优化 | 使用 Rollup 打包,输出高度优化的静态资源 |
🚀 快速开始
1. 环境准备
Vite 需要 Node.js 版本 20.19+ 或 22.12+
# 验证 Node.js 版本
node -v
npm -v
2. 创建项目
# 使用 npm 创建 Vue 项目
npm create vite@latest my-vue-app --template vue
# 使用 npm 创建 React 项目
npm create vite@latest my-react-app --template react
# 使用 npm 创建 TypeScript + Vue 项目
npm create vite@latest my-app --template vue-ts
# 使用 npm 创建 TypeScript + React 项目
npm create vite@latest my-app --template react-ts
# 使用 yarn
yarn create vite my-app --template vue
# 使用 pnpm
pnpm create vite my-app --template vue
3. 安装依赖并启动
cd my-vue-app
npm install
npm run dev
启动后访问 http://localhost:5173 即可看到项目运行。
📁 项目结构
my-vue-app/
├── node_modules/ # 依赖包
├── public/ # 静态资源(直接复制到输出目录)
├── src/ # 源代码
│ ├── assets/ # 资源文件
│ ├── components/ # 组件
│ ├── App.vue # 根组件
│ └── main.js # 入口文件
├── index.html # HTML 模板
├── package.json # 项目配置
├── vite.config.js # Vite 配置文件
└── README.md
⚙️ vite.config.js 配置详解
基础配置模板
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig({
// 基础公共路径(子目录部署时需要)
base: '/',
// 插件配置
plugins: [vue()],
// 路径别名
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@assets': path.resolve(__dirname, './src/assets'),
},
},
// 开发服务器配置
server: {
port: 3000, // 端口号
open: true, // 自动打开浏览器
host: true, // 允许外部访问
cors: true, // 允许跨域
proxy: {
// 代理配置(解决跨域问题)
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
// 构建配置
build: {
outDir: 'dist', // 输出目录
assetsDir: 'assets', // 静态资源目录
sourcemap: false, // 是否生成 source map
minify: 'terser', // 压缩工具
terserOptions: {
compress: {
drop_console: true, // 生产环境移除 console
drop_debugger: true,
},
},
rollupOptions: {
output: {
// 静态资源分类打包
manualChunks: {
'vue-vendor': ['vue', 'vue-router', 'pinia'],
'ui-vendor': ['element-plus'],
},
},
},
},
// CSS 配置
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`,
},
},
},
// 环境变量
define: {
__APP_VERSION__: JSON.stringify(process.env.npm_package_version),
__BUILD_TIME__: JSON.stringify(new Date().toISOString()),
},
})
TypeScript 配置文件
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
},
},
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
},
},
})
🔧 常用命令
# 开发模式
npm run dev
# 构建生产版本
npm run build
# 预览生产构建
npm run preview
# 类型检查(TypeScript 项目)
npm run type-check
📦 环境变量使用
1. 创建环境文件
# 项目根目录
.env # 所有环境
.env.local # 本地环境(不提交到 git)
.env.development # 开发环境
.env.production # 生产环境
2. 环境变量格式
# .env
VITE_API_BASE_URL=https://api.example.com
VITE_APP_TITLE=我的应用
⚠️ 注意:只有以 VITE_ 开头的变量才会暴露给客户端代码
3. 在代码中使用
// main.js
console.log(import.meta.env.VITE_API_BASE_URL)
console.log(import.meta.env.VITE_APP_TITLE)
// 所有环境变量
console.log(import.meta.env)
🎯 完整示例演示
Vue 3 + Vite 示例
main.js
import { createApp } from 'vue'
import App from './App.vue'
import './style.css'
createApp(App).mount('#app')
App.vue
<template>
<div class="app">
<h1>{{ title }}</h1>
<button @click="count++">计数:{{ count }}</button>
<p>API 地址:{{ apiUrl }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const title = ref('Vite + Vue 3 示例')
const count = ref(0)
const apiUrl = import.meta.env.VITE_API_BASE_URL
</script>
<style scoped>
.app {
text-align: center;
padding: 2rem;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
}
button:hover {
background: #35a372;
}
</style>
📈 性能优化技巧
1. 代码分割
// vite.config.js
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
'vue-core': ['vue', 'vue-router'],
'ui-lib': ['element-plus'],
},
},
},
},
})
2. 按需加载
// 动态导入
const Module = () => import('./components/HeavyModule.vue')
// 路由懒加载
const routes = [
{
path: '/about',
component: () => import('@/views/About.vue'),
},
]
3. 图片优化
// 使用 vite-plugin-imagemin
import viteImagemin from 'vite-plugin-imagemin'
export default defineConfig({
plugins: [
vue(),
viteImagemin({
gifsicle: { optimizationLevel: 7 },
optipng: { optimizationLevel: 7 },
mozjpeg: { quality: 80 },
pngquant: { quality: [0.8, 0.9] },
svgo: {
plugins: [
{ removeViewBox: false },
{ removeEmptyAttrs: false },
],
},
}),
],
})
🔌 常用插件推荐
| 插件 | 用途 | 安装命令 |
|---|---|---|
@vitejs/plugin-vue |
Vue 3 支持 | npm i -D @vitejs/plugin-vue |
@vitejs/plugin-react |
React 支持 | npm i -D @vitejs/plugin-react |
vite-plugin-svg-icons |
SVG 图标 | npm i -D vite-plugin-svg-icons |
vite-plugin-compression |
Gzip 压缩 | npm i -D vite-plugin-compression |
unplugin-auto-import |
自动导入 | npm i -D unplugin-auto-import |
unplugin-vue-components |
组件自动注册 | npm i -D unplugin-vue-components |
⚠️ 常见问题
| 问题 | 解决方案 |
|---|---|
| 修改配置不生效 | 重启开发服务器(Ctrl+C 后重新 npm run dev) |
| 端口被占用 | 在 server.port 中指定其他端口 |
| 跨域问题 | 配置 server.proxy 代理 |
| 路径别名不生效 | 同时配置 vite.config.js 和 jsconfig.json/tsconfig.json |
| 生产环境空白 | 检查 base 配置是否正确 |
📚 官方资源
- Vite 官方中文文档: https://cn.vitejs.dev/
- Vite 英文文档: https://vitejs.dev/
- GitHub 仓库: https://github.com/vitejs/vite
希望这份指南能帮助你快速上手 Vite!