Vite 8
Vite 8.x,来自 https://vite.dev/guide/。每个声明末尾均标注其来源页面。
如何导航
- 阅读下面的快速规则。它们涵盖了最常见的错误。
- 根据任务,打开表中对应的一个参考文件。
- 对于
rollupOptions、esbuild或manualChunks,请先阅读references/migration.md。
快速开始
// vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '') // 此处 process.env 不包含 .env 文件
return {
plugins: [react()],
server: { port: Number(env.PORT ?? 5173), strictPort: true },
build: {
rolldownOptions: { output: { /* Rolldown 选项,非 Rollup */ } },
},
}
})
{ "compilerOptions": { "types": ["vite/client"], "isolatedModules": true } }
- Node.js 20.19+ 或 22.12+。使用
npm create vite@latest my-app -- --template react-ts创建项目。https://vite.dev/guide/ - 脚本:
vite(开发,端口 5173)、vite build、vite preview(端口 4173,仅本地检查,绝不用于生产服务器)。https://vite.dev/guide/cli ,https://vite.dev/config/preview-options - Vite 从不进行类型检查。请同时运行
tsc --noEmit。https://vite.dev/guide/features#transpile-only
快速规则
工具链和配置
- Rolldown 负责构建打包和依赖预打包。Oxc 负责 JS 转换和压缩,Lightning CSS 负责 CSS 压缩。https://vite.dev/guide/why#a-unified-toolchain ,https://vite.dev/guide/migration#dependency-optimizer-now-uses-rolldown ,https://vite.dev/guide/migration#javascript-transforms-by-oxc ,https://vite.dev/guide/migration#css-minification-by-lightning-css
- 使用
build.rolldownOptions、worker.rolldownOptions、optimizeDeps.rolldownOptions和oxc配置。rollupOptions、esbuildOptions和esbuild关键字已弃用。https://vite.dev/guide/migration#other-related-deprecations ,https://vite.dev/guide/migration#javascript-transforms-by-oxc - 使用顶层
input选项声明入口。它也是build.rolldownOptions.input、build.lib.entry和optimizeDeps.entries的默认值。https://vite.dev/config/shared-options#input - 代码分割通过
build.rolldownOptions.output.codeSplitting实现,而非manualChunks。https://vite.dev/guide/build#chunking-strategy tsconfig中的target被忽略:请设置build.target(默认为'baseline-widely-available')。Vite 不添加 polyfill,请使用@vitejs/plugin-legacy。https://vite.dev/guide/features#target ,https://vite.dev/config/build-options#build-target ,https://vite.dev/guide/build#browser-compatibility- Oxc 无法降级原生装饰器或混淆属性。请添加 Babel 或 SWC,并过滤到包含
@的文件。https://vite.dev/guide/migration#javascript-transforms-by-oxc ,https://vite.dev/guide/migration#javascript-minification-by-oxc - 从 CommonJS 默认导入现在可能返回整个
module.exports(出现“got: object”、“is not a function”错误)。https://vite.dev/guide/migration#consistent-commonjs-interop ,https://vite.dev/guide/troubleshooting#default-import-unexpectedly-returns-an-object
环境和模式
- 只有
VITE_前缀的变量会到达客户端代码,始终作为字符串,并在打包时内联。切勿在其中放置秘钥,也切勿设置envPrefix: ''。https://vite.dev/guide/env-and-mode#env-variables ,https://vite.dev/config/shared-options#envprefix .env文件在配置运行后加载。在vite.config中,使用loadEnv(mode, root, '')。https://vite.dev/config/#using-environment-variables-in-config- Shell 环境变量优先级高于
.env文件。修改.env文件后需要重启 Vite。https://vite.dev/guide/env-and-mode#env-files --mode和NODE_ENV相互独立:vite build --mode staging仍然是生产构建。https://vite.dev/guide/env-and-mode#node-env-and-modes- 直接编写
import.meta.env.BASE_URL字面量,方括号形式不会被替换。https://vite.dev/guide/build#public-base-path
开发服务器
- 切勿设置
server.allowedHosts: true或server.cors: true:任何网站都可能读取你的源代码。https://vite.dev/config/server-options#server-allowedhosts ,https://vite.dev/config/server-options#server-cors - 端口被占用时,Vite 会静默地使用下一个可用端口,除非设置了
strictPort: true。https://vite.dev/config/server-options#server-port - WebSocket 设置位于
server.ws下。server.hmr仅保留boolean | { overlay }。https://vite.dev/config/server-options#server-hmr - 执行
npm link或编辑链接的依赖后,使用vite --force重启。https://vite.dev/guide/troubleshooting#outdated-pre-bundled-deps-when-linking-to-a-local-package - 发生完整页面重载而非 HMR 可能是因为循环依赖(通过
vite --debug hmr诊断)。https://vite.dev/guide/troubleshooting#a-full-reload-happens-instead-of-hmr
构建与部署
- 提供 HTML 时设置
Cache-Control: no-cache,并监听vite:preloadError事件进行重载,否则部署后旧页面会出错。https://vite.dev/guide/build#load-error-handling import.meta.glob的参数必须是字面量。动态import()必须以./、../或#开头,并以文件扩展名结尾:import(`./dir/${name}.js`)。https://vite.dev/guide/features#glob-import-caveats ,https://vite.dev/guide/features#dynamic-import- 将 CSS 作为字符串导入:
import css from './a.css?inline'。不再支持.css的默认导入。https://vite.dev/guide/features#disabling-css-injection-into-the-page - 库模式会静态替换
import.meta.env.*,但保留process.env.*不变。https://vite.dev/guide/build#library-mode
插件、HMR、SSR
- 使用钩子过滤器:
transform: { filter: { id: /\\.ext$/ }, handler },并在转换非 JS 内容时返回moduleType: 'js'。https://vite.dev/guide/api-plugin#hook-filters ,https://vite.dev/guide/migration#module-type-support-and-auto-detection - 在钩子中读取
this.environment而非ssr标志。hotUpdate是handleHotUpdate的环境感知对应版本,后者的弃用仅计划在未来的大版本中实施。https://vite.dev/guide/api-environment-plugins#accessing-the-current-environment-in-hooks ,https://vite.dev/changes/hotupdate-hook configureServer的中间件在 Vite 内置中间件之前运行。返回一个函数可让中间件在之后运行。https://vite.dev/guide/api-plugin#configureserver- 在
if (import.meta.hot)内部直接编写import.meta.hot.accept(。https://vite.dev/guide/api-hmr#hot-accept-cb - SSR 开发:设置
server.middlewareMode: true和appType: 'custom',使用server.environments.ssr.runner.import()加载入口(ssrLoadModule计划弃用)。https://vite.dev/guide/ssr#setting-up-the-dev-server ,https://vite.dev/guide/api-environment-frameworks#runnabledevenvironment ,https://vite.dev/changes/ssr-using-modulerunner vite build仅构建客户端。vite build --app构建所有环境。https://vite.dev/guide/api-environment-frameworks#environments-during-build
旧模式
| 旧模式 | 当前模式 |
|---|---|
build.rollupOptions | build.rolldownOptions |
esbuild: { jsx..., jsxInject } | oxc: { jsx: {...}, jsxInject } |
optimizeDeps.esbuildOptions | optimizeDeps.rolldownOptions |
output.manualChunks | output.codeSplitting |
server.hmr.port, clientPort | server.ws.port, clientPort |
build.polyfillModulePreload | build.modulePreload.polyfill |
import s from './a.css' | import s from './a.css?inline' |
import.meta.hot.decline() (空操作) | import.meta.hot.invalidate() |
server.ssrLoadModule(url) | environment.runner.import(url) |
handleHotUpdate + server.ws.send | hotUpdate + this.environment.hot.send |
参考文件
| 文件 | 适用场景 |
|---|---|
| references/migration.md | Vite 7 到 8 迁移:重命名的选项、CommonJS 互操作、移除的功能 |
| references/config-and-env.md | 配置、loadEnv、import.meta.env、模式、base |
| references/code-features.md | TypeScript、JSX、HTML、CSS、资源、import.meta.glob、动态导入、Web Worker、WebAssembly |
| references/dev-server.md | 主机、端口、allowedHosts、CORS、代理、中间件模式、预览 |
| references/dependencies-and-performance.md | 预打包、optimizeDeps、链接的包、开发速度 |
| references/build.md | 目标、rolldownOptions、代码块、库模式 |
| references/backend-integration-and-deploy.md | 后端集成、清单、静态托管 |
| references/ssr.md | SSR 开发服务器、生产构建、外部化、插件 |
| references/plugins.md | 插件钩子、过滤器、虚拟模块、排序 |
| references/hmr-and-javascript-api.md | import.meta.hot、自定义事件、createServer、build、preview |
| references/environment-api.md | environments 配置、this.environment、configEnvironment、按环境状态 |
| references/environment-frameworks.md | builder.buildApp、ModuleRunner |
已读取页面:SOURCES.md。