Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .vitepress/theme/composables/sponsor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,14 @@ const viteSponsors: Pick<Sponsors, 'special' | 'gold'> = {
img: '/astro.svg',
},
],
gold: [],
gold: [
// through GitHub -> OpenCollective
{
name: 'Remix',
url: 'https://remix.run/',
img: '/remix.svg',
},
],
}

export function useSponsor() {
Expand Down
6 changes: 3 additions & 3 deletions config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ Vite 也直接支持 TS 配置文件。你可以在 `vite.config.ts` 中使用 `

## 情景配置 {#conditional-config}

如果配置文件需要基于(`dev`/`serve` 或 `build`)命令或者不同的 [模式](/guide/env-and-mode) 来决定选项,亦或者是一个 SSR 构建(`ssrBuild`),则可以选择导出这样一个函数:
如果配置文件需要基于(`dev`/`serve` 或 `build`)命令或者不同的 [模式](/guide/env-and-mode) 来决定选项,亦或者是一个 SSR 构建(`isSsrBuild`)、一个正在预览的构建产物(`isPreview`),则可以选择导出这样一个函数:

```js
export default defineConfig(({ command, mode, ssrBuild }) => {
export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
if (command === 'serve') {
return {
// dev 独有配置
Expand All @@ -67,7 +67,7 @@ export default defineConfig(({ command, mode, ssrBuild }) => {

需要注意的是,在 Vite 的 API 中,在开发环境下 `command` 的值为 `serve`(在 CLI 中, `vite dev` 和 `vite serve` 是 `vite` 的别名),而在生产环境下为 `build`(`vite build`)。

`ssrBuild` 仍是实验性的。它只在构建过程中可用,而不是一个更通用的 `ssr` 标志,因为在开发过程中,我们唯一的服务器会共享处理 SSR 和非 SSR 请求的配置。某些工具可能没有区分浏览器和 SSR 两种构建目标的命令,那么这个值可能是 `undefined`,因此需要采用显式的比较表达式
`isSsrBuild` 和 `isPreview` 是额外的可选标志,用于区分 `build` 和 `serve` 命令的类型。一些加载 Vite 配置的工具可能不支持这些标志,而会传递 `undefined`。因此,建议使用 `true` 和 `false` 的显式比较

## 异步配置 {#async-config}

Expand Down
2 changes: 1 addition & 1 deletion config/server-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export default defineConfig({

## server.https {#server-https}

- **类型:** `boolean | https.ServerOptions`
- **类型:** `https.ServerOptions`

启用 TLS + HTTP/2。注意:当 [`server.proxy` 选项](#server-proxy) 也被使用时,将会仅使用 TLS。

Expand Down
10 changes: 10 additions & 0 deletions guide/api-hmr.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,16 @@ if (import.meta.hot) {

`import.meta.hot.data` 对象在同一个更新模块的不同实例之间持久化。它可以用于将信息从模块的前一个版本传递到下一个版本。

注意,不支持对 `data` 本身的重新赋值。相反,你应该对 `data` 对象的属性进行突变,以便保留从其他处理程序添加的信息。

```js
// ok
import.meta.hot.data.someValue = 'hello'

// 不支持
import.meta.hot.data = { someValue: 'hello' }
```

## `hot.decline()` {#hot-decline}

目前是一个空操作并暂留用于向后兼容。若有新的用途设计可能在未来会发生变更。要指明某模块是不可热更新的,请使用 `hot.invalidate()`。
Expand Down
4 changes: 3 additions & 1 deletion guide/api-javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,10 +249,12 @@ async function resolveConfig(
inlineConfig: InlineConfig,
command: 'build' | 'serve',
defaultMode = 'development',
defaultNodeEnv = 'development',
isPreview = false,
): Promise<ResolvedConfig>
```

该 `command` 值在开发环境(即 CLI 命令 `vite`、`vite dev` 和 `vite serve`) 为 `serve`。
该 `command` 值在开发环境和预览环境 为 `serve`,而在构建环境是 `build`。

## `mergeConfig`

Expand Down
10 changes: 0 additions & 10 deletions guide/env-and-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,6 @@ Vite 在一个特殊的 **`import.meta.env`** 对象上暴露环境变量。这

- **`import.meta.env.SSR`**: {boolean} 应用是否运行在 [server](./ssr.md#conditional-logic) 上。

### 生产环境替换 {#production-replacement}

在生产环境中,这些环境变量会在构建时被**静态替换**,因此,在引用它们时请使用完全静态的字符串。动态的 key 将无法生效。例如,动态 key 取值 `import.meta.env[key]` 是无效的。

它还将替换出现在 JavaScript 和 Vue 模板中的字符串。这本应是非常少见的,但也可能是不小心为之的。在这种情况下你可能会看到类似 `Missing Semicolon` 或 `Unexpected token` 等错误,例如当 `"process.env.NODE_ENV"` 被替换为 `""development": "`。有一些方法可以避免这个问题:

- 对于 JavaScript 字符串,你可以使用 unicode 零宽度空格来分割这个字符串,例如: `'import.meta\u200b.env.MODE'`。

- 对于 Vue 模板或其他编译到 JavaScript 字符串的 HTML,你可以使用 [`<wbr>` 标签](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr),例如:`import.meta.<wbr>env.MODE`。

## `.env` 文件 {#env-files}

Vite 使用 [dotenv](https://github.com/motdotla/dotenv) 从你的 [环境目录](/config/shared-options.md#envdir) 中的下列文件加载额外的环境变量:
Expand Down
25 changes: 25 additions & 0 deletions guide/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ export type { T }

#### `isolatedModules`

- [TypeScript 文档](https://www.typescriptlang.org/tsconfig#isolatedModules)

应该设置为 `true`。

这是因为 `esbuild` 只执行没有类型信息的转译,它并不支持某些特性,如 `const enum` 和隐式类型导入。
Expand All @@ -67,8 +69,12 @@ export type { T }

#### `useDefineForClassFields`

- [TypeScript 文档](https://www.typescriptlang.org/tsconfig#useDefineForClassFields)

从 Vite v2.5.0 开始,如果 TypeScript 的 target 是 `ESNext` 或 `ES2022` 及更新版本,此选项默认值则为 `true`。这与 [`tsc` v4.3.2 及以后版本的行为](https://github.com/microsoft/TypeScript/pull/42663) 一致。这也是标准的 ECMAScript 的运行时行为。

若设了其他 TypeScript 目标,则本项会默认为 `false`.

但对于那些习惯其他编程语言或旧版本 TypeScript 的开发者来说,这可能是违反直觉的。
你可以参阅 [TypeScript 3.7 发布日志](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier) 中了解更多关于如何兼容的信息。

Expand All @@ -78,13 +84,32 @@ export type { T }

但是有几个库还没有兼容这个新的默认值,其中包括 [`lit-element`](https://github.com/lit/lit-element/issues/1030)。如果遇到这种情况,请将 `useDefineForClassFields` 设置为 `false`。

#### `target` {#target}

- [TypeScript 文档](https://www.typescriptlang.org/tsconfig#target)

Vite 默认不会转译 TypeScript,而是使用 `esbuild` 的默认行为。

该 [`esbuild.target`](/config/shared-options.html#esbuild) 选项可以用来代替上述行为,默认值为 `esnext`,以进行最小的转译。在构建中,[`build.target`](/config/build-options.html#build-target) 选项优先级更高,如果需要也可以设置。

::: warning `useDefineForClassFields`
如果 `target` 不是 `ESNext` 或 `ES2022` 或更新版本,或者没有 `tsconfig.json` 文件,`useDefineForClassFields` 将默认为 `false`,这可能会导致默认的 `esbuild.target` 值为 `esnext` 的问题。它可能会转译为 [static initialization blocks](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks#browser_compatibility),这在你的浏览器中可能不被支持。

因此,建议将 `target` 设置为 `ESNext` 或 `ES2022` 或更新版本,或者在配置 `tsconfig.json` 时将 `useDefineForClassFields` 显式设置为 `true`。
:::

#### 影响构建结果的其他编译器选项 {#other-compiler-options-affecting-the-build-result}

- [`extends`](https://www.typescriptlang.org/tsconfig#extends)
- [`importsNotUsedAsValues`](https://www.typescriptlang.org/tsconfig#importsNotUsedAsValues)
- [`preserveValueImports`](https://www.typescriptlang.org/tsconfig#preserveValueImports)
- [`verbatimModuleSyntax`](https://www.typescriptlang.org/tsconfig#verbatimModuleSyntax)
- [`jsx`](https://www.typescriptlang.org/tsconfig#jsx)
- [`jsxFactory`](https://www.typescriptlang.org/tsconfig#jsxFactory)
- [`jsxFragmentFactory`](https://www.typescriptlang.org/tsconfig#jsxFragmentFactory)
- [`jsxImportSource`](https://www.typescriptlang.org/tsconfig#jsxImportSource)
- [`experimentalDecorators`](https://www.typescriptlang.org/tsconfig#experimentalDecorators)
- [`alwaysStrict`](https://www.typescriptlang.org/tsconfig#alwaysStrict)

如果你的代码库很难迁移到 `"isolatedModules": true`,或许你可以尝试通过第三方插件来解决,比如 [rollup-plugin-friendly-type-imports](https://www.npmjs.com/package/rollup-plugin-friendly-type-imports)。但是,这种方式不被 Vite 官方支持。

Expand Down
62 changes: 56 additions & 6 deletions guide/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Vite 现在使用 Rollup 4,它也带来了一些重大的变化,特别是:
- 对于 Vite 插件,`this.resolve` 的 `skipSelf` 选项现在默认为 `true`。
- 对于 Vite 插件,`this.parse` 现在只支持 `allowReturnOutsideFunction` 选项。

你可以阅读 [Rollup 的发布说明](https://github.com/rollup/rollup/releases/tag/v4.0.0) 中的破坏性变更,了解在 `build.rollupOptions` 中构建相关的变更。
你可以阅读 [Rollup 的发布说明](https://github.com/rollup/rollup/releases/tag/v4.0.0) 中的破坏性变更,了解在 [`build.rollupOptions`](/config/build-options.md#build-rollupoptions) 中构建相关的变更。

## 废弃 CJS Node API {#deprecate-cjs-node-api}

Expand All @@ -34,7 +34,7 @@ CJS 的 Node API 已经被废弃。当调用 `require('vite')` 时,将会记

## 重新设计 `define` 和 `import.meta.env.*` 的替换策略 {#rework-define-and-import-meta-env-replacement-strategy}

在 Vite 4 中,`define` 和 `import.meta.env.*` 特性在开发和构建中使用的是不同的替换策略:
在 Vite 4 中,[`define`](/config/shared-options.md#define)[`import.meta.env.*`](/guide/env-and-mode.md#env-variables) 特性在开发和构建中使用的是不同的替换策略:

- 在开发时,这两个特性分别作为全局变量注入到 `globalThis` 和 `import.meta` 中。
- 在构建时,这两个特性都使用正则表达式进行静态替换。
Expand Down Expand Up @@ -98,24 +98,69 @@ const foo = _foo.default

### `worker.plugins` 现在是一个函数 {#worker-plugins-is-now-a-function}

在 Vite 4 中,`worker.plugins` 接受一个插件数组 (`(Plugin | Plugin[])[]`)。从 Vite 5 开始,它需要配置为一个返回插件数组的函数 (`() => (Plugin | Plugin[])[]`)。这个改变是为了让并行的 worker 构建运行得更加一致和可预测。
在 Vite 4 中,[`worker.plugins`](/config/worker-options.md#worker-plugins) 接受一个插件数组 (`(Plugin | Plugin[])[]`)。从 Vite 5 开始,它需要配置为一个返回插件数组的函数 (`() => (Plugin | Plugin[])[]`)。这个改变是为了让并行的 worker 构建运行得更加一致和可预测。

### 允许路径包含 `.` 回退到 index.html {#allow-path-containing-to-fallback-to-index-html}

在 Vite 4 中,即使 `appType` 被设置为 `'SPA'`(默认),访问包含 `.` 的路径也不会回退到 index.html。从 Vite 5 开始,它将会回退到 index.html。
在 Vite 4 中,即使 [`appType`](/config/shared-options.md#apptype) 被设置为 `'SPA'`(默认),访问包含 `.` 的路径也不会回退到 index.html。从 Vite 5 开始,它将会回退到 index.html。

注意浏览器将不再在控制台中显示 404 错误消息,如果你将图片路径指向一个不存在的文件(例如 `<img src="./file-does-not-exist.png">`)。

### Align dev and preview HTML serving behaviour {#align-dev-and-preview-html-serving-behaviour}

在 Vite 4 中,开发服务器和预览服务器会根据 HTML 的目录结构和尾部斜杠的不同来提供 HTML。这会导致在测试构建后的应用时出现不一致的情况。Vite 5 重构成了一个单一的行为,如下所示,给定以下文件结构:

```
├── index.html
├── file.html
└── dir
└── index.html
```

| 请求 | 过往版本 (dev) | 过往版本 (preview) | 现在 (dev & preview) |
| ----------------- | ---------------------------- | ----------------- | ---------------------------- |
| `/dir/index.html` | `/dir/index.html` | `/dir/index.html` | `/dir/index.html` |
| `/dir` | `/index.html` (SPA fallback) | `/dir/index.html` | `/dir.html` (SPA fallback) |
| `/dir/` | `/dir/index.html` | `/dir/index.html` | `/dir/index.html` |
| `/file.html` | `/file.html` | `/file.html` | `/file.html` |
| `/file` | `/index.html` (SPA fallback) | `/file.html` | `/file.html` |
| `/file/` | `/index.html` (SPA fallback) | `/file.html` | `/index.html` (SPA fallback) |

### Manifest 文件现在默认生成到 `.vite` 目录中 {#manifest-files-are-now-generated-in-vite-directory-by-default}

在 Vite 4 中,manifest 文件(`build.manifest``build.ssrManifest`)默认会生成在 `build.outDir` 的根目录中。从 Vite 5 开始,这些文件将默认生成在 `build.outDir` 中的 `.vite` 目录中。
在 Vite 4 中,manifest 文件([`build.manifest`](/config/build-options.md#build-manifest),[`build.ssrManifest`](/config/build-options.md#build-ssrmanifest))默认会生成在 [`build.outDir`](/config/build-options.md#build-outdir) 的根目录中。从 Vite 5 开始,这些文件将默认生成在 `build.outDir` 中的 `.vite` 目录中。

### CLI 快捷功能键需要一个额外的 `Enter` 按键 {#cli-shortcuts-require-an-additional-enter-press}

CLI 快捷功能键,例如 `r` 重启开发服务器,现在需要额外的 `Enter` 按键来触发快捷功能。例如,`r + Enter` 重启开发服务器。

这个改动防止 Vite 吞噬和控制操作系统特定的快捷键,允许更好的兼容性,当将 Vite 开发服务器与其他进程结合使用时,并避免了[之前的注意事项](https://github.com/vitejs/vite/pull/14342)。

### Update `experimentalDecorators` and `useDefineForClassFields` TypeScript behaviour {#update-experimentaldecorators-and-usedefineforclassfields-typescript-behaviour}

Vite 5 使用 esbuild 0.19 并移除了 esbuild 0.18 的兼容层,这改变了 [`experimentalDecorators`](https://www.typescriptlang.org/tsconfig#experimentalDecorators) 和 [`useDefineForClassFields`](https://www.typescriptlang.org/tsconfig#useDefineForClassFields) 的处理方式。

- **`useDefineForClassFields` 默认不启用**

你需要在 `tsconfig.json` 中设置 `compilerOptions.experimentalDecorators` 为 `true` 来使用装饰器。

- **`useDefineForClassFields` 默认依赖 TypeScript 的 `target` 值**

如果 `target` 不是 `ESNext` 或 `ES2022` 或更新的版本,或者没有 `tsconfig.json` 文件,`useDefineForClassFields` 将默认为 `false`,这可能会导致默认的 `esbuild.target` 值 `esnext` 出现问题。它可能会转译为[静态初始化块](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks#browser_compatibility),这在你的浏览器中可能不被支持。

因此,建议在配置 `tsconfig.json` 时将 `target` 设置为 `ESNext` 或 `ES2022` 或更新的版本,或者将 `useDefineForClassFields` 显式地设置为 `true`。

```jsonc
{
"compilerOptions": {
// 若要使用装饰器就设为 true
"experimentalDecorators": true,
// 如果你在浏览器中看到解析错误,请设置为 true
"useDefineForClassFields": true
}
}
```

### 移除 `--https` 标志和 `https: true` {#remove-https-flag-and-https-true}

`--https` 标志设置 `https: true`。这个配置本来是要与自动 https 证书生成特性一起使用的,但这个特性在 [Vite 3 中被移除](https://v3.vitejs.dev/guide/migration.html#automatic-https-certificate-generation)。这个配置现在已经没有意义了,因为它会让Vite启动一个没有证书的 HTTPS 服务器。
Expand Down Expand Up @@ -149,12 +194,16 @@ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))
- CSS 文件的默认导出(例如 `import style from './foo.css'`):使用 `?inline` 查询参数代替
- `import.meta.globEager`:使用 `import.meta.glob('*', { eager: true })` 来代替
- `ssr.format: 'cjs'` 和 `legacy.buildSsrCjsExternalHeuristics`([#13816](https://github.com/vitejs/vite/discussions/13816))
- `server.middlewareMode: 'ssr'` 和 `server.middlewareMode: 'html'`:使用 [`appType`](/config/shared-options.md#apptype) + [`server.middlewareMode: true`](/config/server-options.md#server-middlewaremode) 来代替([#8452](https://github.com/vitejs/vite/pull/8452))

## 进阶 {#advanced}

下列改动仅会影响到插件/工具的作者:

- [[#14119] refactor!: merge `PreviewServerForHook` into `PreviewServer` type](https://github.com/vitejs/vite/pull/14119)
- The `configurePreviewServer` hook now accepts the `PreviewServer` type instead of `PreviewServerForHook` type.
- [[#14818] refactor(preview)!: use base middleware](https://github.com/vitejs/vite/pull/14818)
- Middlewares added from the returned function in `configurePreviewServer` now does not have access to the `base` when comparing the `req.url` value. This aligns the behaviour with the dev server. You can check the `base` from the `configResolved` hook if needed.

此外,还有其他一些只影响少数用户的破坏性变化。

Expand All @@ -171,7 +220,8 @@ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))
- [[#14723] fix(resolve)!: remove special .mjs handling](https://github.com/vitejs/vite/pull/14723)
- 在过去,当一个库的 `"exports"` 字段映射到一个 `.mjs` 文件时,Vite 仍然会尝试匹配 `"browser"` 和 `"module"` 字段,以修复与某些库的兼容性。现在,这种行为已被移除,以便与导出解析算法保持一致。
- [[#14733] feat(resolve)!: remove `resolve.browserField`](https://github.com/vitejs/vite/pull/14733)
- `resolve.browserField` has been deprecated since Vite 3 in favour of an updated default of `['browser', 'module', 'jsnext:main', 'jsnext']` for `resolve.mainFields`。
- `resolve.browserField` 已从 Vite 3 开始被弃用,而是使用 [`resolve.mainFields`](/config/shared-options.md#resolve-mainfields) 的更新默认值 `['browser', 'module', 'jsnext:main', 'jsnext']`。
- 重命名 `ssrBuild` 为 `isSsrBuild`。

## 从 v3 迁移 {#migration-from-v3}

Expand Down
2 changes: 2 additions & 0 deletions guide/performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Vite 的内部和官方插件已经优化,以在提供与更广泛的生态系

2. `resolveId`,`load`,和 `transform` 钩子可能会导致一些文件加载速度比其他文件慢。虽然有时无法避免,但仍值得检查可能的优化区域。例如,检查 `code` 是否包含特定关键字,或 `id` 是否匹配特定扩展名,然后再进行完整的转换。

3. `resolveId`、`load` 和 `transform` 钩子可能导致某些文件加载速度比其他文件慢。虽然有时无法避免,但仍值得检查可能的优化区域。例如,检查 `code` 是否包含特定关键字,或 `id` 是否匹配特定扩展名,然后再进行完整的转换。

转换文件所需的时间越长,加载站点时在浏览器中的请求瀑布图就会越明显。

您可以使用 `DEBUG="vite:plugin-transform" vite` 或 [vite-plugin-inspect](https://github.com/antfu/vite-plugin-inspect) 检查转换文件所需的时间。请注意,由于异步操作往往提供不准确的时间,应将这些数字视为粗略的估计,但它仍应揭示消耗很大的操作。
Expand Down
Loading