一、什么是Vite?
Vite(法语意为"快速")是由Vue作者尤雨溪开发的新型前端构建工具。它基于原生ES模块(ESM)实现,具有以下核心优势:
- 极速启动:冷启动时间比Webpack快10-100倍
- 闪电般的热更新:HMR(热模块替换)保持应用状态
- 开箱即用的支持:TypeScript、JSX、CSS预处理等
- 灵活的扩展:通过插件支持Rollup生态系统
二、环境准备
确保已安装:
- Node.js 14.18+ / 16+
- npm 7+ 或 yarn
# 验证安装
node -v
npm -v
三、创建第一个项目
1. 初始化项目
npm create vite@latest my-vite-app
选择框架模板(这里以React+TS为例):
✔ Select a framework: › React
✔ Select a variant: › TypeScript
2. 项目结构
my-vite-app/
├── node_modules/
├── public/
│ └── vite.svg
├── src/
│ ├── assets/
│ ├── App.css
│ ├── App.tsx
│ ├── index.css
│ ├── main.tsx
│ └── vite-env.d.ts
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts
3. 启动开发服务器
cd my-vite-app
npm install
npm run dev
访问 http://localhost:5173
四、核心功能实践
1. 模块热替换(HMR)
修改 src/App.tsx
:
function App() {return (<div className="App"><h1>Hello Vite!</h1><p>Edit and save to see HMR in action</p></div>)
}
保存后浏览器立即更新,无需刷新页面
2. CSS处理
创建 src/Button.module.css
:
.primary {background: #646cff;color: white;padding: 12px 24px;border-radius: 4px;
}
在组件中使用:
import styles from './Button.module.css'function Button() {return <button className={styles.primary}>Click Me</button>
}
3. 静态资源处理
// 直接引入图片
import logo from './assets/react.svg'function Logo() {return <img src={logo} alt="React logo" />
}
五、Vite配置详解
修改 vite.config.ts
:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'export default defineConfig({plugins: [react()],server: {port: 3000,open: true},build: {outDir: 'dist',assetsDir: 'static'}
})
六、插件系统
1. 常用插件示例
安装官方React插件:
npm install @vitejs/plugin-react -D
配置插件:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'export default defineConfig({plugins: [react({babel: {plugins: ['babel-plugin-styled-components']}})]
})
2. 社区插件示例(以SVG转换为例)
npm install vite-plugin-svgr -D
配置:
import svgr from 'vite-plugin-svgr'export default defineConfig({plugins: [svgr({svgrOptions: {icon: true}})]
})
使用SVG组件:
import { ReactComponent as Logo } from './logo.svg'function App() {return <Logo />
}
七、生产构建
npm run build
生成优化后的静态文件:
dist/
├── static/
│ ├── js/
│ ├── css/
│ └── assets/
└── index.html
八、环境变量
1. 创建环境文件
.env # 所有情况
.env.local # 本地覆盖,git忽略
.env.development # 开发环境
.env.production # 生产环境
2. 定义变量(前缀必须为VITE_)
VITE_API_URL=https://api.example.com
3. 使用变量
console.log(import.meta.env.VITE_API_URL)
九、与Webpack的主要差异
特性 | Vite | Webpack |
---|---|---|
启动时间 | 毫秒级 | 随着项目增长变慢 |
构建方式 | ESM原生模块 | Bundle打包 |
HMR速度 | 保持状态快速更新 | 需要重建模块 |
配置复杂度 | 简单 | 相对复杂 |
生态 | 快速成长 | 成熟 |
十、完整示例代码
查看GitHub仓库:
git clone https://github.com/vitejs/vite-template-react.git
十一、最佳实践
- 按需加载:使用动态import实现代码分割
- 缓存策略:配置合理的hash文件名
- 性能优化:使用
vite-plugin-compression
进行Gzip压缩 - 类型安全:充分利用TypeScript类型检查
- SSR支持:结合vite-ssr插件实现服务端渲染