Skip to content

Commit 3a15f55

Browse files
release: v2.9.1 Merge pull request #420 from vitejs/dev
2 parents d731035 + 804431e commit 3a15f55

9 files changed

+211
-19
lines changed

config/index.md

+58-9
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,17 @@ export default {
2323
vite --config my-config.js
2424
```
2525

26-
注意,Vite 会替换 `__filename``__dirname` 以及 `import.meta.url`。如果使用这些名称作为变量名可能会导致代码报错:
26+
::: tip 注意
27+
注意,Vite 会在 **CommonJS****TypeScript** 配置文件中替换 `__filename``__dirname` 以及 `import.meta.url`。如果使用这些名称作为变量名可能会导致代码报错:
2728

2829
```js
2930
const __filename = "value"
3031
// will be transformed to
3132
const "path/vite.config.js" = "value"
3233
```
3334

35+
:::
36+
3437
### 配置智能提示 {#config-intellisense}
3538

3639
因为 Vite 本身附带 Typescript 类型,所以你可以通过 IDE 和 jsdoc 的配合来实现智能提示:
@@ -92,6 +95,23 @@ export default defineConfig(async ({ command, mode }) => {
9295
})
9396
```
9497

98+
### Environment Variables {#environment-variables}
99+
100+
Vite 默认是不加载 `.env` 文件的,因为这些文件需要在执行完 Vite 配置后才能确定加载哪一个,举个例子,`root``envDir` 选项会影响加载行为。不过当你的确需要时,你可以使用 Vite 导出的 `loadEnv` 函数来加载指定的 `.env` 文件
101+
102+
```js
103+
import { defineConfig, loadEnv } from 'vite'
104+
105+
export default defineConfig(({ command, mode }) => {
106+
// 根据当前工作目录中的 `mode` 加载 .env 文件
107+
const env = loadEnv(mode, process.cwd())
108+
return {
109+
// 构建特定配置
110+
}
111+
})
112+
```
113+
114+
95115
## 共享配置 {#shared-options}
96116

97117
### root {#root}
@@ -131,13 +151,15 @@ export default defineConfig(async ({ command, mode }) => {
131151

132152
定义全局常量替换方式。其中每项在开发环境下会被定义在全局,而在构建时被静态替换。
133153

134-
- `2.0.0-beta.70` 版本开始,字符串值将直接作为一个表达式,所以如果定义为了一个字符串常量,它需要被显式地引用(例如:通过 `JSON.stringify`
154+
- 为了与 [esbuild 的行为](https://esbuild.github.io/api/#define)保持一致,表达式必须为一个 JSON 对象(null、boolean、number、string、数组或对象),亦或是一个单独的标识符
135155

136156
- 替换只会在匹配到周围是单词边界(`\b`)时执行。
137157

158+
::: warning
138159
因为它是不经过任何语法分析,直接替换文本实现的,所以我们建议只对 CONSTANTS 使用 `define`
139160

140161
例如,`process.env.FOO``__APP_VERSION__` 就非常适合。但 `process``global` 不应使用此选项。变量相关应使用 shim 或 polyfill 代替。
162+
:::
141163

142164
::: tip NOTE
143165
对于使用 TypeScript 的开发者来说,请确保在 `env.d.ts``vite-env.d.ts` 文件中添加类型声明,以获得类型检查以及代码提示。
@@ -220,6 +242,10 @@ export default defineConfig(async ({ command, mode }) => {
220242

221243
Vite 有一个“允许的情景”列表,并且会匹配列表中第一个情景。默认允许的情景是:`import``module``browser``default` 和基于当前情景为 `production/development``resolve.conditions` 配置项使得我们可以指定其他允许的情景。
222244

245+
:::warning 解决子路径导出问题
246+
导出以“/”结尾的 key 已被 Node 弃用,可能无法正常工作。请联系包的作者改为使用 [`*` 子路径模式](https://nodejs.org/api/packages.html#package-entry-points)
247+
:::
248+
223249
### resolve.mainFields {#resolve-mainfields}
224250

225251
- **类型:** `string[]`
@@ -272,28 +298,39 @@ export default defineConfig(async ({ command, mode }) => {
272298

273299
- **类型:** `string | (postcss.ProcessOptions & { plugins?: postcss.Plugin[] })`
274300

275-
内联的 PostCSS 配置(格式同 `postcss.config.js`),或者一个(默认基于项目根目录的)自定义的 PostCSS 配置路径。其路径搜索是通过 [postcss-load-config](https://github.com/postcss/postcss-load-config) 实现的。
301+
内联的 PostCSS 配置(格式同 `postcss.config.js`),或者一个(默认基于项目根目录的)自定义的 PostCSS 配置路径。其路径搜索是通过 [postcss-load-config](https://github.com/postcss/postcss-load-config) 实现的,并且只加载支持的配置文件名称
276302

277303
注意:如果提供了该内联配置,Vite 将不会搜索其他 PostCSS 配置源。
278304

279305
### css.preprocessorOptions {#css-preprocessoroptions}
280306

281307
- **类型:** `Record<string, object>`
282308

283-
指定传递给 CSS 预处理器的选项。例如:
309+
指定传递给 CSS 预处理器的选项。文件扩展名用作选项的键,例如:
284310

285311
```js
286312
export default defineConfig({
287313
css: {
288314
preprocessorOptions: {
289315
scss: {
290316
additionalData: `$injectedColor: orange;`
317+
},
318+
styl: {
319+
additionalData: `$injectedColor ?= orange`
291320
}
292321
}
293322
}
294323
})
295324
```
296325

326+
### css.devSourcemap
327+
328+
- **实验性**
329+
- **类型:** `boolean`
330+
- **默认:** `false`
331+
332+
在开发过程中是否启用 sourcemap。
333+
297334
### json.namedExports {#json-namedexports}
298335

299336
- **类型:** `boolean`
@@ -325,7 +362,7 @@ export default defineConfig(async ({ command, mode }) => {
325362
})
326363
```
327364

328-
默认情况下,ESbuild 会被应用在 `ts``jsx``tsx` 文件。你可以通过 `esbuild.include``esbuild.exclude` 对要处理的文件类型进行配置,这两个配置的类型应为 `string | RegExp | (string | RegExp)[]`
365+
默认情况下,ESbuild 会被应用在 `ts``jsx``tsx` 文件。你可以通过 `esbuild.include``esbuild.exclude` 对要处理的文件类型进行配置,这两个配置的值可以是一个正则表达式、一个 [picomatch](https://github.com/micromatch/picomatch#globbing-features) 模式,或是一个值为这两种类型的数组
329366

330367
此外,你还可以通过 `esbuild.jsxInject` 来自动为每一个被 ESbuild 转换的文件注入 JSX helper。
331368

@@ -344,7 +381,7 @@ export default defineConfig(async ({ command, mode }) => {
344381
- **类型:** `string | RegExp | (string | RegExp)[]`
345382
- **相关内容:** [静态资源处理](/guide/assets)
346383

347-
指定额外的 [picomatch 模式](https://github.com/micromatch/picomatch) 作为静态资源处理,因此:
384+
指定额外的 [picomatch 模式](https://github.com/micromatch/picomatch#globbing-features) 作为静态资源处理,因此:
348385

349386
- 当从 HTML 引用它们或直接通过 `fetch` 或 XHR 请求它们时,它们将被插件转换管道排除在外。
350387

@@ -494,7 +531,13 @@ export default defineConfig(async ({ command, mode }) => {
494531

495532
为开发服务器配置 CORS。默认启用并允许任何源,传递一个 [选项对象](https://github.com/expressjs/cors) 来调整行为或设为 `false` 表示禁用。
496533

497-
### server.force {#server-force}
534+
### server.headers ${server-hmr}
535+
536+
- **类型:** `OutgoingHttpHeaders`
537+
538+
指定服务器响应的 header。
539+
540+
### server.force
498541

499542
- **类型:** `boolean`
500543
- **相关内容:** [依赖预构建](/guide/dep-pre-bundling)
@@ -575,6 +618,12 @@ async function createServer() {
575618
createServer()
576619
```
577620

621+
### server.base {#server-base}
622+
623+
- **类型:** `string | undefined`
624+
625+
在 HTTP 请求中预留此文件夹,用于代理 Vite 作为子文件夹时使用。应该以 `/` 字符开始和结束。
626+
578627
### server.fs.strict {#server-fs-strict}
579628

580629
- **类型:** `boolean`
@@ -918,9 +967,9 @@ export default defineConfig({
918967

919968
- **类型:** `string | string[]`
920969

921-
默认情况下,Vite 会抓取你的 `index.html` 来检测需要预构建的依赖项。如果指定了 `build.rollupOptions.input`,Vite 将转而去抓取这些入口点。
970+
默认情况下,Vite 会抓取你的 `index.html` 来检测需要预构建的依赖项(忽略了`node_modules``build.outDir``__tests__``coverage`。如果指定了 `build.rollupOptions.input`,Vite 将转而去抓取这些入口点。
922971

923-
如果这两者都不合你意,则可以使用此选项指定自定义条目——该值需要遵循 [fast-glob 模式](https://github.com/mrmlnc/fast-glob#basic-syntax) ,或者是相对于 Vite 项目根的模式数组。这将覆盖掉默认条目推断
972+
如果这两者都不合你意,则可以使用此选项指定自定义条目——该值需要遵循 [fast-glob 模式](https://github.com/mrmlnc/fast-glob#basic-syntax) ,或者是相对于 Vite 项目根目录的匹配模式数组。当显式声明了 `optimizeDeps.entries` 时默认只有 `node_modules``build.outDir` 文件夹会被忽略。如果还需忽略其他文件夹,你可以在模式列表中使用以 `!` 为前缀的、用来匹配忽略项的模式
924973

925974
### optimizeDeps.exclude {#optimizedeps-exclude}
926975

guide/api-hmr.md

+9-1
Original file line numberDiff line numberDiff line change
@@ -122,4 +122,12 @@ if (import.meta.hot) {
122122
- `'vite:beforePrune'` 当不再需要的模块即将被剔除时
123123
- `'vite:error'` 当发生错误时(例如,语法错误)
124124
125-
自定义 HMR 事件可以由插件发送。更多细节详见 [handleHotUpdate](./api-plugin#handleHotUpdate)。
125+
自定义 HMR 事件可以由插件发送。更多细节详见 [handleHotUpdate](./api-plugin#handleHotUpdate)。
126+
127+
## `hot.send(event, data)`
128+
129+
发送自定义事件到 Vite 开发服务器。
130+
131+
如果在连接前调用,数据会先被缓存、等到连接建立好后再发送。
132+
133+
查看 [客户端与服务器的数据交互](/guide/api-plugin.html#client-server-communication) 一节获取更多细节。

guide/api-plugin.md

+85-1
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,7 @@ apply(config, { command }) {
458458
- 没有使用 [`moduleParsed`](https://rollupjs.org/guide/en/#moduleparsed) 钩子。
459459
- 它在打包钩子和输出钩子之间没有很强的耦合。
460460

461-
如果一个 Rollup 插件只在构建阶段有意义,则在 `build.rollupOptions.plugins` 下指定即可。
461+
如果一个 Rollup 插件只在构建阶段有意义,则在 `build.rollupOptions.plugins` 下指定即可。它的工作原理与Vite插件的 `enforce: 'post'``apply: 'build'` 相同。
462462

463463
你也可以用 Vite 独有的属性来扩展现有的 Rollup 插件:
464464

@@ -492,3 +492,87 @@ import { normalizePath } from 'vite'
492492
normalizePath('foo\\bar') // 'foo/bar'
493493
normalizePath('foo/bar') // 'foo/bar'
494494
```
495+
496+
## Client-server Communication
497+
498+
Since Vite 2.9, we provide some utilities for plugins to help handle the communication with clients.
499+
500+
### Server to Client
501+
502+
On the plugin side, we could use `server.ws.send` to boardcast events to all the clients:
503+
504+
```js
505+
// vite.config.js
506+
export default defineConfig({
507+
plugins: [
508+
{
509+
// ...
510+
configureServer(server) {
511+
server.ws.send('my:greetings', { msg: 'hello' })
512+
}
513+
}
514+
]
515+
})
516+
```
517+
518+
::: tip NOTE
519+
We recommend **alway prefixing** your event names to avoid collisions with other plugins.
520+
:::
521+
522+
On the client side, use [`hot.on`](/guide/api-hmr.html#hot-on-event-cb) to listen to the events:
523+
524+
```ts
525+
// client side
526+
if (import.meta.hot) {
527+
import.meta.hot.on('my:greetings', (data) => {
528+
console.log(data.msg) // hello
529+
})
530+
}
531+
```
532+
533+
### Client to Server
534+
535+
To send events from the client to the server, we can use [`hot.send`](/guide/api-hmr.html#hot-send-event-payload):
536+
537+
```ts
538+
// client side
539+
if (import.meta.hot) {
540+
import.meta.hot.send('my:from-client', { msg: 'Hey!' })
541+
}
542+
```
543+
544+
Then use `server.ws.on` and listen to the events on the server side:
545+
546+
```js
547+
// vite.config.js
548+
export default defineConfig({
549+
plugins: [
550+
{
551+
// ...
552+
configureServer(server) {
553+
server.ws.on('my:from-client', (data, client) => {
554+
console.log('Message from client:', data.msg) // Hey!
555+
// reply only to the client (if needed)
556+
client.send('my:ack', { msg: 'Hi! I got your message!' })
557+
})
558+
}
559+
}
560+
]
561+
})
562+
```
563+
564+
### TypeScript for Custom Events
565+
566+
It is possible to type custom events by extending the `CustomEventMap` interface:
567+
568+
```ts
569+
// events.d.ts
570+
import 'vite/types/customEvent'
571+
572+
declare module 'vite/types/customEvent' {
573+
interface CustomEventMap {
574+
'custom:foo': { msg: string }
575+
// 'event-key': payload
576+
}
577+
}
578+
```

guide/assets.md

+6-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,12 @@ function getImageUrl(name) {
103103
}
104104
```
105105
106-
在生产构建时,Vite 才会进行必要的转换保证 URL 在打包和资源哈希后仍指向正确的地址。
106+
在生产构建时,Vite 才会进行必要的转换保证 URL 在打包和资源哈希后仍指向正确的地址。然而,这个 URL 字符串必须是静态的,这样才好分析。否则代码将被原样保留、因而在 `build.target` 不支持 `import.meta.url` 时会导致运行时错误。
107+
108+
```js
109+
// Vite 不会转换这个
110+
const imgUrl = new URL(imagePath, import.meta.url).href
111+
```
107112
108113
::: warning 注意:无法在 SSR 中使用
109114
如果你正在以服务端渲染模式使用 Vite 则此模式不支持,因为 `import.meta.url` 在浏览器和 Node.js 中有不同的语义。服务端的产物也无法预先确定客户端主机 URL。

guide/backend-integration.md

-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
```html
3535
<!-- 如果是在开发环境中 -->
3636
<script type="module" src="http://localhost:3000/@vite/client"></script>
37-
<script type="module" src="http://localhost:3000/main.js"></script>
3837
```
3938

4039
还要确保服务器配置为提供 Vite 工作目录中的静态资源,否则图片等资源将无法正确加载。

guide/build.md

+25
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,20 @@ module.exports = defineConfig({
4343

4444
例如,你可以使用仅在构建期间应用的插件来指定多个 Rollup 输出。
4545

46+
## 产物分块策略 {#chunking-strategy}
47+
48+
你可以配置在使用 `build.rollupOptions.output.manualChunks` 时各个 chunk 是如何分割的(查看 [Rollup 相应文档](https://rollupjs.org/guide/en/#outputmanualchunks))。到 Vite 2.8 时,默认的策略是将 chunk 分割为 `index``vendor`。这对一些 SPA 来说是好的策略,但是要对每一种用例目标都提供一种通用解决方案是非常困难的。从 Vite 2.9 起,`manualChunks` 默认情况下不再被更改。你可以通过在配置文件中添加 `splitVendorChunkPlugin` 来继续使用 “分割 Vendor Chunk” 策略:
49+
50+
```js
51+
// vite.config.js
52+
import { splitVendorChunkPlugin } from 'vite'
53+
module.exports = defineConfig({
54+
plugins: [splitVendorChunkPlugin()]
55+
})
56+
```
57+
58+
This strategy is also provided as a `splitVendorChunk({ cache: SplitVendorChunkCache })` factory, in case composition with custom logic is needed. `cache.reset()` needs to be called at `buildStart` for build watch mode to work correctly in this case.
59+
4660
## 文件变化时重新构建 {#rebuild-on-files-changs}
4761

4862
你可以使用 `vite build --watch` 来启用 rollup 的监听器。或者,你可以直接通过 `build.watch` 调整底层的 [`WatcherOptions`](https://rollupjs.org/guide/en/#watch-options) 选项:
@@ -58,6 +72,8 @@ module.exports = defineConfig({
5872
})
5973
```
6074

75+
当启用 `--watch` 标志时,对 `vite.config.js` 的改动,以及任何要打包的文件,都将触发重新构建。
76+
6177
## 多页面应用模式 {#multi-page-app}
6278

6379
假设你有下面这样的项目文件结构
@@ -127,6 +143,15 @@ module.exports = defineConfig({
127143
})
128144
```
129145

146+
入口文件将包含可以由你的包的用户导入的导出:
147+
148+
```js
149+
// lib/main.js
150+
import Foo from './Foo.vue'
151+
import Bar from './Bar.vue'
152+
export { Foo, Bar }
153+
```
154+
130155
使用如上配置运行 `vite build` 时,将会使用一套面向库的 Rollup 预设,并且将为该库提供两种构建格式:`es``umd` (可在 `build.lib` 中配置):
131156

132157
```

guide/dep-pre-bundling.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ Pre-bundling dependencies: (正在预构建依赖:)
2828

2929
通过预构建 `lodash-es` 成为一个模块,我们就只需要一个 HTTP 请求了!
3030

31-
请注意,这只会应用在开发模式下。
31+
::: tip 注意
32+
依赖与构建仅会在开发模式下应用,并会使用 `esbuild` 将依赖转为 ESM 模块。在生产构建中则会使用 `@rollup/plugin-commonjs`
33+
:::
3234

3335
## 自动依赖搜寻 {#automatic-dependency-discovery}
3436

guide/env-and-mode.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ Vite 使用 [dotenv](https://github.com/motdotla/dotenv) 从你的 [环境目录
3737

3838
一份用于指定模式的文件(例如 `.env.production`)会比通用形式的优先级更高(例如 `.env`)。
3939

40-
另外,Vite 执行时已经存在的环境变量有最高的优先级,不会被 `.env` 类文件覆盖。
40+
另外,Vite 执行时已经存在的环境变量有最高的优先级,不会被 `.env` 类文件覆盖。例如当运行 `VITE_SOME_KEY=123 vite build` 的时候。
4141

4242
`.env` 类文件会在 Vite 启动一开始时被加载,而改动会在重启服务器后生效。
4343
:::

0 commit comments

Comments
 (0)