Vite 构建工具入门
什么是 Vite
Vite(法语"快"的意思)是由 Vue 作者尤雨溪开发的构建工具。它的核心创新是利用浏览器原生 ES Module 导入能力,开发服务器无需打包即可提供模块,实现了毫秒级的热更新。
核心原理
开发模式
传统工具(Webpack)在开发时需要先打包整个应用再启动服务。Vite 则不同:
Webpack: 打包所有模块 → 启动开发服务器 → 浏览器请求
Vite: 启动开发服务器 → 浏览器请求 → 按需编译被请求的模块
Vite 开发服务器在启动时只做两件事:
- 启动一个静态文件服务器
- 用 esbuild 预构建依赖(node_modules 中的第三方包)
浏览器通过 <script type="module"> 加载源码,遇到 import 语句时向服务器请求对应的模块,服务器即时编译后返回。
热更新(HMR)
文件变更时,Vite 只对变更模块及其直接依赖进行编译,利用 ESM 的精确定位能力实现毫秒级 HMR,不受项目规模影响。
快速开始
# 创建项目
npm create vite@latest my-app -- --template react-ts
# 进入目录并安装
cd my-app
npm install
# 启动开发服务器
npm run dev
# 构建生产版本
npm run build
配置文件
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
},
},
build: {
target: 'es2020',
outDir: 'dist',
sourcemap: false,
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
},
},
},
},
});
核心功能
CSS 处理
Vite 内置支持 CSS、CSS Modules、PostCSS、SCSS/Less:
/* App.module.css */
.title {
color: red;
font-size: 2rem;
}
import styles from './App.module.css';
// 使用: className={styles.title}
静态资源
import logo from './logo.png'; // 返回 URL
import jsonData from './data.json'; // 返回解析后的对象
import worker from './worker?worker'; // 返回 Web Worker
环境变量
# .env 文件
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=我的应用
// 客户端代码中使用
const apiUrl = import.meta.env.VITE_API_URL;
console.log(import.meta.env.MODE); // 'development' | 'production'
TypeScript
Vite 原生支持 TypeScript,但只做编译不做类型检查(由 IDE 或单独脚本负责):
// tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx"
},
"include": ["src"]
}
Vite vs Webpack
| 特性 | Vite | Webpack |
|---|---|---|
| 开发服务器启动 | 极快(秒级) | 较慢(依赖项目规模) |
| HMR 速度 | 毫秒级,与项目规模无关 | 随项目规模变慢 |
| 生产构建 | 基于 Rollup | 自带打包器 |
| 插件生态 | 丰富,可兼容 Rollup 插件 | 最成熟 |
| 配置复杂度 | 简洁 | 复杂 |
| 浏览器兼容 | ES2020 以上 | 可配置更低的 target |
生产构建优化
export default defineConfig({
build: {
// 代码分割
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
if (id.includes('react')) return 'vendor-react';
if (id.includes('lodash')) return 'vendor-lodash';
return 'vendor';
}
},
},
},
// 图片压缩
assetsInlineLimit: 8 * 1024, // 8KB 以下内联
// CSS 代码分割
cssCodeSplit: true,
// 去除 console
esbuild: {
drop: process.env.NODE_ENV === 'production' ? ['console', 'debugger'] : [],
},
},
});
总结
Vite 凭借原生 ESM 和 esbuild 预构建,提供了极致的开发体验。对于新项目,Vite 已成为社区推荐的首选构建工具。如果你还在使用 Webpack,值得尝试将新项目切换到 Vite 体验高效开发的快感。