diff --git a/.github/renovate.json5 b/.github/renovate.json5
index 763dfcfc467d9d..06fe0e7ea2aaff 100644
--- a/.github/renovate.json5
+++ b/.github/renovate.json5
@@ -28,6 +28,7 @@
"react-router", // `react-router:v6.0.0+` has breaking changes
"react-router-dom", // `react-router-dom:v6.0.0+` has breaking changes
"source-map", // `source-map:v0.7.0+` needs more investigation
+ "dotenv-expand", // `dotenv-expand:6.0.0+` has breaking changes (#6858)
// ESM Only => https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c#how-can-i-move-my-commonjs-project-to-esm
"node-fetch",
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3954ca49c11479..dfccbea368c449 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -36,7 +36,7 @@ jobs:
name: "Build&Test: node-${{ matrix.node_version }}, ${{ matrix.os }}"
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
- name: Install pnpm
uses: pnpm/action-setup@v2
@@ -44,7 +44,7 @@ jobs:
version: 6
- name: Set node version to ${{ matrix.node_version }}
- uses: actions/setup-node@v2
+ uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node_version }}
cache: "pnpm"
@@ -72,7 +72,7 @@ jobs:
runs-on: ubuntu-latest
name: "Lint: node-16, ubuntu-latest"
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
with:
fetch-depth: 0
@@ -82,7 +82,7 @@ jobs:
version: 6
- name: Set node version to 16
- uses: actions/setup-node@v2
+ uses: actions/setup-node@v3
with:
node-version: 16
cache: "pnpm"
diff --git a/.github/workflows/issue-close-require.yml b/.github/workflows/issue-close-require.yml
index 02ac374b06c426..97f9dd3a449c3c 100644
--- a/.github/workflows/issue-close-require.yml
+++ b/.github/workflows/issue-close-require.yml
@@ -9,7 +9,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: need reproduction
- uses: actions-cool/issues-helper@v2
+ uses: actions-cool/issues-helper@v3
with:
actions: "close-issues"
token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.github/workflows/issue-labeled.yml b/.github/workflows/issue-labeled.yml
index a63021952fd73d..b6f3919dfa63a2 100644
--- a/.github/workflows/issue-labeled.yml
+++ b/.github/workflows/issue-labeled.yml
@@ -10,7 +10,7 @@ jobs:
steps:
- name: contribution welcome
if: github.event.label.name == 'contribution welcome' || github.event.label.name == 'help wanted'
- uses: actions-cool/issues-helper@v2
+ uses: actions-cool/issues-helper@v3
with:
actions: "create-comment, remove-labels"
token: ${{ secrets.GITHUB_TOKEN }}
@@ -21,7 +21,7 @@ jobs:
- name: remove pending
if: github.event.label.name == 'enhancement' || github.event.label.name == 'bug' || (contains(github.event.label.name, 'pending triage') == false && startsWith(github.event.label.name, 'bug:') == true)
- uses: actions-cool/issues-helper@v2
+ uses: actions-cool/issues-helper@v3
with:
actions: "remove-labels"
token: ${{ secrets.GITHUB_TOKEN }}
@@ -30,7 +30,7 @@ jobs:
- name: need reproduction
if: github.event.label.name == 'need reproduction'
- uses: actions-cool/issues-helper@v2
+ uses: actions-cool/issues-helper@v3
with:
actions: "create-comment, remove-labels"
token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.github/workflows/lock-closed-issues.yml b/.github/workflows/lock-closed-issues.yml
index e20c3e3c8e8138..1f24f316952ea0 100644
--- a/.github/workflows/lock-closed-issues.yml
+++ b/.github/workflows/lock-closed-issues.yml
@@ -11,11 +11,11 @@ jobs:
action:
runs-on: ubuntu-latest
steps:
- - uses: dessant/lock-threads@v2
+ - uses: dessant/lock-threads@v3
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
- issue-lock-inactive-days: "14"
- #issue-lock-comment: |
+ issue-inactive-days: "14"
+ #issue-comment: |
# This issue has been locked since it has been closed for more than 14 days.
#
# If you have found a concrete bug or regression related to it, please open a new [bug report](https://github.com/vitejs/vite/issues/new/choose) with a reproduction against the latest Vite version. If you have any other comments you should join the chat at [Vite Land](https://chat.vitejs.dev) or create a new [discussion](https://github.com/vitejs/vite/discussions).
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index eb8f4513707872..c58c28adac7b40 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -15,7 +15,7 @@ jobs:
environment: Release
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
- name: Install pnpm
uses: pnpm/action-setup@v2
@@ -23,7 +23,7 @@ jobs:
version: 6
- name: Set node version to 16.x
- uses: actions/setup-node@v2
+ uses: actions/setup-node@v3
with:
node-version: 16.x
registry-url: https://registry.npmjs.org/
diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml
index f9d5b8de30bec9..21af4792d4741a 100644
--- a/.github/workflows/release-tag.yml
+++ b/.github/workflows/release-tag.yml
@@ -13,7 +13,7 @@ jobs:
release:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Get pkgName for tag
id: tag
diff --git a/.npmrc b/.npmrc
new file mode 100644
index 00000000000000..4abbb42e5ef159
--- /dev/null
+++ b/.npmrc
@@ -0,0 +1,7 @@
+hoist-pattern[]=*eslint*
+hoist-pattern[]=*babel*
+hoist-pattern[]=*jest*
+hoist-pattern[]=@emotion/*
+hoist-pattern[]=postcss
+hoist-pattern[]=pug
+hoist-pattern[]=source-map-support
diff --git a/.prettierignore b/.prettierignore
index 1692b9d26cfa20..c624a3a21eecfe 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -10,3 +10,4 @@ pnpm-lock.yaml
pnpm-workspace.yaml
packages/playground/tsconfig-json-load-error/has-error/tsconfig.json
packages/playground/html/invalid.html
+packages/playground/worker/classic-worker.js
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5b8f1fed7192c3..fdae54c968c964 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -10,10 +10,42 @@ To develop and test the core `vite` package:
1. Run `pnpm i` in Vite's root folder
-2. Go to `packages/vite` and run `pnpm run dev`. This starts `rollup` in watch mode.
+2. Run `pnpm run build` in Vite's root folder.
+
+3. If you are developing Vite itself, you can go to `packages/vite` and run `pnpm run dev` to automatically rebuild Vite whenever you change its code.
You can alternatively use [Vite.js Docker Dev](https://github.com/nystudio107/vitejs-docker-dev) for a containerized Docker setup for Vite.js development.
+## Debugging
+
+If you want to use break point and explore code execution you can use the ["Run and debug"](https://code.visualstudio.com/docs/editor/debugging) feature from vscode.
+
+1. Add a `debugger` statement where you want to stop the code execution.
+
+2. Click on the "Run and Debug" icon in the activity bar of the editor.
+
+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`.
+
+5. The execution will stop and you'll use the [Debug toolbar](https://code.visualstudio.com/docs/editor/debugging#_debug-actions) to continue, step over, restart the process...
+
+### Debugging errors in Jest tests using Playwright (Chromium)
+
+Some errors are masked and hidden away because of the layers of abstraction and sandboxed nature added by Jest, Playwright, and Chromium. In order to see what's actually going wrong and the contents of the devtools console in those instances, follow this setup:
+
+1. Add a `debugger` statement to the `scripts/jestPerTestSetup.ts` -> `afterAll` hook. This will pause execution before the tests quit and the Playwright browser instance exits.
+
+1. Run the tests with the `debug-serve` script command which will enable remote debugging: `pnpm run debug-serve -- --runInBand resolve`.
+
+1. Wait for inspector devtools to open in your browser and the debugger to attach.
+
+1. In the sources panel in the right column, click the play button to resume execution and allow the tests to run which will open a Chromium instance.
+
+1. Focusing the Chomium instance, you can open the browser devtools and inspect the console there to find the underlying problems.
+
+1. To close everything, just stop the test process back in your terminal.
+
## Testing Vite against external packages
You may wish to test your locally-modified copy of Vite against another package that is built with Vite. For pnpm, after building Vite, you can use [`pnpm.overrides`](https://pnpm.io/package_json#pnpmoverrides). Please note that `pnpm.overrides` must be specified in the root `package.json` and you must first list the package as a dependency in the root `package.json`:
@@ -37,7 +69,7 @@ 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.
+Each test can be run under either dev server mode or build mode. Make sure that [Vite has been built](#repo-setup).
- `pnpm test` by default runs every test in both serve and build mode.
diff --git a/docs/config/index.md b/docs/config/index.md
index ba84c49b2f5820..905ffae7a89cea 100644
--- a/docs/config/index.md
+++ b/docs/config/index.md
@@ -27,7 +27,8 @@ You can also explicitly specify a config file to use with the `--config` CLI opt
vite --config my-config.js
```
-Note that Vite will replace `__filename`, `__dirname`, and `import.meta.url`. Using these as variable names will result in an error:
+::: tip NOTE
+Vite will replace `__filename`, `__dirname`, and `import.meta.url` in **CommonJS** and **TypeScript** config files. Using these as variable names will result in an error:
```js
const __filename = "value"
@@ -35,6 +36,8 @@ const __filename = "value"
const "path/vite.config.js" = "value"
```
+:::
+
### Config Intellisense
Since Vite ships with TypeScript typings, you can leverage your IDE's intellisense with jsdoc type hints:
@@ -96,6 +99,22 @@ export default defineConfig(async ({ command, mode }) => {
})
```
+### Environment Variables
+
+Vite doesn't load `.env` files by default as the files to load can only be determined after evaluating the Vite config, for example, the `root` and `envDir` options affects the loading behaviour. However, you can use the exported `loadEnv` helper to load the specific `.env` file if needed.
+
+```js
+import { defineConfig, loadEnv } from 'vite'
+
+export default defineConfig(({ command, mode }) => {
+ // Load env file based on `mode` in the current working directory
+ const env = loadEnv(mode, process.cwd())
+ return {
+ // build specific config
+ }
+})
+```
+
## Shared Options
### root
@@ -139,9 +158,11 @@ export default defineConfig(async ({ command, mode }) => {
- Replacements are performed only when the match is surrounded by word boundaries (`\b`).
+ ::: warning
Because it's implemented as straightforward text replacements without any syntax analysis, we recommend using `define` for CONSTANTS only.
For example, `process.env.FOO` and `__APP_VERSION__` are good fits. But `process` or `global` should not be put into this option. Variables can be shimmed or polyfilled instead.
+ :::
::: tip NOTE
For TypeScript users, make sure to add the type declarations in the `env.d.ts` or `vite-env.d.ts` file to get type checks and Intellisense.
@@ -223,6 +244,10 @@ export default defineConfig(async ({ command, mode }) => {
Vite has a list of "allowed conditions" and will match the first condition that is in the allowed list. The default allowed conditions are: `import`, `module`, `browser`, `default`, and `production/development` based on current mode. The `resolve.conditions` config option allows specifying additional allowed conditions.
+ :::warning Resolving subpath exports
+ Export keys ending with "/" is deprecated by Node and may not work well. Please contact the package author to use [`*` subpath patterns](https://nodejs.org/api/packages.html#package-entry-points) instead.
+ :::
+
### resolve.mainFields
- **Type:** `string[]`
@@ -277,7 +302,7 @@ export default defineConfig(async ({ command, mode }) => {
- **Type:** `string | (postcss.ProcessOptions & { plugins?: postcss.Plugin[] })`
- Inline PostCSS config (expects the same format as `postcss.config.js`), or a custom path to search PostCSS config from (default is project root). The search is done using [postcss-load-config](https://github.com/postcss/postcss-load-config).
+ Inline PostCSS config (expects the same format as `postcss.config.js`), or a custom directory to search PostCSS config from (default is project root). The search is done using [postcss-load-config](https://github.com/postcss/postcss-load-config) and only the supported config file names are loaded.
Note if an inline config is provided, Vite will not search for other PostCSS config sources.
@@ -285,7 +310,7 @@ export default defineConfig(async ({ command, mode }) => {
- **Type:** `Record`
- Specify options to pass to CSS pre-processors. Example:
+ Specify options to pass to CSS pre-processors. The file extensions are used as keys for the options. Example:
```js
export default defineConfig({
@@ -293,6 +318,9 @@ export default defineConfig(async ({ command, mode }) => {
preprocessorOptions: {
scss: {
additionalData: `$injectedColor: orange;`
+ },
+ styl: {
+ additionalData: `$injectedColor ?= orange`
}
}
}
@@ -330,7 +358,7 @@ export default defineConfig(async ({ command, mode }) => {
})
```
- By default, ESBuild is applied to `ts`, `jsx` and `tsx` files. You can customize this with `esbuild.include` and `esbuild.exclude`, both of which expect type of `string | RegExp | (string | RegExp)[]`.
+ 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:
@@ -349,7 +377,7 @@ export default defineConfig(async ({ command, mode }) => {
- **Type:** `string | RegExp | (string | RegExp)[]`
- **Related:** [Static Asset Handling](/guide/assets)
- Specify additional [picomatch patterns](https://github.com/micromatch/picomatch) to be treated as static assets so that:
+ Specify additional [picomatch patterns](https://github.com/micromatch/picomatch#globbing-features) to be treated as static assets so that:
- They will be excluded from the plugin transform pipeline when referenced from HTML or directly requested over `fetch` or XHR.
@@ -499,6 +527,12 @@ export default defineConfig(async ({ command, mode }) => {
Configure CORS for the dev server. This is enabled by default and allows any origin. Pass an [options object](https://github.com/expressjs/cors) to fine tune the behavior or `false` to disable.
+### server.headers
+
+- **Type:** `OutgoingHttpHeaders`
+
+ Specify server response headers.
+
### server.force
- **Type:** `boolean`
@@ -508,15 +542,17 @@ export default defineConfig(async ({ command, mode }) => {
### server.hmr
-- **Type:** `boolean | { protocol?: string, host?: string, port?: number, path?: string, timeout?: number, overlay?: boolean, clientPort?: number, server?: Server }`
+- **Type:** `boolean | { protocol?: string, host?: string, port?: number | false, 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.
- When using `server.middlewareMode` or `server.https`, assigning `server.hmr.server` to your HTTP(S) server will process HMR connection requests through your server. This can be helpful when using self-signed certificates or when you want to expose Vite over a network on a single port.
+ 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.
### server.watch
@@ -580,6 +616,12 @@ async function createServer() {
createServer()
```
+### server.base
+
+- **Type:** `string | undefined`
+
+ Prepend this folder to http requests, for use when proxying vite as a subfolder. Should start and end with the `/` character.
+
### server.fs.strict
- **Type:** `boolean`
@@ -923,7 +965,7 @@ 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 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.
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.
diff --git a/docs/guide/api-javascript.md b/docs/guide/api-javascript.md
index 1651923c06cdcb..ddaa04279737f5 100644
--- a/docs/guide/api-javascript.md
+++ b/docs/guide/api-javascript.md
@@ -94,7 +94,7 @@ interface ViteDevServer {
*/
ssrLoadModule(
url: string,
- options?: { isolated?: boolean }
+ options?: { fixStacktrace?: boolean }
): Promise>
/**
* Fix ssr error stacktrace.
diff --git a/docs/guide/api-plugin.md b/docs/guide/api-plugin.md
index 01b42980197473..b3888b0fd7009b 100644
--- a/docs/guide/api-plugin.md
+++ b/docs/guide/api-plugin.md
@@ -458,7 +458,7 @@ In general, as long as a Rollup plugin fits the following criteria then it shoul
- It doesn't use the [`moduleParsed`](https://rollupjs.org/guide/en/#moduleparsed) hook.
- It doesn't have strong coupling between bundle-phase hooks and output-phase hooks.
-If a Rollup plugin only makes sense for the build phase, then it can be specified under `build.rollupOptions.plugins` instead.
+If a Rollup plugin only makes sense for the build phase, then it can be specified under `build.rollupOptions.plugins` instead. It will work the same as a Vite plugin with `enforce: 'post'` and `apply: 'build'`.
You can also augment an existing Rollup plugin with Vite-only properties:
diff --git a/docs/guide/backend-integration.md b/docs/guide/backend-integration.md
index a30831e735fff7..55a4b87f1ac481 100644
--- a/docs/guide/backend-integration.md
+++ b/docs/guide/backend-integration.md
@@ -33,7 +33,6 @@ If you need a custom integration, you can follow the steps in this guide to conf
```html
-
```
diff --git a/docs/guide/build.md b/docs/guide/build.md
index aac86a237b6819..8216bcbfbac060 100644
--- a/docs/guide/build.md
+++ b/docs/guide/build.md
@@ -43,6 +43,20 @@ module.exports = defineConfig({
For example, you can specify multiple Rollup outputs with plugins that are only applied during build.
+## Chunking Strategy
+
+You can configure how chunks are split using `build.rollupOptions.output.manualChunks` (see [Rollup docs](https://rollupjs.org/guide/en/#outputmanualchunks)). Until Vite 2.8, the default chunking strategy divided the chunks into `index` and `vendor`. It is a good strategy for some SPAs, but it is hard to provide a general solution for every Vite target use case. From Vite 2.9, `manualChunks` is no longer modified by default. You can continue to use the Split Vendor Chunk strategy by adding the `splitVendorChunkPlugin` in your config file:
+
+```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 changes
You can enable rollup watcher with `vite build --watch`. Or, you can directly adjust the underlying [`WatcherOptions`](https://rollupjs.org/guide/en/#watch-options) via `build.watch`:
@@ -58,6 +72,8 @@ module.exports = defineConfig({
})
```
+With the `--watch` flag enabled, changes to the `vite.config.js`, as well as any files to be bundled, will trigger a rebuild.
+
## Multi-Page App
Suppose you have the following source code structure:
@@ -129,6 +145,15 @@ module.exports = defineConfig({
})
```
+The entry file would contain exports that can be imported by users of your package:
+
+```js
+// lib/main.js
+import Foo from './Foo.vue'
+import Bar from './Bar.vue'
+export { Foo, Bar }
+```
+
Running `vite build` with this config uses a Rollup preset that is oriented towards shipping libraries and produces two bundle formats: `es` and `umd` (configurable via `build.lib`):
```
diff --git a/docs/guide/dep-pre-bundling.md b/docs/guide/dep-pre-bundling.md
index 6864ef55899eba..0afce072e9fcc3 100644
--- a/docs/guide/dep-pre-bundling.md
+++ b/docs/guide/dep-pre-bundling.md
@@ -3,10 +3,10 @@
When you run `vite` for the first time, you may notice this message:
```
-Optimizable dependencies detected:
-react, react-dom
-Pre-bundling them to speed up dev server page load...
-(this will be run only when your dependencies have changed)
+Pre-bundling dependencies:
+ react
+ react-dom
+(this will be run only when your dependencies or config have changed)
```
## The Why
@@ -28,6 +28,10 @@ This is Vite performing what we call "dependency pre-bundling". This process ser
By pre-bundling `lodash-es` into a single module, we now only need one HTTP request instead!
+::: tip NOTE
+Dependency pre-bundling only applies in development mode, and uses `esbuild` to convert dependencies to ESM. In production builds, `@rollup/plugin-commonjs` is used instead.
+:::
+
## Automatic Dependency Discovery
If an existing cache is not found, Vite will crawl your source code and automatically discover dependency imports (i.e. "bare imports" that expect to be resolved from `node_modules`) and use these found imports as entry points for the pre-bundle. The pre-bundling is performed with `esbuild` so it's typically very fast.
@@ -36,11 +40,27 @@ After the server has already started, if a new dependency import is encountered
## Monorepos and Linked Dependencies
-In a monorepo setup, a dependency may be a linked package from the same repo. Vite automatically detects dependencies that are not resolved from `node_modules` and treats the linked dep as source code. It will not attempt to bundle the linked dep, and instead will analyze the linked dep's dependency list instead.
+In a monorepo setup, a dependency may be a linked package from the same repo. Vite automatically detects dependencies that are not resolved from `node_modules` and treats the linked dep as source code. It will not attempt to bundle the linked dep, and will analyze the linked dep's dependency list instead.
+
+However, this requires the linked dep to be exported as ESM. If not, you can add the dependency to [`optimizeDeps.include`](/config/#optimizedeps-include) and [`build.commonjsOptions.include`](/config/#build-commonjsoptions) in your config.
+
+```js
+export default defineConfig({
+ optimizeDeps: {
+ include: ['linked-dep']
+ },
+ build: {
+ commonjsOptions: {
+ include: [/linked-dep/, /node_modules/]
+ }
+ }
+})
+```
+
+When making changes to the linked dep, restart the dev server with the `--force` command line option for the changes to take effect.
-::: warning Note
-Linked dependencies might not work properly in the final build due to differences in dependency resolution.
-Use `npm package` instead for all local dependencies to avoid issues in the final bundle.
+::: warning Deduping
+Due to differences in linked dependency resolution, transitive dependencies can deduplicated incorrectly, causing issues when used in runtime. If you stumble on this issue, use `npm pack` on the linked dependency to fix it.
:::
## Customizing the Behavior
@@ -57,7 +77,7 @@ Both `include` and `exclude` can be used to deal with this. If the dependency is
Vite caches the pre-bundled dependencies in `node_modules/.vite`. It determines whether it needs to re-run the pre-bundling step based on a few sources:
-- The `dependencies` list in your `package.json`
+- The `dependencies` list in your `package.json`.
- Package manager lockfiles, e.g. `package-lock.json`, `yarn.lock`, or `pnpm-lock.yaml`.
- Relevant fields in your `vite.config.js`, if present.
diff --git a/docs/guide/features.md b/docs/guide/features.md
index da8e3b1de092b2..ebed85cd2d529d 100644
--- a/docs/guide/features.md
+++ b/docs/guide/features.md
@@ -298,10 +298,26 @@ const modules = {
}
```
+`import.meta.glob` and `import.meta.globEager` also support importing files as strings (similar to [Importing Asset as String](https://vitejs.dev/guide/assets.html#importing-asset-as-string)) with the [Import Reflection](https://github.com/tc39/proposal-import-reflection) syntax:
+
+```js
+const modules = import.meta.glob('./dir/*.js', { as: 'raw' })
+```
+
+The above will be transformed into the following:
+
+```js
+// code produced by vite
+const modules = {
+ './dir/foo.js': '{\n "msg": "foo"\n}\n',
+ './dir/bar.js': '{\n "msg": "bar"\n}\n'
+}
+```
+
Note that:
- This is a Vite-only feature and is not a web or ES standard.
-- The glob patterns are treated like import specifiers: they must be either relative (start with `./`) or absolute (start with `/`, resolved relative to project root).
+- The glob patterns are treated like import specifiers: they must be either relative (start with `./`) or absolute (start with `/`, resolved relative to project root) or an alias path (see [`resolve.alias` option](/config/#resolve-alias)).
- The glob matching is done via `fast-glob` - check out its documentation for [supported glob patterns](https://github.com/mrmlnc/fast-glob#pattern-syntax).
- You should also be aware that glob imports do not accept variables, you need to directly pass the string pattern.
- The glob patterns cannot contain the same quote string (i.e. `'`, `"`, `` ` ``) as outer quotes, e.g. `'/Tom\'s files/**'`, use `"/Tom's files/**"` instead.
@@ -336,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
@@ -352,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.
diff --git a/docs/guide/why.md b/docs/guide/why.md
index 59e9c138eb7dca..89ca7698394246 100644
--- a/docs/guide/why.md
+++ b/docs/guide/why.md
@@ -32,7 +32,7 @@ Vite improves the dev server start time by first dividing the modules in an appl
When a file is edited in a bundler-based build setup, it is inefficient to rebuild the whole bundle for obvious reasons: the update speed will degrade linearly with the size of the app.
-Some bundler dev server runs the bundling in memory so that it only needs to invalidate part of its module graph when a file changes, but it still needs to re-construct the entire bundle and reload the web page. Reconstructing the bundle can be expensive, and reloading the page blows away the current state of the application. This is why some bundlers support Hot Module Replacement (HMR): allowing a module to "hot replace" itself without affecting the rest of the page. This greatly improves DX - however, in practice we've found that even HMR update speed deteriorates significantly as the size of the application grows.
+In some bundlers, the dev server runs the bundling in memory so that it only needs to invalidate part of its module graph when a file changes, but it still needs to re-construct the entire bundle and reload the web page. Reconstructing the bundle can be expensive, and reloading the page blows away the current state of the application. This is why some bundlers support Hot Module Replacement (HMR): allowing a module to "hot replace" itself without affecting the rest of the page. This greatly improves DX - however, in practice we've found that even HMR update speed deteriorates significantly as the size of the application grows.
In Vite, HMR is performed over native ESM. When a file is edited, Vite only needs to precisely invalidate the chain between the edited module and its closest HMR boundary (most of the time only the module itself), making HMR updates consistently fast regardless of the size of your application.
diff --git a/jest.config.ts b/jest.config.ts
index 7d4831524d01c3..11663af4e08107 100644
--- a/jest.config.ts
+++ b/jest.config.ts
@@ -6,7 +6,7 @@ const config: Config.InitialOptions = {
testMatch: process.env.VITE_TEST_BUILD
? ['**/playground/**/*.spec.[jt]s?(x)']
: ['**/*.spec.[jt]s?(x)'],
- testTimeout: process.env.CI ? 30000 : 10000,
+ testTimeout: process.env.CI ? 50000 : 20000,
globalSetup: './scripts/jestGlobalSetup.cjs',
globalTeardown: './scripts/jestGlobalTeardown.cjs',
testEnvironment: './scripts/jestEnv.cjs',
diff --git a/package.json b/package.json
index 72b7076ee65d01..858e7502d53324 100644
--- a/package.json
+++ b/package.json
@@ -34,30 +34,30 @@
"ci-docs": "run-s build-vite build-plugin-vue build-docs"
},
"devDependencies": {
- "@microsoft/api-extractor": "^7.19.4",
+ "@microsoft/api-extractor": "^7.19.5",
"@types/fs-extra": "^9.0.13",
- "@types/jest": "^27.4.0",
- "@types/node": "^16.11.22",
+ "@types/jest": "^27.4.1",
+ "@types/node": "^16.11.26",
"@types/prompts": "^2.0.14",
"@types/semver": "^7.3.9",
- "@typescript-eslint/eslint-plugin": "^5.11.0",
- "@typescript-eslint/parser": "^5.11.0",
+ "@typescript-eslint/eslint-plugin": "^5.16.0",
+ "@typescript-eslint/parser": "^5.16.0",
"conventional-changelog-cli": "^2.2.2",
"cross-env": "^7.0.3",
- "esbuild": "^0.14.14",
- "eslint": "^8.8.0",
- "eslint-define-config": "^1.2.4",
+ "esbuild": "^0.14.27",
+ "eslint": "^8.11.0",
+ "eslint-define-config": "^1.3.0",
"eslint-plugin-node": "^11.1.0",
"execa": "^5.1.1",
- "fs-extra": "^10.0.0",
+ "fs-extra": "^10.0.1",
"jest": "^27.5.1",
- "lint-staged": "^12.3.3",
+ "lint-staged": "^12.3.7",
"minimist": "^1.2.5",
"node-fetch": "^2.6.6",
"npm-run-all": "^4.1.5",
"picocolors": "^1.0.0",
- "playwright-chromium": "^1.18.1",
- "prettier": "2.5.1",
+ "playwright-chromium": "^1.20.0",
+ "prettier": "2.6.0",
"prompts": "^2.4.2",
"rimraf": "^3.0.2",
"rollup": "^2.59.0",
@@ -68,7 +68,7 @@
"ts-node": "^10.4.0",
"typescript": "~4.5.4",
"vite": "workspace:*",
- "vitepress": "^0.21.6"
+ "vitepress": "^0.22.3"
},
"simple-git-hooks": {
"pre-commit": "pnpm exec lint-staged --concurrent false",
@@ -85,7 +85,7 @@
"eslint --ext .ts"
]
},
- "packageManager": "pnpm@6.30.0",
+ "packageManager": "pnpm@6.32.3",
"pnpm": {
"overrides": {
"vite": "workspace:*",
diff --git a/packages/create-vite/template-vue-ts/README.md b/packages/create-vite/template-vue-ts/README.md
index f5342b7d8f66dd..b53dcfb1a715e6 100644
--- a/packages/create-vite/template-vue-ts/README.md
+++ b/packages/create-vite/template-vue-ts/README.md
@@ -8,4 +8,9 @@ This template should help get you started developing with Vue 3 and Typescript i
## Type Support For `.vue` Imports in TS
-Since TypeScript cannot handle type information for `.vue` imports, they are shimmed to be a generic Vue component type by default. In most cases this is fine if you don't really care about component prop types outside of templates. However, if you wish to get actual prop types in `.vue` imports (for example to get props validation when using manual `h(...)` calls), you can enable Volar's `.vue` type support plugin by running `Volar: Switch TS Plugin on/off` from VSCode command palette.
+Since TypeScript cannot handle type information for `.vue` imports, they are shimmed to be a generic Vue component type by default. In most cases this is fine if you don't really care about component prop types outside of templates. However, if you wish to get actual prop types in `.vue` imports (for example to get props validation when using manual `h(...)` calls), you can enable Volar's Take Over mode by following these steps:
+
+1. Run `Extensions: Show Built-in Extensions` from VSCode's command palette, look for `TypeScript and JavaScript Language Features`, then right click and select `Disable (Workspace)`. By default, Take Over mode will enable itself if the default TypeScript extension is disabled.
+2. Reload the VSCode window by running `Developer: Reload Window` from the command palette.
+
+You can learn more about Take Over mode [here](https://github.com/johnsoncodehk/volar/discussions/471).
diff --git a/packages/create-vite/template-vue-ts/tsconfig.json b/packages/create-vite/template-vue-ts/tsconfig.json
index af31eb8152d3cb..52205ea0029c99 100644
--- a/packages/create-vite/template-vue-ts/tsconfig.json
+++ b/packages/create-vite/template-vue-ts/tsconfig.json
@@ -8,6 +8,7 @@
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
+ "isolatedModules": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"]
},
diff --git a/packages/playground/assets/__tests__/assets.spec.ts b/packages/playground/assets/__tests__/assets.spec.ts
index 8c66588d50716d..f53c783c52b606 100644
--- a/packages/playground/assets/__tests__/assets.spec.ts
+++ b/packages/playground/assets/__tests__/assets.spec.ts
@@ -8,7 +8,8 @@ import {
readManifest,
readFile,
editFile,
- notifyRebuildComplete
+ notifyRebuildComplete,
+ untilUpdated
} from '../../testUtils'
const assetMatch = isBuild
@@ -37,7 +38,7 @@ describe('injected scripts', () => {
test('html-proxy', async () => {
const hasHtmlProxy = await page.$(
- 'script[type="module"][src="/foo/index.html?html-proxy&index=0.js"]'
+ 'script[type="module"][src^="/foo/index.html?html-proxy"]'
)
if (isBuild) {
expect(hasHtmlProxy).toBeFalsy()
@@ -120,6 +121,10 @@ describe('css url() references', () => {
const match = isBuild ? `data:image/png;base64` : `/foo/nested/icon.png`
expect(await getBg('.css-url-base64-inline')).toMatch(match)
expect(await getBg('.css-url-quotes-base64-inline')).toMatch(match)
+ const icoMatch = isBuild ? `data:image/x-icon;base64` : `favicon.ico`
+ const el = await page.$(`link.ico`)
+ const herf = await el.getAttribute('href')
+ expect(herf).toMatch(icoMatch)
})
test('multiple urls on the same line', async () => {
@@ -238,6 +243,12 @@ test('new URL(`${dynamic}`, import.meta.url)', async () => {
)
})
+test('new URL(`non-existent`, import.meta.url)', async () => {
+ expect(await page.textContent('.non-existent-import-meta-url')).toMatch(
+ '/foo/non-existent'
+ )
+})
+
if (isBuild) {
test('manifest', async () => {
const manifest = readManifest('foo')
@@ -264,3 +275,15 @@ describe('css and assets in css in build watch', () => {
})
}
})
+
+if (!isBuild) {
+ test('@import in html style tag hmr', async () => {
+ await untilUpdated(() => getColor('.import-css'), 'rgb(0, 136, 255)')
+ editFile(
+ './css/import.css',
+ (code) => code.replace('#0088ff', '#00ff88'),
+ true
+ )
+ await untilUpdated(() => getColor('.import-css'), 'rgb(0, 255, 136)')
+ })
+}
diff --git a/packages/playground/assets/favicon.ico b/packages/playground/assets/favicon.ico
new file mode 100644
index 00000000000000..d75d248ef0b150
Binary files /dev/null and b/packages/playground/assets/favicon.ico differ
diff --git a/packages/playground/assets/index.html b/packages/playground/assets/index.html
index 66753240c8a54e..7534ecbe1677bf 100644
--- a/packages/playground/assets/index.html
+++ b/packages/playground/assets/index.html
@@ -2,6 +2,7 @@
+
@@ -140,6 +141,14 @@
new URL('...', import.meta.url)
+
new URL('...', import.meta.url,) (with comma)
+
+
+
+
new URL('...', import.meta.url,) (with comma + new line)
+
+
+
new URL(`./${dynamic}`, import.meta.url)
@@ -150,6 +159,21 @@
new URL(`./${dynamic}`, import.meta.url)
+
new URL(`./${dynamic}`, import.meta.url,) (with comma)