vite

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vite 7

Vite 7

Build tooling and dev server for React projects. Vite 7 (June 2025) is ESM-only, requires Node.js 20.19+ / 22.12+, and defaults browser target to
baseline-widely-available
. The user's stack uses
rolldown-vite
(Rust-based drop-in replacement),
@vitejs/plugin-react
,
@tailwindcss/vite
,
@tanstack/router-plugin
,
@cloudflare/vite-plugin
, and
@tanstack/react-start
.
React项目的构建工具与开发服务器。Vite 7(2025年6月发布)仅支持ESM,要求Node.js版本为20.19+ / 22.12+,默认浏览器目标为
baseline-widely-available
。用户技术栈使用
rolldown-vite
(基于Rust的开箱即用替代品)、
@vitejs/plugin-react
@tailwindcss/vite
@tanstack/router-plugin
@cloudflare/vite-plugin
以及
@tanstack/react-start

Critical Rules

核心规则

Plugin Order Matters

插件顺序至关重要

TanStack Start or TanStack Router plugin MUST come before
@vitejs/plugin-react
:
ts
plugins: [
  tanstackStart(),      // or tanstackRouter() for SPA
  tailwindcss(),
  react(),              // ALWAYS last among framework plugins
]
Wrong order causes route generation failures and HMR breakage.
TanStack Start或TanStack Router插件必须放在
@vitejs/plugin-react
之前:
ts
plugins: [
  tanstackStart(),      // SPA场景可替换为tanstackRouter()
  tailwindcss(),
  react(),              // 框架类插件中必须放在最后一位
]
顺序错误会导致路由生成失败和HMR失效。

Vite 7 is ESM-Only

Vite 7仅支持ESM

Vite 7 distributes as ESM only. Your
vite.config.ts
must use
import
/
export
syntax. CJS
require()
is not supported in config files. Node.js 20.19+ supports
require(esm)
natively, so Vite can still be required by CJS consumers.
Vite 7仅以ESM格式分发,你的
vite.config.ts
必须使用
import
/
export
语法,配置文件中不支持CJS的
require()
语法。Node.js 20.19+原生支持
require(esm)
,因此CJS侧的消费者依然可以引入Vite。

No
tailwind.config.js

无需
tailwind.config.js

Tailwind CSS v4 uses CSS-first configuration. Never create
tailwind.config.js
/
tailwind.config.ts
. Use
@tailwindcss/vite
plugin and configure in CSS via
@theme
,
@utility
,
@plugin
.
Tailwind CSS v4采用CSS优先的配置方式,不要创建
tailwind.config.js
/
tailwind.config.ts
文件,请使用
@tailwindcss/vite
插件,并在CSS中通过
@theme
@utility
@plugin
进行配置。

Environment Variables Need VITE_ Prefix

环境变量需要添加VITE_前缀

Only variables prefixed with
VITE_
are exposed to client code via
import.meta.env
. Server-only secrets must NOT use this prefix. For type safety, augment
ImportMetaEnv
in
vite-env.d.ts
.
只有带有
VITE_
前缀的变量才会通过
import.meta.env
暴露给客户端代码,仅服务端使用的密钥绝对不能使用此前缀。如需类型安全,可以在
vite-env.d.ts
中扩展
ImportMetaEnv
类型。

splitVendorChunkPlugin Is Removed

splitVendorChunkPlugin已被移除

Removed in Vite 7. Use
build.rollupOptions.output.manualChunks
for custom chunk splitting.
该插件在Vite 7中已被移除,如需自定义代码块拆分,请使用
build.rollupOptions.output.manualChunks
配置。

Configuration

配置说明

vite.config.ts (Full Stack with TanStack Start)

vite.config.ts(搭配TanStack Start的全栈项目)

ts
import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import { cloudflare } from '@cloudflare/vite-plugin'
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    tanstackStart(),
    cloudflare(),
    tailwindcss(),
    react(),
  ],
  resolve: {
    alias: {
      '@': new URL('./src', import.meta.url).pathname,
    },
  },
})
ts
import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import { cloudflare } from '@cloudflare/vite-plugin'
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    tanstackStart(),
    cloudflare(),
    tailwindcss(),
    react(),
  ],
  resolve: {
    alias: {
      '@': new URL('./src', import.meta.url).pathname,
    },
  },
})

vite.config.ts (SPA with TanStack Router)

vite.config.ts(搭配TanStack Router的SPA项目)

ts
import { defineConfig } from 'vite'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    tanstackRouter({ autoCodeSplitting: true }),
    tailwindcss(),
    react(),
  ],
  resolve: {
    alias: {
      '@': new URL('./src', import.meta.url).pathname,
    },
  },
})
ts
import { defineConfig } from 'vite'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    tanstackRouter({ autoCodeSplitting: true }),
    tailwindcss(),
    react(),
  ],
  resolve: {
    alias: {
      '@': new URL('./src', import.meta.url).pathname,
    },
  },
})

React Compiler

React Compiler配置

ts
react({
  babel: {
    plugins: [['babel-plugin-react-compiler', {}]],
  },
})
Install:
pnpm add -D babel-plugin-react-compiler
. Auto-memoizes components and hooks - no manual
useMemo
/
useCallback
.
ts
react({
  babel: {
    plugins: [['babel-plugin-react-compiler', {}]],
  },
})
安装命令:
pnpm add -D babel-plugin-react-compiler
。该插件会自动为组件和Hook添加缓存,无需手动编写
useMemo
/
useCallback

Path Aliases

路径别名配置

Use
import.meta.url
for ESM-compatible resolution (no
__dirname
in ESM):
ts
resolve: {
  alias: {
    '@': new URL('./src', import.meta.url).pathname,
  },
}
Mirror in
tsconfig.json
:
"paths": { "@/*": ["./src/*"] }
请使用
import.meta.url
实现兼容ESM的路径解析(ESM中没有
__dirname
):
ts
resolve: {
  alias: {
    '@': new URL('./src', import.meta.url).pathname,
  },
}
同时在
tsconfig.json
中同步配置:
"paths": { "@/*": ["./src/*"] }

Environment Variables

环境变量配置

Files:
.env
,
.env.local
,
.env.[mode]
,
.env.[mode].local
. Only
VITE_
-prefixed vars exposed to client. Built-in constants:
import.meta.env.MODE
,
.DEV
,
.PROD
,
.SSR
,
.BASE_URL
.
Type augmentation in
src/vite-env.d.ts
:
ts
interface ImportMetaEnv {
  readonly VITE_API_URL: string
}
interface ImportMeta {
  readonly env: ImportMetaEnv
}
支持的配置文件:
.env
.env.local
.env.[mode]
.env.[mode].local
。只有带
VITE_
前缀的变量会暴露给客户端。内置常量包括:
import.meta.env.MODE
.DEV
.PROD
.SSR
.BASE_URL
src/vite-env.d.ts
中扩展类型:
ts
interface ImportMetaEnv {
  readonly VITE_API_URL: string
}
interface ImportMeta {
  readonly env: ImportMetaEnv
}

Plugin Ecosystem

插件生态

@vitejs/plugin-react

@vitejs/plugin-react

Provides Fast Refresh (HMR for React), JSX transform, and optional Babel plugin pipeline. Always place last among framework plugins.
ts
import react from '@vitejs/plugin-react'

react()                          // zero-config default
react({ fastRefresh: false })    // disable for debugging HMR issues
提供React场景的Fast Refresh(即HMR能力)、JSX转换,以及可选的Babel插件流水线,始终要放在框架类插件的最后一位。
ts
import react from '@vitejs/plugin-react'

react()                          // 零配置默认值
react({ fastRefresh: false })    // 排查HMR问题时可禁用该功能

@tailwindcss/vite

@tailwindcss/vite

Native Vite integration for Tailwind CSS v4. Replaces PostCSS-based setup - no
postcss.config.js
needed.
ts
import tailwindcss from '@tailwindcss/vite'

tailwindcss()  // zero-config, reads @theme from CSS
Tailwind CSS v4的原生Vite集成插件,替代了基于PostCSS的配置方案,无需
postcss.config.js
文件。
ts
import tailwindcss from '@tailwindcss/vite'

tailwindcss()  // 零配置,自动读取CSS中的@theme配置

@tanstack/router-plugin/vite

@tanstack/router-plugin/vite

File-based route generation for TanStack Router. Must come before
react()
.
ts
import { tanstackRouter } from '@tanstack/router-plugin/vite'

tanstackRouter({ autoCodeSplitting: true })
为TanStack Router提供基于文件的路由生成能力,必须放在
react()
之前。
ts
import { tanstackRouter } from '@tanstack/router-plugin/vite'

tanstackRouter({ autoCodeSplitting: true })

@tanstack/react-start/plugin/vite

@tanstack/react-start/plugin/vite

Full-stack plugin for TanStack Start. Includes router plugin internally - do NOT add both.
ts
import { tanstackStart } from '@tanstack/react-start/plugin/vite'

tanstackStart()                           // default SSR
tanstackStart({ spa: { enabled: true } }) // SPA mode (no SSR)
TanStack Start的全栈插件,内部已集成路由插件,请勿同时添加两个路由相关插件。
ts
import { tanstackStart } from '@tanstack/react-start/plugin/vite'

tanstackStart()                           // 默认SSR模式
tanstackStart({ spa: { enabled: true } }) // SPA模式(无SSR)

@cloudflare/vite-plugin

@cloudflare/vite-plugin

Runs Worker code inside
workerd
during dev, matching production behavior. Uses Vite's Environment API for runtime integration.
ts
import { cloudflare } from '@cloudflare/vite-plugin'

cloudflare()  // reads wrangler.jsonc by default

// Programmatic config (no wrangler file needed)
cloudflare({
  config: {
    name: 'my-worker',
    compatibility_flags: ['nodejs_compat'],
  },
})
开发阶段在
workerd
中运行Worker代码,与生产环境行为保持一致,使用Vite的Environment API实现运行时集成。
ts
import { cloudflare } from '@cloudflare/vite-plugin'

cloudflare()  // 默认读取wrangler.jsonc配置

// 编程式配置(无需wrangler文件)
cloudflare({
  config: {
    name: 'my-worker',
    compatibility_flags: ['nodejs_compat'],
  },
})

Dev Server

开发服务器

Proxy Configuration

代理配置

ts
server: {
  proxy: {
    '/api': {
      target: 'http://localhost:8787',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/api/, ''),
    },
    '/ws': { target: 'ws://localhost:8787', ws: true },
  },
}
ts
server: {
  proxy: {
    '/api': {
      target: 'http://localhost:8787',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/api/, ''),
    },
    '/ws': { target: 'ws://localhost:8787', ws: true },
  },
}

HMR Troubleshooting

HMR问题排查

SymptomFix
Full reload instead of HMRCheck
plugin-react
is loaded
HMR not connectingSet
server.hmr.clientPort
if behind reverse proxy
Stale state after editComponent must export a single component
CSS not updatingEnsure
@tailwindcss/vite
is in plugins
Behind a reverse proxy:
ts
server: {
  hmr: { protocol: 'ws', host: 'localhost', port: 5173, clientPort: 443 },
}
现象修复方案
页面全量刷新而非HMR热更新检查是否正确加载了
plugin-react
HMR连接失败如果使用反向代理,请配置
server.hmr.clientPort
编辑后状态未更新组件文件必须只导出单个组件
CSS样式不更新确认
@tailwindcss/vite
已添加到plugins数组中
反向代理场景配置示例:
ts
server: {
  hmr: { protocol: 'ws', host: 'localhost', port: 5173, clientPort: 443 },
}

File Warmup

文件预热配置

ts
server: {
  warmup: {
    clientFiles: ['./src/components/*.tsx', './src/routes/__root.tsx'],
  },
}
ts
server: {
  warmup: {
    clientFiles: ['./src/components/*.tsx', './src/routes/__root.tsx'],
  },
}

Build Optimization

构建优化

Default Browser Target

默认浏览器目标

Vite 7 targets
baseline-widely-available
(Chrome 107+, Edge 107+, Firefox 104+, Safari 16+). Override:
build.target: 'es2020'
or
['chrome90', 'safari14']
.
Vite 7默认目标为
baseline-widely-available
(Chrome 107+、Edge 107+、Firefox 104+、Safari 16+),可通过
build.target: 'es2020'
['chrome90', 'safari14']
自定义覆盖。

Manual Chunks

手动代码块拆分

ts
build: {
  rollupOptions: {
    output: {
      manualChunks: {
        'react-vendor': ['react', 'react-dom'],
        'tanstack': ['@tanstack/react-router', '@tanstack/react-query'],
      },
    },
  },
}
Dynamic splitting by function:
ts
manualChunks(id) {
  if (id.includes('node_modules')) {
    if (id.includes('react')) return 'react-vendor'
    if (id.includes('@tanstack')) return 'tanstack'
    return 'vendor'
  }
}
ts
build: {
  rollupOptions: {
    output: {
      manualChunks: {
        'react-vendor': ['react', 'react-dom'],
        'tanstack': ['@tanstack/react-router', '@tanstack/react-query'],
      },
    },
  },
}
基于函数的动态拆分示例:
ts
manualChunks(id) {
  if (id.includes('node_modules')) {
    if (id.includes('react')) return 'react-vendor'
    if (id.includes('@tanstack')) return 'tanstack'
    return 'vendor'
  }
}

Bundle Analysis

包体积分析

bash
pnpm add -D rollup-plugin-visualizer
ts
import { visualizer } from 'rollup-plugin-visualizer'

// Add to plugins array
visualizer({ filename: 'stats.html', open: true, gzipSize: true })
See build-optimization.md for detailed chunking strategies, CSS splitting, asset inlining, source maps, and performance tuning.
bash
pnpm add -D rollup-plugin-visualizer
ts
import { visualizer } from 'rollup-plugin-visualizer'

// 添加到plugins数组中
visualizer({ filename: 'stats.html', open: true, gzipSize: true })
查看build-optimization.md了解详细的代码块拆分策略、CSS拆分、资源内联、Source Map和性能调优内容。

Rolldown Integration

Rolldown集成

What is rolldown-vite

什么是rolldown-vite

rolldown-vite
is a Rust-based drop-in replacement for Vite's bundler, developed by the Vite team (sponsored by VoidZero). It replaces both esbuild and Rollup with a single high-performance tool built on Rolldown and the Oxc toolkit. Build time reductions of 3x to 16x have been reported, with memory usage cut by up to 100x on large projects.
Rolldown will become the default bundler in Vite 8 (currently in beta). Using
rolldown-vite
today prepares your project for the transition.
Note: Vite 7 requires Vitest 3.2+ for compatibility. Earlier Vitest versions will not work.
rolldown-vite
是Vite团队开发的基于Rust的Vite打包器开箱替代品(由VoidZero赞助),它使用基于Rolldown和Oxc工具链的高性能工具替代了esbuild和Rollup。据反馈,构建速度可提升3到16倍,大型项目的内存占用最多可降低100倍。
Rolldown将成为Vite 8(当前处于beta阶段)的默认打包器,现在使用
rolldown-vite
可以为后续的版本迁移做好准备。
注意: Vite 7要求Vitest版本≥3.2才能兼容,更早的Vitest版本无法正常工作。

Installation

安装方式

In
package.json
, alias
vite
to
rolldown-vite
:
json
{
  "devDependencies": {
    "vite": "npm:rolldown-vite@latest"
  }
}
For monorepos or frameworks with Vite as a peer dependency, use overrides:
json
{
  "pnpm": {
    "overrides": {
      "vite": "npm:rolldown-vite@latest"
    }
  }
}
Then run
pnpm install
. No config changes needed - it is a drop-in replacement.
package.json
中为
vite
设置别名指向
rolldown-vite
json
{
  "devDependencies": {
    "vite": "npm:rolldown-vite@latest"
  }
}
对于单仓或者将Vite作为peer依赖的框架,请使用覆盖配置:
json
{
  "pnpm": {
    "overrides": {
      "vite": "npm:rolldown-vite@latest"
    }
  }
}
然后运行
pnpm install
即可,无需修改其他配置,它是完全开箱兼容的。

Key Differences from Standard Vite

与标准Vite的核心差异

  • No esbuild dependency - Oxc handles all transforms and minification (config still shows
    minify: 'esbuild'
    but the underlying engine is Oxc)
  • Faster builds - Rust-native bundling, especially for large projects
  • Same plugin API - Rollup/Vite plugins work without changes in most cases
  • Patch versions may break -
    rolldown-vite
    follows Vite major/minor but patches are independent
  • 无esbuild依赖:所有转换和压缩都由Oxc处理(配置中依然显示
    minify: 'esbuild'
    但底层引擎为Oxc)
  • 更快的构建速度:Rust原生打包能力,在大型项目中优势尤其明显
  • 相同的插件API:绝大多数Rollup/Vite插件无需修改即可正常运行
  • 补丁版本可能存在兼容性问题
    rolldown-vite
    跟随Vite的主/次版本号,但补丁版本是独立发布的

Compatibility Notes

兼容性说明

Most frameworks and Vite plugins work out of the box. Check the rolldown-vite repo for known issues and changelog. Some warnings about unsupported options may appear during the transition period.
绝大多数框架和Vite插件都可以开箱即用,已知问题和更新日志请查看rolldown-vite仓库,迁移阶段可能会出现部分选项不支持的警告。

Environment API

Environment API

Experimental API introduced in Vite 6, improved in Vite 7 with the
buildApp
hook. Enables multi-target builds (browser, Node.js, edge runtimes) from a single Vite config.
该实验性API在Vite 6中引入,Vite 7中新增了
buildApp
钩子进行了优化,支持在单个Vite配置中实现多目标构建(浏览器、Node.js、边缘运行时)。

How It Works

工作原理

Each environment has its own module graph, plugin pipeline, and build config. The
@cloudflare/vite-plugin
uses this to run Worker code inside
workerd
during dev, matching production behavior.
每个环境都有独立的模块依赖图、插件流水线和构建配置,
@cloudflare/vite-plugin
就是使用该API在开发阶段的
workerd
中运行Worker代码,保证与生产环境行为一致。

buildApp Hook (Vite 7)

buildApp钩子(Vite 7新增)

Frameworks coordinate building multiple environments. Config-level form (most common):
ts
export default defineConfig({
  builder: {
    async buildApp(builder) {
      await builder.build(builder.environments.client)
      await builder.build(builder.environments.server)
    },
  },
})
Plugin hook form (for plugin authors):
ts
{
  name: 'my-framework',
  buildApp: async (builder) => {
    const environments = Object.values(builder.environments)
    return Promise.all(
      environments.map((env) => builder.build(env))
    )
  },
}
框架可以通过该钩子协调多个环境的构建,最常用的是配置级写法:
ts
export default defineConfig({
  builder: {
    async buildApp(builder) {
      await builder.build(builder.environments.client)
      await builder.build(builder.environments.server)
    },
  },
})
插件钩子写法(适用于插件开发者):
ts
{
  name: 'my-framework',
  buildApp: async (builder) => {
    const environments = Object.values(builder.environments)
    return Promise.all(
      environments.map((env) => builder.build(env))
    )
  },
}

Multi-Environment Config

多环境配置

ts
export default defineConfig({
  environments: {
    client: {
      build: { outDir: 'dist/client' },
    },
    server: {
      build: { outDir: 'dist/server' },
    },
  },
})
For most projects, the
@cloudflare/vite-plugin
or
@tanstack/react-start
handles environment configuration automatically. Direct Environment API usage is for framework authors.
ts
export default defineConfig({
  environments: {
    client: {
      build: { outDir: 'dist/client' },
    },
    server: {
      build: { outDir: 'dist/server' },
    },
  },
})
对于绝大多数项目,
@cloudflare/vite-plugin
@tanstack/react-start
会自动处理环境配置,只有框架开发者需要直接使用Environment API。

Deployment

部署

Cloudflare Workers (via TanStack Start)

Cloudflare Workers(通过TanStack Start)

Add
cloudflare()
to plugins and create
wrangler.jsonc
:
jsonc
// wrangler.jsonc
{
  "name": "my-app",
  "compatibility_date": "2025-01-01",
  "compatibility_flags": ["nodejs_compat"],
  "main": "./dist/server/index.js",
  "assets": { "directory": "./dist/client" }
}
bash
pnpm vite build && pnpm wrangler deploy
在plugins中添加
cloudflare()
并创建
wrangler.jsonc
jsonc
// wrangler.jsonc
{
  "name": "my-app",
  "compatibility_date": "2025-01-01",
  "compatibility_flags": ["nodejs_compat"],
  "main": "./dist/server/index.js",
  "assets": { "directory": "./dist/client" }
}
bash
pnpm vite build && pnpm wrangler deploy

Static SPA

静态SPA

Build produces
dist/
. Deploy to any static host (Cloudflare Pages, Vercel, Netlify).
构建产物输出到
dist/
目录,可部署到任意静态托管服务(Cloudflare Pages、Vercel、Netlify)。

Prerendering (SSG)

预渲染(SSG)

ts
tanstackStart({ prerender: { enabled: true, crawlLinks: true } })
ts
tanstackStart({ prerender: { enabled: true, crawlLinks: true } })

Best Practices

最佳实践

  1. Plugin order - framework plugins first, then utilities, then
    react()
    last
  2. Use rolldown-vite - drop-in replacement with 3-16x faster builds
  3. Set
    staleTime
    in dev
    - avoid unnecessary refetches during HMR reloads
  4. Warm up critical files - use
    server.warmup
    for frequently accessed modules
  5. Split vendor chunks - separate
    react
    ,
    @tanstack/*
    into stable chunks for caching
  6. Never use
    transition-all
    - specific properties only for CSS transitions
  7. Use
    import.meta.url
    for path resolution in ESM config files
  8. Analyze bundles regularly - use
    rollup-plugin-visualizer
    before deploys
  9. Keep
    VITE_
    prefix discipline
    - only public values; secrets go in server functions
  10. Set
    build.sourcemap
    for production
    -
    'hidden'
    for error tracking without exposing source
  1. 注意插件顺序:框架类插件优先,其次是工具类插件,
    react()
    放在最后
  2. 使用rolldown-vite:开箱兼容的替代品,构建速度提升3-16倍
  3. 开发阶段设置
    staleTime
    :避免HMR重载时不必要的重复请求
  4. 预热核心文件:对高频访问的模块使用
    server.warmup
    配置
  5. 拆分第三方依赖代码块:将
    react
    @tanstack/*
    等稳定依赖拆分为独立代码块提升缓存效率
  6. 不要使用
    transition-all
    :CSS过渡只指定需要动画的属性
  7. 使用
    import.meta.url
    :在ESM配置文件中做路径解析
  8. 定期分析包体积:发布前使用
    rollup-plugin-visualizer
    检查包体积
  9. 严格遵守
    VITE_
    前缀规范
    :只有公开变量使用该前缀,密钥放在服务端函数中
  10. 生产环境配置
    build.sourcemap
    :设置为
    'hidden'
    即可支持错误追踪,又不会暴露源码

Resources

参考资源