Skip to content

Commit

Permalink
Merge branch 'main' into watch-mode
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangyu96 authored and zhangyu96 committed Apr 11, 2022
2 parents d939eb4 + eb57627 commit 995897f
Show file tree
Hide file tree
Showing 228 changed files with 4,039 additions and 1,540 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Expand Up @@ -11,6 +11,8 @@ on:
- main
- release/*
- feat/*
- fix/*
- perf/*
pull_request:
workflow_dispatch:

Expand Down
12 changes: 7 additions & 5 deletions CONTRIBUTING.md
Expand Up @@ -24,7 +24,7 @@ If you want to use break point and explore code execution you can use the ["Run

2. Click on the "Run and Debug" icon in the activity bar of the editor.

3. Click on the "Javascript Debug Terminal" button.
3. Click on the "JavaScript Debug Terminal" button.

4. It will open a terminal, then go to `packages/playground/xxx` and run `pnpm run dev`.

Expand Down Expand Up @@ -69,7 +69,9 @@ And re-run `pnpm install` to link the package.

Each package under `packages/playground/` contains a `__tests__` directory. The tests are run using [Jest](https://jestjs.io/) + [Playwright](https://playwright.dev/) with custom integrations to make writing tests simple. The detailed setup is inside `jest.config.js` and `scripts/jest*` files.

Each test can be run under either dev server mode or build mode. Make sure that [Vite has been built](#repo-setup).
Before running the tests, make sure that [Vite has been built](#repo-setup). On Windows, you may want to [activate Developer Mode](https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development) to solve [issues with symlink creation for non-admins](https://github.com/vitejs/vite/issues/7390).

Each test can be run under either dev server mode or build mode.

- `pnpm test` by default runs every test in both serve and build mode.

Expand Down Expand Up @@ -227,7 +229,7 @@ The english docs are embedded in the main Vite repo, to allow contributors to wo
1. In order to get all doc files, you first need to clone this repo in your personal account.
2. Keep all the files in `docs/` and remove everything else.

- You should setup your translation site based on all the files in `docs/` folder as a Vitepress project.
- You should setup your translation site based on all the files in `docs/` folder as a VitePress project.
(that said, `package.json` is need).

- Refresh git history by removing `.git` and then `git init`
Expand All @@ -236,7 +238,7 @@ The english docs are embedded in the main Vite repo, to allow contributors to wo

- During this stage, you may be translating documents and synchronizing updates at the same time, but don't worry about that, it's very common in translation contribution.

4. Push your commits to your Github repo. you can setup a netlify preview as well.
5. Use [Ryu-cho](https://github.com/vuejs-translations/ryu-cho) tool to setup a Github Action, automatically track English docs update later.
4. Push your commits to your GitHub repo. you can setup a netlify preview as well.
5. Use [Ryu-cho](https://github.com/vuejs-translations/ryu-cho) tool to setup a GitHub Action, automatically track English docs update later.

We recommend talking with others in Vite Land so you find more contributors for your language to share the maintenance work. Once the translation is done, communicate it to the Vite team so the repo can be moved to the official vitejs org in GitHub.
2 changes: 1 addition & 1 deletion docs/blog/announcing-vite2.md
Expand Up @@ -34,7 +34,7 @@ The [programmatic API](https://vitejs.dev/guide/api-javascript.html) has also be

### esbuild Powered Dep Pre-Bundling

Since Vite is a native ESM dev server, it pre-bundles dependencies to reduce the number browser requests and handle CommonJS to ESM conversion. Previously Vite did this using Rollup, and in 2.0 it now uses `esbuild` which results in 10-100x faster dependency pre-bundling. As a reference, cold-booting a test app with heavy dependencies like React Material UI previously took 28 seconds on an M1-powered Macbook Pro and now takes ~1.5 seconds. Expect similar improvements if you are switching from a traditional bundler based setup.
Since Vite is a native ESM dev server, it pre-bundles dependencies to reduce the number browser requests and handle CommonJS to ESM conversion. Previously Vite did this using Rollup, and in 2.0 it now uses `esbuild` which results in 10-100x faster dependency pre-bundling. As a reference, cold-booting a test app with heavy dependencies like React Material UI previously took 28 seconds on an M1-powered MacBook Pro and now takes ~1.5 seconds. Expect similar improvements if you are switching from a traditional bundler based setup.

### First-class CSS Support

Expand Down
28 changes: 18 additions & 10 deletions docs/config/index.md
Expand Up @@ -156,6 +156,8 @@ export default defineConfig(({ command, mode }) => {

- Starting from `2.0.0-beta.70`, string values will be used as raw expressions, so if defining a string constant, it needs to be explicitly quoted (e.g. with `JSON.stringify`).

- To be consistent with [esbuild behavior](https://esbuild.github.io/api/#define), expressions must either be a JSON object (null, boolean, number, string, array, or object) or a single identifier.

- Replacements are performed only when the match is surrounded by word boundaries (`\b`).

::: warning
Expand Down Expand Up @@ -327,6 +329,14 @@ export default defineConfig(({ command, mode }) => {
})
```

### css.devSourcemap

- **Experimental**
- **Type:** `boolean`
- **Default:** `false`

Whether to enable sourcemaps during dev.

### json.namedExports

- **Type:** `boolean`
Expand All @@ -347,7 +357,7 @@ export default defineConfig(({ command, mode }) => {

- **Type:** `ESBuildOptions | false`

`ESBuildOptions` extends [ESbuild's own transform options](https://esbuild.github.io/api/#transform-api). The most common use case is customizing JSX:
`ESBuildOptions` extends [esbuild's own transform options](https://esbuild.github.io/api/#transform-api). The most common use case is customizing JSX:

```js
export default defineConfig({
Expand All @@ -358,9 +368,9 @@ export default defineConfig(({ command, mode }) => {
})
```

By default, ESBuild is applied to `ts`, `jsx` and `tsx` files. You can customize this with `esbuild.include` and `esbuild.exclude`, which can be a regex, a [picomatch](https://github.com/micromatch/picomatch#globbing-features) pattern, or an array of either.
By default, esbuild is applied to `ts`, `jsx` and `tsx` files. You can customize this with `esbuild.include` and `esbuild.exclude`, which can be a regex, a [picomatch](https://github.com/micromatch/picomatch#globbing-features) pattern, or an array of either.

In addition, you can also use `esbuild.jsxInject` to automatically inject JSX helper imports for every file transformed by ESBuild:
In addition, you can also use `esbuild.jsxInject` to automatically inject JSX helper imports for every file transformed by esbuild:

```js
export default defineConfig({
Expand All @@ -370,7 +380,7 @@ export default defineConfig(({ command, mode }) => {
})
```

Set to `false` to disable ESbuild transforms.
Set to `false` to disable esbuild transforms.

### assetsInclude

Expand Down Expand Up @@ -542,14 +552,12 @@ export default defineConfig(({ command, mode }) => {

### server.hmr

- **Type:** `boolean | { protocol?: string, host?: string, port?: number | false, path?: string, timeout?: number, overlay?: boolean, clientPort?: number, server?: Server }`
- **Type:** `boolean | { protocol?: string, host?: string, port?: number, path?: string, timeout?: number, overlay?: boolean, clientPort?: number, server?: Server }`

Disable or configure HMR connection (in cases where the HMR websocket must use a different address from the http server).

Set `server.hmr.overlay` to `false` to disable the server error overlay.

Set `server.hmr.port` to `false` when connecting to a domain without a port.

`clientPort` is an advanced option that overrides the port only on the client side, allowing you to serve the websocket on a different port than the client code looks for it on. Useful if you're using an SSL proxy in front of your dev server.

If specifying `server.hmr.server`, Vite will process HMR connection requests through the provided server. If not in middleware mode, Vite will attempt to process HMR connection requests through the existing server. This can be helpful when using self-signed certificates or when you want to expose Vite over a network on a single port.
Expand Down Expand Up @@ -841,7 +849,7 @@ export default defineConfig({
- **Type:** `boolean | 'terser' | 'esbuild'`
- **Default:** `'esbuild'`

Set to `false` to disable minification, or specify the minifier to use. The default is [Esbuild](https://github.com/evanw/esbuild) which is 20 ~ 40x faster than terser and only 1 ~ 2% worse compression. [Benchmarks](https://github.com/privatenumber/minification-benchmarks)
Set to `false` to disable minification, or specify the minifier to use. The default is [esbuild](https://github.com/evanw/esbuild) which is 20 ~ 40x faster than terser and only 1 ~ 2% worse compression. [Benchmarks](https://github.com/privatenumber/minification-benchmarks)

Note the `build.minify` option is not available when using the `'es'` format in lib mode.

Expand Down Expand Up @@ -965,9 +973,9 @@ export default defineConfig({

- **Type:** `string | string[]`

By default, Vite will crawl your `index.html` to detect dependencies that need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite will crawl those entry points instead.
By default, Vite will crawl all your `.html` files to detect dependencies that need to be pre-bundled (ignoring `node_modules`, `build.outDir`, `__tests__` and `coverage`). If `build.rollupOptions.input` is specified, Vite will crawl those entry points instead.

If neither of these fit your needs, you can specify custom entries using this option - the value should be a [fast-glob pattern](https://github.com/mrmlnc/fast-glob#basic-syntax) or array of patterns that are relative from Vite project root. This will overwrite default entries inference.
If neither of these fit your needs, you can specify custom entries using this option - the value should be a [fast-glob pattern](https://github.com/mrmlnc/fast-glob#basic-syntax) or array of patterns that are relative from Vite project root. This will overwrite default entries inference. Only `node_modules` and `build.outDir` folders will be ignored by default when `optimizeDeps.entries` is explicitily defined. If other folders needs to be ignored, you can use an ignore pattern as part of the entries list, marked with an initial `!`.

### optimizeDeps.exclude

Expand Down
8 changes: 8 additions & 0 deletions docs/guide/api-hmr.md
Expand Up @@ -123,3 +123,11 @@ The following HMR events are dispatched by Vite automatically:
- `'vite:error'` when an error occurs (e.g. syntax error)
Custom HMR events can also be sent from plugins. See [handleHotUpdate](./api-plugin#handlehotupdate) for more details.
## `hot.send(event, data)`
Send custom events back to Vite's dev server.
If called before connected, the data will be buffered and sent once the connection is established.
See [Client-server Communication](/guide/api-plugin.html#client-server-communication) for more details.
2 changes: 1 addition & 1 deletion docs/guide/api-javascript.md
@@ -1,6 +1,6 @@
# JavaScript API

Vite's JavaScript APIs are fully typed, and it's recommended to use TypeScript or enable JS type checking in VSCode to leverage the intellisense and validation.
Vite's JavaScript APIs are fully typed, and it's recommended to use TypeScript or enable JS type checking in VS Code to leverage the intellisense and validation.

## `createServer`

Expand Down
96 changes: 91 additions & 5 deletions docs/guide/api-plugin.md
Expand Up @@ -113,7 +113,7 @@ Virtual modules are a useful scheme that allows you to pass build time informati

```js
export default function myPlugin() {
const virtualModuleId = '@my-virtual-module'
const virtualModuleId = 'virtual:my-module'
const resolvedVirtualModuleId = '\0' + virtualModuleId

return {
Expand All @@ -135,7 +135,7 @@ export default function myPlugin() {
Which allows importing the module in JavaScript:

```js
import { msg } from '@my-virtual-module'
import { msg } from 'virtual:my-module'

console.log(msg)
```
Expand Down Expand Up @@ -186,8 +186,10 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo
const partialConfigPlugin = () => ({
name: 'return-partial',
config: () => ({
alias: {
foo: 'bar'
resolve: {
alias: {
foo: 'bar'
}
}
})
})
Expand Down Expand Up @@ -480,7 +482,7 @@ export default defineConfig({
Check out [Vite Rollup Plugins](https://vite-rollup-plugins.patak.dev) for a list of compatible official Rollup plugins with usage instructions.
## Path normalization
## Path Normalization
Vite normalizes paths while resolving ids to use POSIX separators ( / ) while preserving the volume in Windows. On the other hand, Rollup keeps resolved paths untouched by default, so resolved ids have win32 separators ( \\ ) in Windows. However, Rollup plugins use a [`normalizePath` utility function](https://github.com/rollup/plugins/tree/master/packages/pluginutils#normalizepath) from `@rollup/pluginutils` internally, which converts separators to POSIX before performing comparisons. This means that when these plugins are used in Vite, the `include` and `exclude` config pattern and other similar paths against resolved ids comparisons work correctly.
Expand All @@ -492,3 +494,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 broadcast 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
}
}
```
13 changes: 11 additions & 2 deletions docs/guide/assets.md
Expand Up @@ -103,8 +103,17 @@ function getImageUrl(name) {
}
```
During the production build, Vite will perform necessary transforms so that the URLs still point to the correct location even after bundling and asset hashing.
During the production build, Vite will perform necessary transforms so that the URLs still point to the correct location even after bundling and asset hashing. However, the URL string must be static so it can be analyzed, otherwise the code will be left as is, which can cause runtime errors if `build.target` does not support `import.meta.url`
::: warning Note: Does not work with SSR
```js
// Vite will not transform this
const imgUrl = new URL(imagePath, import.meta.url).href
```
::: warning Does not work with SSR
This pattern does not work if you are using Vite for Server-Side Rendering, because `import.meta.url` have different semantics in browsers vs. Node.js. The server bundle also cannot determine the client host URL ahead of time.
:::
::: warning Esbuild target config is necessary
This pattern needs esbuild target to be set to `es2020` or higher. `vite@2.x` use `es2019` as default target. Set [build-target](https://vitejs.dev/config/#build-target) and [optimizedeps.esbuildoptions.target](https://vitejs.dev/config/#optimizedeps-esbuildoptions) to `es2020` or higher if you intend to use this partten.
:::
4 changes: 2 additions & 2 deletions docs/guide/env-and-mode.md
Expand Up @@ -37,7 +37,7 @@ Vite uses [dotenv](https://github.com/motdotla/dotenv) to load additional enviro

An env file for a specific mode (e.g. `.env.production`) will take higher priority than a generic one (e.g. `.env`).

In addition, environment variables that already exist when Vite is executed have the highest priority and will not be overwritten by `.env` files.
In addition, environment variables that already exist when Vite is executed have the highest priority and will not be overwritten by `.env` files. For example, when running `VITE_SOME_KEY=123 vite build`.

`.env` files are loaded at the start of Vite. Restart the server after making changes.
:::
Expand All @@ -57,7 +57,7 @@ If you want to customize env variables prefix, see [envPrefix](/config/index#env

:::warning SECURITY NOTES

- `.env.*.local` files are local-only and can contain sensitive variables. You should add `.local` to your `.gitignore` to avoid them being checked into git.
- `.env.*.local` files are local-only and can contain sensitive variables. You should add `*.local` to your `.gitignore` to avoid them being checked into git.

- Since any variables exposed to your Vite source code will end up in your client bundle, `VITE_*` variables should _not_ contain any sensitive information.
:::
Expand Down
20 changes: 20 additions & 0 deletions docs/guide/features.md
Expand Up @@ -352,6 +352,24 @@ In the production build, `.wasm` files smaller than `assetInlineLimit` will be i

## Web Workers

### Import with Constructors

A web worker script can be imported using [`new Worker()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker) and [`new SharedWorker()`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker/SharedWorker). Compared to the worker suffixes, this syntax leans closer to the standards and is the **recommended** way to create workers.

```ts
const worker = new Worker(new URL('./worker.js', import.meta.url))
```

The worker constructor also accepts options, which can be used to create "module" workers:

```ts
const worker = new Worker(new URL('./worker.js', import.meta.url), {
type: 'module'
})
```

### Import with Query Suffixes

A web worker script can be directly imported by appending `?worker` or `?sharedworker` to the import request. The default export will be a custom worker constructor:

```js
Expand All @@ -368,6 +386,8 @@ By default, the worker script will be emitted as a separate chunk in the product
import MyWorker from './worker?worker&inline'
```

See [Worker Options](/config/#worker-options) for details on configuring the bundling of all workers.

## Build Optimizations

> Features listed below are automatically applied as part of the build process and there is no need for explicit configuration unless you want to disable them.
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/static-deploy.md
Expand Up @@ -299,7 +299,7 @@ Vercel CLI

### Vercel for Git

1. Push your code to your git repository (GitHub, GitLab, BitBucket).
1. Push your code to your git repository (GitHub, GitLab, Bitbucket).
2. [Import your Vite project](https://vercel.com/new) into Vercel.
3. Vercel will detect that you are using Vite and will enable the correct settings for your deployment.
4. Your application is deployed! (e.g. [vite-vue-template.vercel.app](https://vite-vue-template.vercel.app/))
Expand Down

0 comments on commit 995897f

Please sign in to comment.