vite-advanced
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseVite Advanced Patterns
Vite 进阶使用模式
Advanced configuration for Vite 7+ including Environment API.
Vite 7+ 进阶配置,包括Environment API。
Vite 7 Environment API (Key 2026 Feature)
Vite 7 Environment API(2026年核心特性)
Multi-environment support is now first-class:
typescript
import { defineConfig } from 'vite'
export default defineConfig({
environments: {
// Browser client
client: {
build: {
outDir: 'dist/client',
manifest: true,
},
},
// Node.js SSR
ssr: {
build: {
outDir: 'dist/server',
target: 'node20',
},
},
// Edge runtime (Cloudflare, etc.)
edge: {
resolve: {
noExternal: true,
conditions: ['edge', 'worker'],
},
build: {
outDir: 'dist/edge',
},
},
},
})Key Changes:
- Environments have their own module graph
- Plugins access in hooks
this.environment - API for coordinated builds
createBuilder - Node.js 20.19+ or 22.12+ required
多环境支持现已成为一等公民:
typescript
import { defineConfig } from 'vite'
export default defineConfig({
environments: {
// Browser client
client: {
build: {
outDir: 'dist/client',
manifest: true,
},
},
// Node.js SSR
ssr: {
build: {
outDir: 'dist/server',
target: 'node20',
},
},
// Edge runtime (Cloudflare, etc.)
edge: {
resolve: {
noExternal: true,
conditions: ['edge', 'worker'],
},
build: {
outDir: 'dist/edge',
},
},
},
})核心变化:
- 每个环境拥有独立的模块图
- 插件可在钩子中访问
this.environment - API用于协调多环境构建
createBuilder - 要求Node.js 20.19+ 或22.12+
Plugin Development
插件开发
Basic plugin structure:
typescript
export function myPlugin(): Plugin {
return {
name: 'my-plugin',
// Called once when config is resolved
configResolved(config) {
// Access resolved config
},
// Transform individual modules
transform(code, id) {
// this.environment available in Vite 7+
if (id.endsWith('.special')) {
return { code: transformCode(code) }
}
},
// Virtual modules
resolveId(id) {
if (id === 'virtual:my-module') {
return '\0virtual:my-module'
}
},
load(id) {
if (id === '\0virtual:my-module') {
return 'export const value = "generated"'
}
},
}
}基础插件结构:
typescript
export function myPlugin(): Plugin {
return {
name: 'my-plugin',
// Called once when config is resolved
configResolved(config) {
// Access resolved config
},
// Transform individual modules
transform(code, id) {
// this.environment available in Vite 7+
if (id.endsWith('.special')) {
return { code: transformCode(code) }
}
},
// Virtual modules
resolveId(id) {
if (id === 'virtual:my-module') {
return '\0virtual:my-module'
}
},
load(id) {
if (id === '\0virtual:my-module') {
return 'export const value = "generated"'
}
},
}
}SSR Configuration
SSR配置
Development (middleware mode):
typescript
import { createServer } from 'vite'
const vite = await createServer({
server: { middlewareMode: true },
appType: 'custom',
})
app.use('*', async (req, res) => {
const url = req.originalUrl
let template = fs.readFileSync('index.html', 'utf-8')
template = await vite.transformIndexHtml(url, template)
const { render } = await vite.ssrLoadModule('/src/entry-server.tsx')
const html = template.replace('<!--outlet-->', await render(url))
res.send(html)
})Production build scripts:
json
{
"scripts": {
"build:client": "vite build --outDir dist/client",
"build:server": "vite build --outDir dist/server --ssr src/entry-server.tsx"
}
}开发模式(中间件模式):
typescript
import { createServer } from 'vite'
const vite = await createServer({
server: { middlewareMode: true },
appType: 'custom',
})
app.use('*', async (req, res) => {
const url = req.originalUrl
let template = fs.readFileSync('index.html', 'utf-8')
template = await vite.transformIndexHtml(url, template)
const { render } = await vite.ssrLoadModule('/src/entry-server.tsx')
const html = template.replace('<!--outlet-->', await render(url))
res.send(html)
})生产构建脚本:
json
{
"scripts": {
"build:client": "vite build --outDir dist/client",
"build:server": "vite build --outDir dist/server --ssr src/entry-server.tsx"
}
}Build Optimization
构建优化
typescript
export default defineConfig({
build: {
target: 'baseline-widely-available', // Vite 7 default
sourcemap: false,
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
router: ['react-router-dom'],
},
},
},
},
})typescript
export default defineConfig({
build: {
target: 'baseline-widely-available', // Vite 7 default
sourcemap: false,
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
router: ['react-router-dom'],
},
},
},
},
})Quick Reference
快速参考
| Feature | Vite 7 Status |
|---|---|
| Environment API | Stable |
| ESM-only distribution | Default |
| Node.js requirement | 20.19+ or 22.12+ |
| New for plugins |
| Multi-env builds |
| Feature | Vite 7 Status |
|---|---|
| Environment API | Stable |
| ESM-only distribution | Default |
| Node.js requirement | 20.19+ or 22.12+ |
| New for plugins |
| Multi-env builds |
Vite 8: Rolldown-Powered Builds
Vite 8:基于Rolldown的构建系统
Vite 8 replaces the esbuild+Rollup pipeline with Rolldown, a Rust-based unified bundler delivering dramatic performance improvements.
Vite 8 使用Rolldown替代了esbuild+Rollup的构建流水线,这是一个基于Rust的统一打包工具,可带来显著的性能提升。
Migration Options
迁移方案
Option 1: Direct Upgrade to Vite 8
bash
npm install vite@8Best for: New projects, smaller codebases, teams ready to adopt cutting-edge tooling.
Option 2: Gradual Migration with rolldown-vite
bash
npm install rolldown-vitetypescript
// vite.config.ts - swap import only
import { defineConfig } from 'rolldown-vite' // instead of 'vite'
export default defineConfig({
// Existing config works unchanged
})Best for: Large production apps, risk-averse teams, testing Rolldown before full commitment.
方案1:直接升级到Vite 8
bash
npm install vite@8适用场景:新项目、小型代码库、愿意采用前沿工具的团队。
方案2:通过rolldown-vite逐步迁移
bash
npm install rolldown-vitetypescript
// vite.config.ts - 仅替换导入语句
import { defineConfig } from 'rolldown-vite' // 替代 'vite'
export default defineConfig({
// 现有配置无需修改
})适用场景:大型生产应用、风险规避型团队、在全面升级前测试Rolldown的团队。
Performance Benchmarks
性能基准测试
Real-world improvements from production deployments:
| Metric | Before (Vite 7) | After (Vite 8) | Improvement |
|---|---|---|---|
| Linear build time | 46s | 6s | 7.7x faster |
| Dev server startup | ~3s | ~1s | 3x faster |
| HMR updates | ~100ms | ~60ms | 40% faster |
| Memory usage | ~800MB | ~400MB | 50% reduction |
来自生产环境部署的真实性能提升:
| 指标 | Vite 7之前 | Vite 8之后 | 提升幅度 |
|---|---|---|---|
| 线性构建时间 | 46s | 6s | 7.7倍提速 |
| 开发服务器启动时间 | ~3s | ~1s | 3倍提速 |
| HMR更新时间 | ~100ms | ~60ms | 40%提速 |
| 内存占用 | ~800MB | ~400MB | 减少50% |
advancedChunks (Replaces manualChunks)
advancedChunks(替代manualChunks)
Vite 8 introduces with declarative grouping, priority control, and size constraints:
advancedChunkstypescript
export default defineConfig({
build: {
rollupOptions: {
output: {
// NEW: advancedChunks replaces manualChunks
advancedChunks: {
groups: [
{
name: 'react-vendor',
test: /[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/,
priority: 20,
minSize: 20000, // 20KB minimum
maxSize: 250000, // 250KB maximum
},
{
name: 'ui-vendor',
test: /[\\/]node_modules[\\/]@radix-ui[\\/]/,
priority: 15,
minShareCount: 2, // Must be used by 2+ chunks
},
{
name: 'vendor',
test: /[\\/]node_modules[\\/]/,
priority: 10,
maxSize: 500000, // Auto-split if exceeds 500KB
},
],
},
},
},
},
})Key Differences from manualChunks:
| Feature | manualChunks | advancedChunks |
|---|---|---|
| Syntax | Function or object | Declarative groups array |
| Priority control | Manual ordering | Explicit |
| Size constraints | None | |
| Shared module handling | Manual | |
| Regex support | Via function | Native |
Vite 8 引入了,支持声明式分组、优先级控制和大小约束:
advancedChunkstypescript
export default defineConfig({
build: {
rollupOptions: {
output: {
// 新特性:advancedChunks替代manualChunks
advancedChunks: {
groups: [
{
name: 'react-vendor',
test: /[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/,
priority: 20,
minSize: 20000, // 最小20KB
maxSize: 250000, // 最大250KB
},
{
name: 'ui-vendor',
test: /[\\/]node_modules[\\/]@radix-ui[\\/]/,
priority: 15,
minShareCount: 2, // 必须被至少2个chunk引用
},
{
name: 'vendor',
test: /[\\/]node_modules[\\/]/,
priority: 10,
maxSize: 500000, // 超过500KB自动拆分
},
],
},
},
},
},
})与manualChunks的核心差异:
| 特性 | manualChunks | advancedChunks |
|---|---|---|
| 语法 | 函数或对象 | 声明式数组分组 |
| 优先级控制 | 手动排序 | 显式 |
| 大小约束 | 无 | |
| 共享模块处理 | 手动实现 | |
| 正则支持 | 通过函数实现 | 原生 |
When to Use Vite 7 vs Vite 8
Vite 7与Vite 8的适用场景
| Scenario | Recommendation | Reason |
|---|---|---|
| New greenfield project | Vite 8 | Latest features, best performance |
| Existing stable production app | Vite 7 (evaluate 8) | Stability, proven track record |
| Build times > 30s | Vite 8 | Significant improvement |
| Complex plugin ecosystem | Vite 7 (test 8) | Some plugins may need updates |
| Monorepo with many packages | Vite 8 | Memory and speed benefits |
| Enterprise with strict stability | Vite 7 | LTS-style support |
| 场景 | 推荐方案 | 理由 |
|---|---|---|
| 全新项目 | Vite 8 | 最新特性、最佳性能 |
| 现有稳定生产应用 | Vite 7(评估Vite 8) | 稳定性、成熟的使用记录 |
| 构建时间>30s | Vite 8 | 显著的性能提升 |
| 复杂插件生态 | Vite 7(测试Vite 8) | 部分插件可能需要更新 |
| 包含多个包的单体仓库 | Vite 8 | 内存和速度优势 |
| 对稳定性要求严格的企业级应用 | Vite 7 | 类LTS支持 |
Full Bundle Mode (Upcoming)
全打包模式(即将推出)
Vite 8.1+ will introduce optional Full Bundle Mode for production builds:
typescript
export default defineConfig({
build: {
// Preview API - may change
fullBundleMode: true,
},
})Benefits:
- Single unified bundle (no code splitting)
- Optimal for small apps, libraries, or embedded contexts
- Eliminates chunk loading overhead
- Better for offline-first applications
Vite 8.1+ 将为生产构建引入可选的全打包模式:
typescript
export default defineConfig({
build: {
// 预览API - 可能会变更
fullBundleMode: true,
},
})优势:
- 单一统一打包文件(无代码拆分)
- 适用于小型应用、库或嵌入式场景
- 消除chunk加载开销
- 更适合离线优先应用
Oxc Integration Benefits
Oxc集成优势
Rolldown is built on Oxc (Oxidation Compiler), providing:
- Parsing: 3x faster than SWC, 100x faster than Babel
- Transformation: Unified transform pipeline
- Tree-shaking: More aggressive dead code elimination
- Scope hoisting: Better than Rollup's implementation
- Minification: Oxc minifier (optional, in development)
typescript
export default defineConfig({
build: {
// Future Oxc minifier option (when stable)
// minify: 'oxc',
},
})Rolldown 基于Oxc(Oxidation Compiler)构建,提供:
- 解析速度:比SWC快3倍,比Babel快100倍
- 转换流程:统一的转换流水线
- 摇树优化:更激进的死代码消除
- 作用域提升:优于Rollup的实现
- 代码压缩:Oxc压缩器(开发中,可选)
typescript
export default defineConfig({
build: {
// 未来的Oxc压缩器选项(稳定后推出)
// minify: 'oxc',
},
})Migration Checklist
迁移检查清单
[ ] Review plugin compatibility (most work unchanged)
[ ] Test with rolldown-vite first if risk-averse
[ ] Replace manualChunks with advancedChunks
[ ] Remove esbuild-specific workarounds (no longer needed)
[ ] Update CI/CD build time expectations
[ ] Test HMR behavior (should be faster, same API)
[ ] Verify source maps work correctlyStatus: Vite 8 stable as of Feb 2026. Recommended for new projects; evaluate for existing production apps.
[ ] 检查插件兼容性(大部分插件可直接使用)
[ ] 若规避风险,先使用rolldown-vite测试
[ ] 用advancedChunks替代manualChunks
[ ] 移除esbuild相关的临时方案(不再需要)
[ ] 更新CI/CD构建时间预期
[ ] 测试HMR行为(应该更快,API保持一致)
[ ] 验证source map是否正常工作状态: Vite 8 已于2026年2月发布稳定版。推荐新项目使用;现有生产应用建议评估后升级。
Key Decisions
核心决策建议
| Decision | Recommendation |
|---|---|
| Multi-env builds | Use Vite 7 Environment API |
| Plugin scope | Use |
| SSR | Middleware mode for dev, separate builds for prod |
| Chunks | Manual chunks for vendor/router separation |
| 决策场景 | 推荐方案 |
|---|---|
| 多环境构建 | 使用Vite 7 Environment API |
| 插件范围 | 为环境感知型插件使用 |
| SSR | 开发使用中间件模式,生产使用分离构建 |
| 代码拆分 | 用manualChunks分离依赖包/路由 |
Related Skills
相关技能
- - Fast linting alongside Vite
biome-linting - - SSR integration
ork:react-server-components-framework - - Edge environment builds
edge-computing-patterns
- - 与Vite搭配的快速代码检查工具
biome-linting - - SSR集成框架
ork:react-server-components-framework - - 边缘环境构建模式
edge-computing-patterns
References
参考资料
- Environment API - Multi-environment builds
- Plugin Development - Plugin hooks
- SSR Configuration - SSR setup
- Library Mode - Building packages
- Chunk Optimization - Build optimization
- Environment API - 多环境构建
- Plugin Development - 插件钩子
- SSR Configuration - SSR设置
- Library Mode - 包构建
- Chunk Optimization - 构建优化