Skip to content

Commit

Permalink
release: v2.9.1 Merge pull request #420 from vitejs/dev
Browse files Browse the repository at this point in the history
  • Loading branch information
ShenQingchuan committed Mar 31, 2022
2 parents d731035 + 804431e commit 3a15f55
Show file tree
Hide file tree
Showing 9 changed files with 211 additions and 19 deletions.
67 changes: 58 additions & 9 deletions config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,17 @@ export default {
vite --config my-config.js
```

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

```js
const __filename = "value"
// will be transformed to
const "path/vite.config.js" = "value"
```

:::

### 配置智能提示 {#config-intellisense}

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

### Environment Variables {#environment-variables}

Vite 默认是不加载 `.env` 文件的,因为这些文件需要在执行完 Vite 配置后才能确定加载哪一个,举个例子,`root``envDir` 选项会影响加载行为。不过当你的确需要时,你可以使用 Vite 导出的 `loadEnv` 函数来加载指定的 `.env` 文件

```js
import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ command, mode }) => {
// 根据当前工作目录中的 `mode` 加载 .env 文件
const env = loadEnv(mode, process.cwd())
return {
// 构建特定配置
}
})
```


## 共享配置 {#shared-options}

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

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

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

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

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

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

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

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

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

### resolve.mainFields {#resolve-mainfields}

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

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

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

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

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

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

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

```js
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
additionalData: `$injectedColor: orange;`
},
styl: {
additionalData: `$injectedColor ?= orange`
}
}
}
})
```

### css.devSourcemap

- **实验性**
- **类型:** `boolean`
- **默认:** `false`

在开发过程中是否启用 sourcemap

### json.namedExports {#json-namedexports}

- **类型:** `boolean`
Expand Down Expand Up @@ -325,7 +362,7 @@ export default defineConfig(async ({ command, mode }) => {
})
```

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

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

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

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

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

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

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

### server.force {#server-force}
### server.headers ${server-hmr}

- **类型:** `OutgoingHttpHeaders`

指定服务器响应的 header

### server.force

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

### server.base {#server-base}

- **类型:** `string | undefined`

HTTP 请求中预留此文件夹,用于代理 Vite 作为子文件夹时使用。应该以 `/` 字符开始和结束。

### server.fs.strict {#server-fs-strict}

- **类型:** `boolean`
Expand Down Expand Up @@ -918,9 +967,9 @@ export default defineConfig({

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

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

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

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

Expand Down
10 changes: 9 additions & 1 deletion guide/api-hmr.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,12 @@ if (import.meta.hot) {
- `'vite:beforePrune'` 当不再需要的模块即将被剔除时
- `'vite:error'` 当发生错误时(例如,语法错误)
自定义 HMR 事件可以由插件发送。更多细节详见 [handleHotUpdate](./api-plugin#handleHotUpdate)。
自定义 HMR 事件可以由插件发送。更多细节详见 [handleHotUpdate](./api-plugin#handleHotUpdate)。
## `hot.send(event, data)`
发送自定义事件到 Vite 开发服务器。
如果在连接前调用,数据会先被缓存、等到连接建立好后再发送。
查看 [客户端与服务器的数据交互](/guide/api-plugin.html#client-server-communication) 一节获取更多细节。
86 changes: 85 additions & 1 deletion guide/api-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ apply(config, { command }) {
- 没有使用 [`moduleParsed`](https://rollupjs.org/guide/en/#moduleparsed) 钩子。
- 它在打包钩子和输出钩子之间没有很强的耦合。

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

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

Expand Down Expand Up @@ -492,3 +492,87 @@ import { normalizePath } from 'vite'
normalizePath('foo\\bar') // 'foo/bar'
normalizePath('foo/bar') // 'foo/bar'
```

## Client-server Communication

Since Vite 2.9, we provide some utilities for plugins to help handle the communication with clients.

### Server to Client

On the plugin side, we could use `server.ws.send` to boardcast events to all the clients:

```js
// vite.config.js
export default defineConfig({
plugins: [
{
// ...
configureServer(server) {
server.ws.send('my:greetings', { msg: 'hello' })
}
}
]
})
```

::: tip NOTE
We recommend **alway prefixing** your event names to avoid collisions with other plugins.
:::

On the client side, use [`hot.on`](/guide/api-hmr.html#hot-on-event-cb) to listen to the events:

```ts
// client side
if (import.meta.hot) {
import.meta.hot.on('my:greetings', (data) => {
console.log(data.msg) // hello
})
}
```

### Client to Server

To send events from the client to the server, we can use [`hot.send`](/guide/api-hmr.html#hot-send-event-payload):

```ts
// client side
if (import.meta.hot) {
import.meta.hot.send('my:from-client', { msg: 'Hey!' })
}
```

Then use `server.ws.on` and listen to the events on the server side:

```js
// vite.config.js
export default defineConfig({
plugins: [
{
// ...
configureServer(server) {
server.ws.on('my:from-client', (data, client) => {
console.log('Message from client:', data.msg) // Hey!
// reply only to the client (if needed)
client.send('my:ack', { msg: 'Hi! I got your message!' })
})
}
}
]
})
```

### TypeScript for Custom Events

It is possible to type custom events by extending the `CustomEventMap` interface:

```ts
// events.d.ts
import 'vite/types/customEvent'
declare module 'vite/types/customEvent' {
interface CustomEventMap {
'custom:foo': { msg: string }
// 'event-key': payload
}
}
```
7 changes: 6 additions & 1 deletion guide/assets.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,12 @@ function getImageUrl(name) {
}
```
在生产构建时,Vite 才会进行必要的转换保证 URL 在打包和资源哈希后仍指向正确的地址。
在生产构建时,Vite 才会进行必要的转换保证 URL 在打包和资源哈希后仍指向正确的地址。然而,这个 URL 字符串必须是静态的,这样才好分析。否则代码将被原样保留、因而在 `build.target` 不支持 `import.meta.url` 时会导致运行时错误。
```js
// Vite 不会转换这个
const imgUrl = new URL(imagePath, import.meta.url).href
```
::: warning 注意:无法在 SSR 中使用
如果你正在以服务端渲染模式使用 Vite 则此模式不支持,因为 `import.meta.url` 在浏览器和 Node.js 中有不同的语义。服务端的产物也无法预先确定客户端主机 URL。
Expand Down
1 change: 0 additions & 1 deletion guide/backend-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
```html
<!-- 如果是在开发环境中 -->
<script type="module" src="http://localhost:3000/@vite/client"></script>
<script type="module" src="http://localhost:3000/main.js"></script>
```

还要确保服务器配置为提供 Vite 工作目录中的静态资源,否则图片等资源将无法正确加载。
Expand Down
25 changes: 25 additions & 0 deletions guide/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ module.exports = defineConfig({

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

## 产物分块策略 {#chunking-strategy}

你可以配置在使用 `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” 策略:

```js
// vite.config.js
import { splitVendorChunkPlugin } from 'vite'
module.exports = defineConfig({
plugins: [splitVendorChunkPlugin()]
})
```

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.

## 文件变化时重新构建 {#rebuild-on-files-changs}

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

当启用 `--watch` 标志时,对 `vite.config.js` 的改动,以及任何要打包的文件,都将触发重新构建。

## 多页面应用模式 {#multi-page-app}

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

入口文件将包含可以由你的包的用户导入的导出:

```js
// lib/main.js
import Foo from './Foo.vue'
import Bar from './Bar.vue'
export { Foo, Bar }
```

使用如上配置运行 `vite build` 时,将会使用一套面向库的 Rollup 预设,并且将为该库提供两种构建格式:`es``umd` (可在 `build.lib` 中配置):

```
Expand Down
4 changes: 3 additions & 1 deletion guide/dep-pre-bundling.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ Pre-bundling dependencies: (正在预构建依赖:)

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

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

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

Expand Down
2 changes: 1 addition & 1 deletion guide/env-and-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Vite 使用 [dotenv](https://github.com/motdotla/dotenv) 从你的 [环境目录

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

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

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

0 comments on commit 3a15f55

Please sign in to comment.