vite-advanced

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vite 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
    this.environment
    in hooks
  • createBuilder
    API for coordinated builds
  • 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
  • createBuilder
    API用于协调多环境构建
  • 要求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

快速参考

FeatureVite 7 Status
Environment APIStable
ESM-only distributionDefault
Node.js requirement20.19+ or 22.12+
buildApp
hook
New for plugins
createBuilder
Multi-env builds
FeatureVite 7 Status
Environment APIStable
ESM-only distributionDefault
Node.js requirement20.19+ or 22.12+
buildApp
hook
New for plugins
createBuilder
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@8
Best for: New projects, smaller codebases, teams ready to adopt cutting-edge tooling.
Option 2: Gradual Migration with rolldown-vite
bash
npm install rolldown-vite
typescript
// 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-vite
typescript
// vite.config.ts - 仅替换导入语句
import { defineConfig } from 'rolldown-vite' // 替代 'vite'

export default defineConfig({
  // 现有配置无需修改
})
适用场景:大型生产应用、风险规避型团队、在全面升级前测试Rolldown的团队。

Performance Benchmarks

性能基准测试

Real-world improvements from production deployments:
MetricBefore (Vite 7)After (Vite 8)Improvement
Linear build time46s6s7.7x faster
Dev server startup~3s~1s3x faster
HMR updates~100ms~60ms40% faster
Memory usage~800MB~400MB50% reduction
来自生产环境部署的真实性能提升:
指标Vite 7之前Vite 8之后提升幅度
线性构建时间46s6s7.7倍提速
开发服务器启动时间~3s~1s3倍提速
HMR更新时间~100ms~60ms40%提速
内存占用~800MB~400MB减少50%

advancedChunks (Replaces manualChunks)

advancedChunks(替代manualChunks)

Vite 8 introduces
advancedChunks
with declarative grouping, priority control, and size constraints:
typescript
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:
FeaturemanualChunksadvancedChunks
SyntaxFunction or objectDeclarative groups array
Priority controlManual orderingExplicit
priority
field
Size constraintsNone
minSize
,
maxSize
Shared module handlingManual
minShareCount
Regex supportVia functionNative
test
field
Vite 8 引入了
advancedChunks
,支持声明式分组、优先级控制和大小约束:
typescript
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的核心差异:
特性manualChunksadvancedChunks
语法函数或对象声明式数组分组
优先级控制手动排序显式
priority
字段
大小约束
minSize
,
maxSize
共享模块处理手动实现
minShareCount
自动处理
正则支持通过函数实现原生
test
字段

When to Use Vite 7 vs Vite 8

Vite 7与Vite 8的适用场景

ScenarioRecommendationReason
New greenfield projectVite 8Latest features, best performance
Existing stable production appVite 7 (evaluate 8)Stability, proven track record
Build times > 30sVite 8Significant improvement
Complex plugin ecosystemVite 7 (test 8)Some plugins may need updates
Monorepo with many packagesVite 8Memory and speed benefits
Enterprise with strict stabilityVite 7LTS-style support
场景推荐方案理由
全新项目Vite 8最新特性、最佳性能
现有稳定生产应用Vite 7(评估Vite 8)稳定性、成熟的使用记录
构建时间>30sVite 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 correctly
Status: 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

核心决策建议

DecisionRecommendation
Multi-env buildsUse Vite 7 Environment API
Plugin scopeUse
this.environment
for env-aware plugins
SSRMiddleware mode for dev, separate builds for prod
ChunksManual chunks for vendor/router separation
决策场景推荐方案
多环境构建使用Vite 7 Environment API
插件范围为环境感知型插件使用
this.environment
SSR开发使用中间件模式,生产使用分离构建
代码拆分用manualChunks分离依赖包/路由

Related Skills

相关技能

  • biome-linting
    - Fast linting alongside Vite
  • ork:react-server-components-framework
    - SSR integration
  • edge-computing-patterns
    - Edge environment builds
  • biome-linting
    - 与Vite搭配的快速代码检查工具
  • ork:react-server-components-framework
    - SSR集成框架
  • 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 - 构建优化