+
+
+
+
diff --git a/docs/config/build-options.md b/docs/config/build-options.md
index b5872e363de973..c2c240249c6523 100644
--- a/docs/config/build-options.md
+++ b/docs/config/build-options.md
@@ -83,7 +83,7 @@ Specify the directory to nest generated assets under (relative to `build.outDir`
## build.assetsInlineLimit
- **Type:** `number`
-- **Default:** `4096` (4kb)
+- **Default:** `4096` (4 KiB)
Imported or referenced assets that are smaller than this threshold will be inlined as base64 URLs to avoid extra http requests. Set to `0` to disable inlining altogether.
@@ -218,7 +218,6 @@ By default, Vite will empty the `outDir` on build if it is inside project root.
## build.copyPublicDir
-- **Experimental:** [Give feedback](https://github.com/vitejs/vite/discussions/13807)
- **Type:** `boolean`
- **Default:** `true`
@@ -236,7 +235,7 @@ Enable/disable gzip-compressed size reporting. Compressing large output files ca
- **Type:** `number`
- **Default:** `500`
-Limit for chunk size warnings (in kbs). It is compared against the uncompressed chunk size as the [JavaScript size itself is related to the execution time](https://v8.dev/blog/cost-of-javascript-2019).
+Limit for chunk size warnings (in kB). It is compared against the uncompressed chunk size as the [JavaScript size itself is related to the execution time](https://v8.dev/blog/cost-of-javascript-2019).
## build.watch
diff --git a/docs/config/shared-options.md b/docs/config/shared-options.md
index fd193f0fde4966..e7708d80c517cf 100644
--- a/docs/config/shared-options.md
+++ b/docs/config/shared-options.md
@@ -326,7 +326,7 @@ Enabling this disables named imports.
- **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). The most common use case is customizing JSX:
```js
export default defineConfig({
diff --git a/docs/guide/api-javascript.md b/docs/guide/api-javascript.md
index cb1540950ec23c..a9a5a2592bc8cd 100644
--- a/docs/guide/api-javascript.md
+++ b/docs/guide/api-javascript.md
@@ -201,15 +201,7 @@ import { preview } from 'vite'
## `PreviewServer`
```ts
-interface PreviewServer extends PreviewServerForHook {
- resolvedUrls: ResolvedServerUrls
-}
-```
-
-## `PreviewServerForHook`
-
-```ts
-interface PreviewServerForHook {
+interface PreviewServer {
/**
* The resolved vite config object
*/
@@ -228,7 +220,8 @@ interface PreviewServerForHook {
*/
httpServer: http.Server
/**
- * The resolved urls Vite prints on the CLI
+ * The resolved urls Vite prints on the CLI.
+ * null before server is listening.
*/
resolvedUrls: ResolvedServerUrls | null
/**
@@ -268,6 +261,15 @@ Deeply merge two Vite configs. `isRoot` represents the level within the Vite con
::: tip NOTE
`mergeConfig` accepts only config in object form. If you have a config in callback form, you should call it before passing into `mergeConfig`.
+
+You can use the `defineConfig` helper to merge a config in callback form with another config:
+
+```ts
+export default defineConfig((configEnv) =>
+ mergeConfig(configAsCallback(configEnv), configAsObject),
+)
+```
+
:::
## `searchForWorkspaceRoot`
diff --git a/docs/guide/api-plugin.md b/docs/guide/api-plugin.md
index 4ca270afcc53fa..d2f3b6ff8e25c9 100644
--- a/docs/guide/api-plugin.md
+++ b/docs/guide/api-plugin.md
@@ -311,9 +311,9 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo
### `configurePreviewServer`
-- **Type:** `(server: PreviewServerForHook) => (() => void) | void | Promise<(() => void) | void>`
+- **Type:** `(server: PreviewServer) => (() => void) | void | Promise<(() => void) | void>`
- **Kind:** `async`, `sequential`
-- **See also:** [PreviewServerForHook](./api-javascript#previewserverforhook)
+- **See also:** [PreviewServer](./api-javascript#previewserver)
Same as [`configureServer`](/guide/api-plugin.html#configureserver) but for the preview server. Similarly to `configureServer`, the `configurePreviewServer` hook is called before other middlewares are installed. If you want to inject a middleware **after** other middlewares, you can return a function from `configurePreviewServer`, which will be called after internal middlewares are installed:
diff --git a/docs/guide/assets.md b/docs/guide/assets.md
index dff926f2c2da31..782d734e2f9ccc 100644
--- a/docs/guide/assets.md
+++ b/docs/guide/assets.md
@@ -1,3 +1,7 @@
+---
+outline: [2, 3]
+---
+
# Static Asset Handling
- Related: [Public Base Path](./build#public-base-path)
diff --git a/docs/guide/build.md b/docs/guide/build.md
index b2b210b51fcd28..e08946a8435f81 100644
--- a/docs/guide/build.md
+++ b/docs/guide/build.md
@@ -170,8 +170,8 @@ Running `vite build` with this config uses a Rollup preset that is oriented towa
```
$ vite build
building for production...
-dist/my-lib.js 0.08 KiB / gzip: 0.07 KiB
-dist/my-lib.umd.cjs 0.30 KiB / gzip: 0.16 KiB
+dist/my-lib.js 0.08 kB / gzip: 0.07 kB
+dist/my-lib.umd.cjs 0.30 kB / gzip: 0.16 kB
```
Recommended `package.json` for your lib:
diff --git a/docs/guide/cli.md b/docs/guide/cli.md
index 050610701c4d70..5beece69d9064a 100644
--- a/docs/guide/cli.md
+++ b/docs/guide/cli.md
@@ -1,3 +1,7 @@
+---
+outline: [2, 3]
+---
+
# Command Line Interface
## Dev server
@@ -14,24 +18,25 @@ vite [root]
#### Options
-| Options | |
-| ------------------------ | ----------------------------------------------------------------- |
-| `--host [host]` | Specify hostname (`string`) |
-| `--port ` | Specify port (`number`) |
-| `--https` | Use TLS + HTTP/2 (`boolean`) |
-| `--open [path]` | Open browser on startup (`boolean \| string`) |
-| `--cors` | Enable CORS (`boolean`) |
-| `--strictPort` | Exit if specified port is already in use (`boolean`) |
-| `--force` | Force the optimizer to ignore the cache and re-bundle (`boolean`) |
-| `-c, --config ` | Use specified config file (`string`) |
-| `--base ` | Public base path (default: `/`) (`string`) |
-| `-l, --logLevel ` | Info \| warn \| error \| silent (`string`) |
-| `--clearScreen` | Allow/disable clear screen when logging (`boolean`) |
-| `-d, --debug [feat]` | Show debug logs (`string \| boolean`) |
-| `-f, --filter ` | Filter debug logs (`string`) |
-| `-m, --mode ` | Set env mode (`string`) |
-| `-h, --help` | Display available CLI options |
-| `-v, --version` | Display version number |
+| Options | |
+| ------------------------ | ------------------------------------------------------------------------------------------------------------------ |
+| `--host [host]` | Specify hostname (`string`) |
+| `--port ` | Specify port (`number`) |
+| `--https` | Use TLS + HTTP/2 (`boolean`) |
+| `--open [path]` | Open browser on startup (`boolean \| string`) |
+| `--cors` | Enable CORS (`boolean`) |
+| `--strictPort` | Exit if specified port is already in use (`boolean`) |
+| `--force` | Force the optimizer to ignore the cache and re-bundle (`boolean`) |
+| `-c, --config ` | Use specified config file (`string`) |
+| `--base ` | Public base path (default: `/`) (`string`) |
+| `-l, --logLevel ` | info \| warn \| error \| silent (`string`) |
+| `--clearScreen` | Allow/disable clear screen when logging (`boolean`) |
+| `--profile` | Start built-in Node.js inspector (check [Performance bottlenecks](/guide/troubleshooting#performance-bottlenecks)) |
+| `-d, --debug [feat]` | Show debug logs (`string \| boolean`) |
+| `-f, --filter ` | Filter debug logs (`string`) |
+| `-m, --mode ` | Set env mode (`string`) |
+| `-h, --help` | Display available CLI options |
+| `-v, --version` | Display version number |
## Build
@@ -65,6 +70,7 @@ vite build [root]
| `--base ` | Public base path (default: `/`) (`string`) |
| `-l, --logLevel ` | Info \| warn \| error \| silent (`string`) |
| `--clearScreen` | Allow/disable clear screen when logging (`boolean`) |
+| `--profile` | Start built-in Node.js inspector (check [Performance bottlenecks](/guide/troubleshooting#performance-bottlenecks)) |
| `-d, --debug [feat]` | Show debug logs (`string \| boolean`) |
| `-f, --filter ` | Filter debug logs (`string`) |
| `-m, --mode ` | Set env mode (`string`) |
diff --git a/docs/guide/dep-pre-bundling.md b/docs/guide/dep-pre-bundling.md
index ddfad451322c08..1a8f0f226124b6 100644
--- a/docs/guide/dep-pre-bundling.md
+++ b/docs/guide/dep-pre-bundling.md
@@ -1,3 +1,7 @@
+---
+outline: [2, 3]
+---
+
# Dependency Pre-Bundling
When you run `vite` for the first time, Vite prebundles your project dependencies before loading your site locally. It is done automatically and transparently by default.
diff --git a/docs/guide/env-and-mode.md b/docs/guide/env-and-mode.md
index e54ba86d1c0cbd..700ecba58f216f 100644
--- a/docs/guide/env-and-mode.md
+++ b/docs/guide/env-and-mode.md
@@ -8,7 +8,7 @@ Vite exposes env variables on the special **`import.meta.env`** object. Some bui
- **`import.meta.env.BASE_URL`**: {string} the base url the app is being served from. This is determined by the [`base` config option](/config/shared-options.md#base).
-- **`import.meta.env.PROD`**: {boolean} whether the app is running in production.
+- **`import.meta.env.PROD`**: {boolean} whether the app is running in production (running the dev server with `NODE_ENV='production'` or running an app built with `NODE_ENV='production'`).
- **`import.meta.env.DEV`**: {boolean} whether the app is running in development (always the opposite of `import.meta.env.PROD`)
diff --git a/docs/guide/index.md b/docs/guide/index.md
index ebe76458c21984..c45e1711d69dbe 100644
--- a/docs/guide/index.md
+++ b/docs/guide/index.md
@@ -42,27 +42,25 @@ The supported template presets are:
## Scaffolding Your First Vite Project
::: tip Compatibility Note
-Vite requires [Node.js](https://nodejs.org/en/) version 14.18+, 16+. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it.
+Vite requires [Node.js](https://nodejs.org/en/) version 18+. 20+. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it.
:::
-With NPM:
+::: code-group
-```bash
+```bash [NPM]
$ npm create vite@latest
```
-With Yarn:
-
-```bash
+```bash [Yarn]
$ yarn create vite
```
-With PNPM:
-
-```bash
+```bash [PNPM]
$ pnpm create vite
```
+:::
+
Then follow the prompts!
You can also directly specify the project name and the template you want to use via additional command line options. For example, to scaffold a Vite + Vue project, run:
diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md
index 4108902477bbfa..e5bfd3869fb647 100644
--- a/docs/guide/troubleshooting.md
+++ b/docs/guide/troubleshooting.md
@@ -144,6 +144,30 @@ You will need to access the file with `http` protocol. The easiest way to achiev
The hash key used to invalidate optimized dependencies depend on the package lock contents, the patches applied to dependencies, and the options in the Vite config file that affects the bundling of node modules. This means that Vite will detect when a dependency is overridden using a feature as [npm overrides](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#overrides), and re-bundle your dependencies on the next server start. Vite won't invalidate the dependencies when you use a feature like [npm link](https://docs.npmjs.com/cli/v9/commands/npm-link). In case you link or unlink a dependency, you'll need to force re-optimization on the next server start by using `vite --force`. We recommend using overrides instead, which are supported now by every package manager (see also [pnpm overrides](https://pnpm.io/package_json#pnpmoverrides) and [yarn resolutions](https://yarnpkg.com/configuration/manifest/#resolutions)).
+## Performance bottlenecks
+
+If you suffer any application performance bottlenecks resulting in slow load times, you can start the built-in Node.js inspector with your Vite dev server or when building your application to create the CPU profile:
+
+::: code-group
+
+```bash [dev server]
+vite --profile --open
+```
+
+```bash [build]
+vite build --profile
+```
+
+:::
+
+::: tip Vite Dev Server
+Once your application is opened in the browser, just await finish loading it and then go back to the terminal and press `p` key (will stop the Node.js inspector) then press `q` key to stop the dev server.
+:::
+
+Node.js inspector will generate `vite-profile-0.cpuprofile` in the root folder, go to https://www.speedscope.app/, and upload the CPU profile using the `BROWSE` button to inspect the result.
+
+You can install [vite-plugin-inspect](https://github.com/antfu/vite-plugin-inspect), which lets you inspect the intermediate state of Vite plugins and can also help you to identify which plugins or middlewares are the bottleneck in your applications. The plugin can be used in both dev and build modes. Check the readme file for more details.
+
## Others
### Module externalized for browser compatibility
diff --git a/docs/guide/why.md b/docs/guide/why.md
index d58d165ca0228e..1647c7781e93e4 100644
--- a/docs/guide/why.md
+++ b/docs/guide/why.md
@@ -1,3 +1,7 @@
+---
+outline: [2, 3]
+---
+
# Why Vite
## The Problems
diff --git a/docs/index.md b/docs/index.md
index bdf716bc3d20a7..fb683307bd6f4b 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -21,6 +21,9 @@ hero:
- theme: alt
text: View on GitHub
link: https://github.com/vitejs/vite
+ - theme: brand
+ text: 🎉 ViteConf 23!
+ link: https://viteconf.org/23
features:
- icon: 💡
diff --git a/docs/public/viteconf.svg b/docs/public/viteconf.svg
index a01c0bd224407c..2ca20c23f890ff 100644
--- a/docs/public/viteconf.svg
+++ b/docs/public/viteconf.svg
@@ -1 +1,24 @@
-
\ No newline at end of file
+
diff --git a/netlify.toml b/netlify.toml
index 961d936bd686e5..d78254570def67 100644
--- a/netlify.toml
+++ b/netlify.toml
@@ -1,5 +1,5 @@
[build.environment]
- NODE_VERSION = "16"
+ NODE_VERSION = "18"
# don't need playwright for docs build
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD = "1"
[build]
diff --git a/package.json b/package.json
index 4d76a344005691..2dd3d289ce511a 100644
--- a/package.json
+++ b/package.json
@@ -3,7 +3,7 @@
"private": true,
"type": "module",
"engines": {
- "node": "^14.18.0 || >=16.0.0"
+ "node": "^18.0.0 || >=20.0.0"
},
"homepage": "https://vitejs.dev/",
"repository": {
@@ -69,12 +69,12 @@
"eslint": "^8.46.0",
"eslint-define-config": "^1.23.0",
"eslint-plugin-import": "^2.28.0",
- "eslint-plugin-n": "^15.7.0",
+ "eslint-plugin-n": "^16.0.1",
"eslint-plugin-regexp": "^1.15.0",
- "execa": "^7.2.0",
+ "execa": "^8.0.1",
"fast-glob": "^3.3.1",
"fs-extra": "^11.1.1",
- "lint-staged": "^13.2.3",
+ "lint-staged": "^14.0.1",
"npm-run-all": "^4.1.5",
"picocolors": "^1.0.0",
"playwright-chromium": "^1.36.2",
diff --git a/packages/create-vite/README.md b/packages/create-vite/README.md
index 8776ab3c3aeb3c..ea05ce4009beaf 100644
--- a/packages/create-vite/README.md
+++ b/packages/create-vite/README.md
@@ -3,7 +3,7 @@
## Scaffolding Your First Vite Project
> **Compatibility Note:**
-> Vite requires [Node.js](https://nodejs.org/en/) version 14.18+, 16+. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it.
+> Vite requires [Node.js](https://nodejs.org/en/) version 18+, 20+. However, some templates require a higher Node.js version to work, please upgrade if your package manager warns about it.
With NPM:
diff --git a/packages/create-vite/build.config.ts b/packages/create-vite/build.config.ts
index 435c39bc937a6a..71d1ba88717d6d 100644
--- a/packages/create-vite/build.config.ts
+++ b/packages/create-vite/build.config.ts
@@ -11,11 +11,12 @@ export default defineBuildConfig({
rollup: {
inlineDependencies: true,
esbuild: {
+ target: 'node18',
minify: true,
},
},
alias: {
- // we can always use non-transpiled code since we support 14.18.0+
+ // we can always use non-transpiled code since we support node 18+
prompts: 'prompts/lib/index.js',
},
hooks: {
diff --git a/packages/create-vite/package.json b/packages/create-vite/package.json
index 94134bdd378846..8ee1ddf9224f30 100644
--- a/packages/create-vite/package.json
+++ b/packages/create-vite/package.json
@@ -20,7 +20,7 @@
"prepublishOnly": "npm run build"
},
"engines": {
- "node": "^14.18.0 || >=16.0.0"
+ "node": "^18.0.0 || >=20.0.0"
},
"repository": {
"type": "git",
diff --git a/packages/create-vite/tsconfig.json b/packages/create-vite/tsconfig.json
index 65fffe74592b9b..9fc23ebe675e0f 100644
--- a/packages/create-vite/tsconfig.json
+++ b/packages/create-vite/tsconfig.json
@@ -2,7 +2,7 @@
"include": ["build.config.ts", "src", "__tests__"],
"compilerOptions": {
"outDir": "dist",
- "target": "ES2020",
+ "target": "ES2022",
"module": "ES2020",
"moduleResolution": "bundler",
"strict": true,
diff --git a/packages/plugin-legacy/build.config.ts b/packages/plugin-legacy/build.config.ts
index db325ecfa3b0a8..f7e0fdb0bc049f 100644
--- a/packages/plugin-legacy/build.config.ts
+++ b/packages/plugin-legacy/build.config.ts
@@ -7,5 +7,8 @@ export default defineBuildConfig({
rollup: {
emitCJS: true,
inlineDependencies: true,
+ esbuild: {
+ target: 'node18',
+ },
},
})
diff --git a/packages/plugin-legacy/package.json b/packages/plugin-legacy/package.json
index ee78c70817f109..801dcb557e968e 100644
--- a/packages/plugin-legacy/package.json
+++ b/packages/plugin-legacy/package.json
@@ -29,7 +29,7 @@
"prepublishOnly": "npm run build"
},
"engines": {
- "node": "^14.18.0 || >=16.0.0"
+ "node": "^18.0.0 || >=20.0.0"
},
"repository": {
"type": "git",
diff --git a/packages/vite/api-extractor.json b/packages/vite/api-extractor.json
index 642cef99fecd59..0b5b4178c2bd90 100644
--- a/packages/vite/api-extractor.json
+++ b/packages/vite/api-extractor.json
@@ -5,8 +5,6 @@
"mainEntryPointFilePath": "./temp/node/index.d.ts",
- "bundledPackages": ["lightningcss"],
-
"dtsRollup": {
"enabled": true,
"untrimmedFilePath": "",
diff --git a/packages/vite/client.d.ts b/packages/vite/client.d.ts
index b73389ec373f1f..0f2c3db286d82f 100644
--- a/packages/vite/client.d.ts
+++ b/packages/vite/client.d.ts
@@ -221,7 +221,7 @@ declare module '*.txt' {
// wasm?init
declare module '*.wasm?init' {
const initWasm: (
- options: WebAssembly.Imports,
+ options?: WebAssembly.Imports,
) => Promise
export default initWasm
}
diff --git a/packages/vite/package.json b/packages/vite/package.json
index 824305fc2a4841..546eb859ea5f42 100644
--- a/packages/vite/package.json
+++ b/packages/vite/package.json
@@ -38,7 +38,7 @@
"types"
],
"engines": {
- "node": "^14.18.0 || >=16.0.0"
+ "node": "^18.0.0 || >=20.0.0"
},
"repository": {
"type": "git",
@@ -57,7 +57,7 @@
"build-types": "run-s build-types-temp build-types-pre-patch build-types-roll build-types-post-patch build-types-check",
"build-types-temp": "tsc --emitDeclarationOnly --outDir temp/node -p src/node",
"build-types-pre-patch": "tsx scripts/prePatchTypes.ts",
- "build-types-roll": "tsx scripts/api-extractor.ts run && rimraf temp",
+ "build-types-roll": "api-extractor run && rimraf temp",
"build-types-post-patch": "tsx scripts/postPatchTypes.ts",
"build-types-check": "tsx scripts/checkBuiltTypes.ts && tsc --project tsconfig.check.json",
"typecheck": "tsc --noEmit",
diff --git a/packages/vite/rollup.config.ts b/packages/vite/rollup.config.ts
index 026288950e87c0..82415fff301b85 100644
--- a/packages/vite/rollup.config.ts
+++ b/packages/vite/rollup.config.ts
@@ -195,7 +195,7 @@ function createCjsConfig(isProduction: boolean) {
...Object.keys(pkg.dependencies),
...(isProduction ? [] : Object.keys(pkg.devDependencies)),
],
- plugins: [...createNodePlugins(false, false, false), bundleSizeLimit(150)],
+ plugins: [...createNodePlugins(false, false, false), bundleSizeLimit(155)],
})
}
@@ -317,7 +317,7 @@ const __require = require;
/**
* Guard the bundle size
*
- * @param limit size in KB
+ * @param limit size in kB
*/
function bundleSizeLimit(limit: number): Plugin {
return {
@@ -329,10 +329,10 @@ function bundleSizeLimit(limit: number): Plugin {
.join(''),
'utf-8',
)
- const kb = size / 1024
+ const kb = size / 1000
if (kb > limit) {
throw new Error(
- `Bundle size exceeded ${limit}kb, current size is ${kb.toFixed(
+ `Bundle size exceeded ${limit} kB, current size is ${kb.toFixed(
2,
)}kb.`,
)
diff --git a/packages/vite/scripts/api-extractor.ts b/packages/vite/scripts/api-extractor.ts
deleted file mode 100644
index 1154830ffa8cd6..00000000000000
--- a/packages/vite/scripts/api-extractor.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { Extractor, ExtractorConfig } from '@microsoft/api-extractor'
-
-const result = Extractor.invoke(
- ExtractorConfig.loadFileAndPrepare('./api-extractor.json'),
- {
- messageCallback: (message) => {
- const ignore = () => {
- // @ts-expect-error TS requires to use the const enum, which is not available as the named export in tsx
- message.logLevel = 'none'
- }
- if (message.sourceFilePath?.includes('lightningcss')) {
- ignore()
- }
- if (message.messageId === 'ae-forgotten-export') {
- if (message.sourceFilePath?.endsWith('/src/types/lightningcss.d.ts')) {
- // We only expose LightningCSS types via prefixed types to avoid
- // having confusing name like "Targets" in Vite types
- ignore()
- }
- }
- },
- },
-)
-
-if (!result.succeeded) process.exit(1)
diff --git a/packages/vite/scripts/checkBuiltTypes.ts b/packages/vite/scripts/checkBuiltTypes.ts
index 5601a1e84fb9cd..43f8a914b63c4d 100644
--- a/packages/vite/scripts/checkBuiltTypes.ts
+++ b/packages/vite/scripts/checkBuiltTypes.ts
@@ -17,7 +17,9 @@ const distDir = resolve(dir, '../dist')
const pkgJson = JSON.parse(
readFileSync(resolve(dir, '../package.json'), 'utf-8'),
)
-const deps = new Set(Object.keys(pkgJson.dependencies))
+const deps = new Set(
+ Object.keys(Object.assign(pkgJson.dependencies, pkgJson.peerDependencies)),
+)
type SpecifierError = {
loc: SourceLocation | null | undefined
diff --git a/packages/vite/src/client/client.ts b/packages/vite/src/client/client.ts
index 8943fb0521a5d7..b909c1328a9a3b 100644
--- a/packages/vite/src/client/client.ts
+++ b/packages/vite/src/client/client.ts
@@ -289,15 +289,12 @@ function notifyListeners(event: string, data: any): void {
const enableOverlay = __HMR_ENABLE_OVERLAY__
function createErrorOverlay(err: ErrorPayload['err']) {
- if (!enableOverlay) return
clearErrorOverlay()
document.body.appendChild(new ErrorOverlay(err))
}
function clearErrorOverlay() {
- document
- .querySelectorAll(overlayId)
- .forEach((n) => (n as ErrorOverlay).close())
+ document.querySelectorAll(overlayId).forEach((n) => n.close())
}
function hasErrorOverlay() {
@@ -388,9 +385,11 @@ const sheetsMap = new Map()
// collect existing style elements that may have been inserted during SSR
// to avoid FOUC or duplicate styles
if ('document' in globalThis) {
- document.querySelectorAll('style[data-vite-dev-id]').forEach((el) => {
- sheetsMap.set(el.getAttribute('data-vite-dev-id')!, el as HTMLStyleElement)
- })
+ document
+ .querySelectorAll('style[data-vite-dev-id]')
+ .forEach((el) => {
+ sheetsMap.set(el.getAttribute('data-vite-dev-id')!, el)
+ })
}
// all css imports should be inserted at the same position
diff --git a/packages/vite/src/client/overlay.ts b/packages/vite/src/client/overlay.ts
index 9951510f916a30..508eaf7e05bc9e 100644
--- a/packages/vite/src/client/overlay.ts
+++ b/packages/vite/src/client/overlay.ts
@@ -2,7 +2,9 @@ import type { ErrorPayload } from 'types/hmrPayload'
// injected by the hmr plugin when served
declare const __BASE__: string
+declare const __HMR_CONFIG_NAME__: string
+const hmrConfigName = __HMR_CONFIG_NAME__
const base = __BASE__ || '/'
// set :host styles to make playwright detect the element as visible
@@ -142,7 +144,7 @@ kbd {
Click outside, press Esc key, or fix the code to dismiss.
You can also disable this overlay by setting
- server.hmr.overlay to false in vite.config.js.
+ server.hmr.overlay to false in ${hmrConfigName}.
diff --git a/packages/vite/src/node/build.ts b/packages/vite/src/node/build.ts
index dfaab8362784c5..d8935a90b99d78 100644
--- a/packages/vite/src/node/build.ts
+++ b/packages/vite/src/node/build.ts
@@ -107,7 +107,7 @@ export interface BuildOptions {
assetsDir?: string
/**
* Static asset files smaller than this number (in bytes) will be inlined as
- * base64 strings. Default limit is `4096` (4kb). Set to `0` to disable.
+ * base64 strings. Default limit is `4096` (4 KiB). Set to `0` to disable.
* @default 4096
*/
assetsInlineLimit?: number
@@ -179,7 +179,6 @@ export interface BuildOptions {
/**
* Copy the public directory to outDir on write.
* @default true
- * @experimental
*/
copyPublicDir?: boolean
/**
@@ -234,7 +233,7 @@ export interface BuildOptions {
*/
reportCompressedSize?: boolean
/**
- * Adjust chunk size warning limit (in kbs).
+ * Adjust chunk size warning limit (in kB).
* @default 500
*/
chunkSizeWarningLimit?: number
@@ -535,7 +534,6 @@ export async function build(
}
const rollupOptions: RollupOptions = {
- context: 'globalThis',
preserveEntrySignatures: ssr
? 'allow-extension'
: libOptions
diff --git a/packages/vite/src/node/cli.ts b/packages/vite/src/node/cli.ts
index df858f403f80c5..f6d3c9b6d6fd15 100644
--- a/packages/vite/src/node/cli.ts
+++ b/packages/vite/src/node/cli.ts
@@ -102,6 +102,16 @@ function cleanOptions(
return ret
}
+/**
+ * host may be a number (like 0), should convert to string
+ */
+const convertHost = (v: any) => {
+ if (typeof v === 'number') {
+ return String(v)
+ }
+ return v
+}
+
cli
.option('-c, --config ', `[string] use specified config file`)
.option('--base ', `[string] public base path (default: /)`)
@@ -116,7 +126,7 @@ cli
.command('[root]', 'start dev server') // default command
.alias('serve') // the command is called 'serve' in Vite's API
.alias('dev') // alias to align with the script name
- .option('--host [host]', `[string] specify hostname`)
+ .option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
.option('--port ', `[number] specify port`)
.option('--https', `[boolean] use TLS + HTTP/2`)
.option('--open [path]', `[boolean | string] open browser on startup`)
@@ -306,7 +316,7 @@ cli
// preview
cli
.command('preview [root]', 'locally preview production build')
- .option('--host [host]', `[string] specify hostname`)
+ .option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
.option('--port ', `[number] specify port`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option('--https', `[boolean] use TLS + HTTP/2`)
diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts
index f73ae2ae703e1c..916af948368d9b 100644
--- a/packages/vite/src/node/config.ts
+++ b/packages/vite/src/node/config.ts
@@ -1017,7 +1017,7 @@ async function bundleConfigFile(
entryPoints: [fileName],
outfile: 'out.js',
write: false,
- target: ['node14.18', 'node16'],
+ target: ['node18'],
platform: 'node',
bundle: true,
format: isESM ? 'esm' : 'cjs',
diff --git a/packages/vite/src/node/index.ts b/packages/vite/src/node/index.ts
index ffa1d4ecd83a49..c4afbd2bd4812d 100644
--- a/packages/vite/src/node/index.ts
+++ b/packages/vite/src/node/index.ts
@@ -34,7 +34,6 @@ export type {
export type {
PreviewOptions,
PreviewServer,
- PreviewServerForHook,
PreviewServerHook,
ResolvedPreviewOptions,
} from './preview'
@@ -75,6 +74,7 @@ export type {
export type {
CSSOptions,
CSSModulesOptions,
+ LightningCSSOptions,
PreprocessCSSResult,
ResolvedCSSOptions,
} from './plugins/css'
@@ -117,7 +117,6 @@ export type {
} from 'types/customEvent'
export type {
ImportGlobFunction,
- ImportGlobEagerFunction,
ImportGlobOptions,
GeneralImportGlobOptions,
KnownAsTypeMap,
@@ -144,4 +143,3 @@ export type { Terser } from 'dep-types/terser'
export type { RollupCommonJSOptions } from 'dep-types/commonjs'
export type { RollupDynamicImportVarsOptions } from 'dep-types/dynamicImportVars'
export type { Matcher, AnymatchPattern, AnymatchFn } from 'dep-types/anymatch'
-export type { LightningCSSOptions } from 'dep-types/lightningcss'
diff --git a/packages/vite/src/node/plugin.ts b/packages/vite/src/node/plugin.ts
index e522295f30c896..4ec7ccc512d920 100644
--- a/packages/vite/src/node/plugin.ts
+++ b/packages/vite/src/node/plugin.ts
@@ -90,7 +90,7 @@ export interface Plugin extends RollupPlugin {
*/
configureServer?: ObjectHook
/**
- * Configure the preview server. The hook receives the {@link PreviewServerForHook}
+ * Configure the preview server. The hook receives the {@link PreviewServer}
* instance. This can also be used to store a reference to the server
* for use in other hooks.
*
diff --git a/packages/vite/src/node/plugins/clientInjections.ts b/packages/vite/src/node/plugins/clientInjections.ts
index 5ac79c8d14ef8e..2a773542aef58c 100644
--- a/packages/vite/src/node/plugins/clientInjections.ts
+++ b/packages/vite/src/node/plugins/clientInjections.ts
@@ -35,6 +35,7 @@ export function clientInjectionsPlugin(config: ResolvedConfig): Plugin {
const timeout = hmrConfig?.timeout || 30000
const overlay = hmrConfig?.overlay !== false
const isHmrServerSpecified = !!hmrConfig?.server
+ const hmrConfigName = path.basename(config.configFile || 'vite.config.js')
// hmr.clientPort -> hmr.port
// -> (24678 if middleware mode and HMR server is not specified) -> new URL(import.meta.url).port
@@ -65,6 +66,7 @@ export function clientInjectionsPlugin(config: ResolvedConfig): Plugin {
const hmrBaseReplacement = escapeReplacement(hmrBase)
const hmrTimeoutReplacement = escapeReplacement(timeout)
const hmrEnableOverlayReplacement = escapeReplacement(overlay)
+ const hmrConfigNameReplacement = escapeReplacement(hmrConfigName)
injectConfigValues = (code: string) => {
return code
@@ -79,6 +81,7 @@ export function clientInjectionsPlugin(config: ResolvedConfig): Plugin {
.replace(`__HMR_BASE__`, hmrBaseReplacement)
.replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement)
.replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement)
+ .replace(`__HMR_CONFIG_NAME__`, hmrConfigNameReplacement)
}
},
transform(code, id, options) {
diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts
index 9aa3abf5c2da68..7ed3eb9d456082 100644
--- a/packages/vite/src/node/plugins/css.ts
+++ b/packages/vite/src/node/plugins/css.ts
@@ -20,10 +20,10 @@ import type Sass from 'sass'
import type Stylus from 'stylus'
import type Less from 'less'
import type { Alias } from 'dep-types/alias'
-import type { LightningCSSOptions } from 'dep-types/lightningcss'
import type { TransformOptions } from 'esbuild'
import { formatMessages, transform } from 'esbuild'
import type { RawSourceMap } from '@ampproject/remapping'
+import type { BundleAsyncOptions, CustomAtRules } from 'lightningcss'
import { getCodeWithSourcemap, injectSourcesContent } from '../server/sourcemap'
import type { ModuleNode } from '../server/moduleGraph'
import type { ResolveFn, ViteDevServer } from '../'
@@ -139,6 +139,12 @@ export type ResolvedCSSOptions = Omit & {
}
}
+// remove options set by Vite
+export type LightningCSSOptions = Omit<
+ BundleAsyncOptions,
+ 'filename' | 'resolver' | 'minify' | 'sourceMap' | 'analyzeDependencies'
+>
+
export function resolveCSSOptions(
options: CSSOptions | undefined,
): ResolvedCSSOptions | undefined {
@@ -505,7 +511,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
} else {
let content = css
if (config.build.cssMinify) {
- content = await minifyCSS(content, config)
+ content = await minifyCSS(content, config, true)
}
code = `export default ${JSON.stringify(content)}`
}
@@ -616,9 +622,12 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
pureCssChunks.add(chunk)
}
if (opts.format === 'es' || opts.format === 'cjs') {
- const cssAssetName = chunk.facadeModuleId
- ? normalizePath(path.relative(config.root, chunk.facadeModuleId))
- : chunk.name
+ const isEntry = chunk.isEntry && isPureCssChunk
+ const cssAssetName = normalizePath(
+ !isEntry && chunk.facadeModuleId
+ ? path.relative(config.root, chunk.facadeModuleId)
+ : chunk.name,
+ )
const lang = path.extname(cssAssetName).slice(1)
const cssFileName = ensureFileExt(cssAssetName, '.css')
@@ -648,7 +657,6 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
source: chunkCSS,
})
const originalName = isPreProcessor(lang) ? cssAssetName : cssFileName
- const isEntry = chunk.isEntry && isPureCssChunk
generatedAssets
.get(config)!
.set(referenceId, { originalName, isEntry })
@@ -1275,7 +1283,7 @@ async function finalizeCss(
css = await hoistAtRules(css)
}
if (minify && config.build.cssMinify) {
- css = await minifyCSS(css, config)
+ css = await minifyCSS(css, config, false)
}
return css
}
@@ -1497,7 +1505,15 @@ async function doImportCSSReplace(
return `@import ${wrap}${await replacer(rawUrl)}${wrap}`
}
-async function minifyCSS(css: string, config: ResolvedConfig) {
+async function minifyCSS(
+ css: string,
+ config: ResolvedConfig,
+ inlined: boolean,
+) {
+ // We want inlined CSS to not end with a linebreak, while ensuring that
+ // regular CSS assets do end with a linebreak.
+ // See https://github.com/vitejs/vite/pull/13893#issuecomment-1678628198
+
if (config.build.cssMinify === 'lightningcss') {
const { code, warnings } = (await importLightningCSS()).transform({
...config.css?.lightningcss,
@@ -1516,7 +1532,8 @@ async function minifyCSS(css: string, config: ResolvedConfig) {
),
)
}
- return code.toString()
+ // LightningCSS output does not return a linebreak at the end
+ return code.toString() + (inlined ? '' : '\n')
}
try {
const { code, warnings } = await transform(css, {
@@ -1530,7 +1547,8 @@ async function minifyCSS(css: string, config: ResolvedConfig) {
colors.yellow(`warnings when minifying css:\n${msgs.join('\n')}`),
)
}
- return code
+ // esbuild output does return a linebreak at the end
+ return inlined ? code.trimEnd() : code
} catch (e) {
if (e.errors) {
e.message = '[esbuild css minify] ' + e.message
@@ -2167,13 +2185,15 @@ async function compileLightningCSS(
? (await importLightningCSS()).transformStyleAttribute({
filename,
code: Buffer.from(src),
- targets: config.css?.lightningcss?.targets,
minify: config.isProduction && !!config.build.cssMinify,
+ targets: config.css?.lightningcss?.targets,
analyzeDependencies: true,
+ visitor: config.css?.lightningcss?.visitor,
})
: await (
await importLightningCSS()
).bundleAsync({
+ ...config.css?.lightningcss,
filename,
resolver: {
read(filePath) {
@@ -2204,14 +2224,12 @@ async function compileLightningCSS(
return id
},
},
- targets: config.css?.lightningcss?.targets,
minify: config.isProduction && !!config.build.cssMinify,
sourceMap: config.css?.devSourcemap,
analyzeDependencies: true,
cssModules: cssModuleRE.test(id)
? config.css?.lightningcss?.cssModules ?? true
: undefined,
- drafts: config.css?.lightningcss?.drafts,
})
let css = res.code.toString()
diff --git a/packages/vite/src/node/plugins/importMetaGlob.ts b/packages/vite/src/node/plugins/importMetaGlob.ts
index 0daf6b04358b30..c76ab9f495196d 100644
--- a/packages/vite/src/node/plugins/importMetaGlob.ts
+++ b/packages/vite/src/node/plugins/importMetaGlob.ts
@@ -34,13 +34,11 @@ import { isCSSRequest, isModuleCSSRequest } from './css'
const { isMatch, scan } = micromatch
export interface ParsedImportGlob {
- match: RegExpMatchArray
index: number
globs: string[]
globsResolved: string[]
isRelative: boolean
options: GeneralImportGlobOptions
- type: string
start: number
end: number
}
@@ -58,8 +56,10 @@ export function getAffectedGlobModules(
(!affirmed.length || affirmed.some((glob) => isMatch(file, glob))) &&
(!negated.length || negated.every((glob) => isMatch(file, glob))),
)
- )
- modules.push(...(server.moduleGraph.getModulesByFile(id) || []))
+ ) {
+ const mod = server.moduleGraph.getModuleById(id)
+ if (mod) modules.push(mod)
+ }
}
modules.forEach((i) => {
if (i?.file) server.moduleGraph.onFileChange(i.file)
@@ -109,8 +109,7 @@ export function importGlobPlugin(config: ResolvedConfig): Plugin {
}
}
-const importGlobRE =
- /\bimport\.meta\.(glob|globEager|globEagerDefault)(?:<\w+>)?\s*\(/g
+const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g
const knownOptions = {
as: ['string'],
@@ -210,7 +209,6 @@ export async function parseImportGlob(
const matches = Array.from(cleanCode.matchAll(importGlobRE))
const tasks = matches.map(async (match, index) => {
- const type = match[1]
const start = match.index!
const err = (msg: string) => {
@@ -317,13 +315,11 @@ export async function parseImportGlob(
const isRelative = globs.every((i) => '.!'.includes(i[0]))
return {
- match,
index,
globs,
globsResolved,
isRelative,
options,
- type,
start,
end,
}
@@ -383,15 +379,6 @@ export async function transformGlobImport(
)
const matchedFiles = new Set()
- // TODO: backwards compatibility
- matches.forEach((i) => {
- if (i.type === 'globEager') i.options.eager = true
- if (i.type === 'globEagerDefault') {
- i.options.eager = true
- i.options.import = 'default'
- }
- })
-
if (!matches.length) return null
const s = new MagicString(code)
diff --git a/packages/vite/src/node/plugins/reporter.ts b/packages/vite/src/node/plugins/reporter.ts
index cbcb0409d1e3f0..bea7d4facd798b 100644
--- a/packages/vite/src/node/plugins/reporter.ts
+++ b/packages/vite/src/node/plugins/reporter.ts
@@ -285,7 +285,7 @@ export function buildReporterPlugin(config: ResolvedConfig): Plugin {
) {
config.logger.warn(
colors.yellow(
- `\n(!) Some chunks are larger than ${chunkLimit} kBs after minification. Consider:\n` +
+ `\n(!) Some chunks are larger than ${chunkLimit} kB after minification. Consider:\n` +
`- Using dynamic import() to code-split the application\n` +
`- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n` +
`- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`,
diff --git a/packages/vite/src/node/preview.ts b/packages/vite/src/node/preview.ts
index 460366446a2f3c..eb15dc55b95057 100644
--- a/packages/vite/src/node/preview.ts
+++ b/packages/vite/src/node/preview.ts
@@ -45,8 +45,7 @@ export function resolvePreviewOptions(
}
}
-// TODO: merge with PreviewServer in Vite 5
-export interface PreviewServerForHook {
+export interface PreviewServer {
/**
* The resolved vite config object
*/
@@ -65,7 +64,8 @@ export interface PreviewServerForHook {
*/
httpServer: http.Server
/**
- * The resolved urls Vite prints on the CLI
+ * The resolved urls Vite prints on the CLI.
+ * null before server is listening.
*/
resolvedUrls: ResolvedServerUrls | null
/**
@@ -74,13 +74,9 @@ export interface PreviewServerForHook {
printUrls(): void
}
-export interface PreviewServer extends PreviewServerForHook {
- resolvedUrls: ResolvedServerUrls
-}
-
export type PreviewServerHook = (
this: void,
- server: PreviewServerForHook,
+ server: PreviewServer,
) => (() => void) | void | Promise<(() => void) | void>
/**
@@ -122,7 +118,7 @@ export async function preview(
const options = config.preview
const logger = config.logger
- const server: PreviewServerForHook = {
+ const server: PreviewServer = {
config,
middlewares: app,
httpServer,
diff --git a/packages/vite/src/node/server/ws.ts b/packages/vite/src/node/server/ws.ts
index 4a298cac1eebd2..7df59370f9e1d8 100644
--- a/packages/vite/src/node/server/ws.ts
+++ b/packages/vite/src/node/server/ws.ts
@@ -1,9 +1,10 @@
import path from 'node:path'
-import type { Server } from 'node:http'
+import type { IncomingMessage, Server } from 'node:http'
import { STATUS_CODES, createServer as createHttpServer } from 'node:http'
import type { ServerOptions as HttpsServerOptions } from 'node:https'
import { createServer as createHttpsServer } from 'node:https'
import type { Socket } from 'node:net'
+import type { Duplex } from 'node:stream'
import colors from 'picocolors'
import type { WebSocket as WebSocketRaw } from 'ws'
import { WebSocketServer as WebSocketServerRaw_ } from 'ws'
@@ -104,6 +105,11 @@ export function createWebSocketServer(
// TODO: the main server port may not have been chosen yet as it may use the next available
const portsAreCompatible = !hmrPort || hmrPort === config.server.port
const wsServer = hmrServer || (portsAreCompatible && server)
+ let hmrServerWsListener: (
+ req: InstanceType,
+ socket: Duplex,
+ head: Buffer,
+ ) => void
const customListeners = new Map>>()
const clientsMap = new WeakMap()
const port = hmrPort || 24678
@@ -116,7 +122,7 @@ export function createWebSocketServer(
hmrBase = path.posix.join(hmrBase, hmrPath)
}
wss = new WebSocketServerRaw({ noServer: true })
- wsServer.on('upgrade', (req, socket, head) => {
+ hmrServerWsListener = (req, socket, head) => {
if (
req.headers['sec-websocket-protocol'] === HMR_HEADER &&
req.url === hmrBase
@@ -125,7 +131,8 @@ export function createWebSocketServer(
wss.emit('connection', ws, req)
})
}
- })
+ }
+ wsServer.on('upgrade', hmrServerWsListener)
} else {
// http server request handler keeps the same with
// https://github.com/websockets/ws/blob/45e17acea791d865df6b255a55182e9c42e5877a/lib/websocket-server.js#L88-L96
@@ -273,6 +280,11 @@ export function createWebSocketServer(
},
close() {
+ // should remove listener if hmr.server is set
+ // otherwise the old listener swallows all WebSocket connections
+ if (hmrServerWsListener && wsServer) {
+ wsServer.off('upgrade', hmrServerWsListener)
+ }
return new Promise((resolve, reject) => {
wss.clients.forEach((client) => {
client.terminate()
diff --git a/packages/vite/src/node/shortcuts.ts b/packages/vite/src/node/shortcuts.ts
index 66b45e6b42713b..0c3a7da40ba568 100644
--- a/packages/vite/src/node/shortcuts.ts
+++ b/packages/vite/src/node/shortcuts.ts
@@ -147,8 +147,13 @@ const BASE_PREVIEW_SHORTCUTS: CLIShortcut[] = [
key: 'o',
description: 'open in browser',
action(server) {
- const url = server.resolvedUrls.local[0] ?? server.resolvedUrls.network[0]
- openBrowser(url, true, server.config.logger)
+ const url =
+ server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0]
+ if (url) {
+ openBrowser(url, true, server.config.logger)
+ } else {
+ server.config.logger.warn('No URL available to open in browser')
+ }
},
},
{
diff --git a/packages/vite/src/types/lightningcss.d.ts b/packages/vite/src/types/lightningcss.d.ts
deleted file mode 100644
index 98367f381283a2..00000000000000
--- a/packages/vite/src/types/lightningcss.d.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import type {
- CSSModulesConfig,
- Drafts,
- Features,
- NonStandard,
- PseudoClasses,
- Targets,
-} from 'lightningcss'
-
-/**
- * Options are spread, so you can also use options that are not typed here like
- * visitor (not exposed because it would impact too much the bundle size)
- */
-export type LightningCSSOptions = {
- targets?: Targets
- include?: Features
- exclude?: Features
- drafts?: Drafts
- nonStandard?: NonStandard
- pseudoClasses?: PseudoClasses
- unusedSymbols?: string[]
- cssModules?: CSSModulesConfig
-}
diff --git a/packages/vite/tsconfig.base.json b/packages/vite/tsconfig.base.json
index 37eb865185662d..04df5b8dd6f5d7 100644
--- a/packages/vite/tsconfig.base.json
+++ b/packages/vite/tsconfig.base.json
@@ -1,6 +1,6 @@
{
"compilerOptions": {
- "target": "ES2020",
+ "target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
diff --git a/packages/vite/types/importGlob.d.ts b/packages/vite/types/importGlob.d.ts
index 98786bbdd9efa5..b9ba52ec1ca881 100644
--- a/packages/vite/types/importGlob.d.ts
+++ b/packages/vite/types/importGlob.d.ts
@@ -71,27 +71,3 @@ export interface ImportGlobFunction {
options: ImportGlobOptions,
): Record
}
-
-export interface ImportGlobEagerFunction {
- /**
- * Eagerly import a list of files with a glob pattern.
- *
- * Overload 1: No generic provided, infer the type from `as`
- */
- <
- As extends string,
- T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown,
- >(
- glob: string | string[],
- options?: Omit, 'eager'>,
- ): Record
- /**
- * Eagerly import a list of files with a glob pattern.
- *
- * Overload 2: Module generic provided
- */
- (
- glob: string | string[],
- options?: Omit, 'eager'>,
- ): Record
-}
diff --git a/packages/vite/types/importMeta.d.ts b/packages/vite/types/importMeta.d.ts
index e9047a78117d82..bd4418379951b3 100644
--- a/packages/vite/types/importMeta.d.ts
+++ b/packages/vite/types/importMeta.d.ts
@@ -19,8 +19,4 @@ interface ImportMeta {
readonly env: ImportMetaEnv
glob: import('./importGlob').ImportGlobFunction
- /**
- * @deprecated Use `import.meta.glob('*', { eager: true })` instead
- */
- globEager: import('./importGlob').ImportGlobEagerFunction
}
diff --git a/playground/assets/vite.config.js b/playground/assets/vite.config.js
index 8305a6a0d6ede8..a1bcf02143de76 100644
--- a/playground/assets/vite.config.js
+++ b/playground/assets/vite.config.js
@@ -12,7 +12,7 @@ export default defineConfig({
assetsInclude: ['**/*.unknown'],
build: {
outDir: 'dist/foo',
- assetsInlineLimit: 8192, // 8kb
+ assetsInlineLimit: 8000, // 8 kB
manifest: true,
watch: {},
},
diff --git a/playground/backend-integration/__tests__/backend-integration.spec.ts b/playground/backend-integration/__tests__/backend-integration.spec.ts
index 8d067f0616775d..442ed159219af9 100644
--- a/playground/backend-integration/__tests__/backend-integration.spec.ts
+++ b/playground/backend-integration/__tests__/backend-integration.spec.ts
@@ -37,7 +37,7 @@ describe.runIf(isBuild)('build', () => {
const cssAssetEntry = manifest['global.css']
const scssAssetEntry = manifest['nested/blue.scss']
const imgAssetEntry = manifest['../images/logo.png']
- const dirFooAssetEntry = manifest['../../dir/foo.css'] // '\\' should not be used even on windows
+ const dirFooAssetEntry = manifest['../dynamic/foo.css'] // '\\' should not be used even on windows
expect(htmlEntry.css.length).toEqual(1)
expect(htmlEntry.assets.length).toEqual(1)
expect(cssAssetEntry?.file).not.toBeUndefined()
@@ -48,6 +48,9 @@ describe.runIf(isBuild)('build', () => {
expect(imgAssetEntry?.file).not.toBeUndefined()
expect(imgAssetEntry?.isEntry).toBeUndefined()
expect(dirFooAssetEntry).not.toBeUndefined()
+ // use the entry name
+ expect(manifest['bar.css']).not.toBeUndefined()
+ expect(manifest['foo.css']).toBeUndefined()
})
})
diff --git a/playground/backend-integration/dir/foo.css b/playground/backend-integration/dir/foo.css
index c2fad7486d3ab6..1e31c585bebc9c 100644
--- a/playground/backend-integration/dir/foo.css
+++ b/playground/backend-integration/dir/foo.css
@@ -1,3 +1,3 @@
-.windows-path-foo {
+.entry-name-foo {
color: blue;
}
diff --git a/playground/backend-integration/frontend/dynamic/foo.css b/playground/backend-integration/frontend/dynamic/foo.css
new file mode 100644
index 00000000000000..c2fad7486d3ab6
--- /dev/null
+++ b/playground/backend-integration/frontend/dynamic/foo.css
@@ -0,0 +1,3 @@
+.windows-path-foo {
+ color: blue;
+}
diff --git a/playground/backend-integration/frontend/dynamic/foo.ts b/playground/backend-integration/frontend/dynamic/foo.ts
new file mode 100644
index 00000000000000..c2441c49231d80
--- /dev/null
+++ b/playground/backend-integration/frontend/dynamic/foo.ts
@@ -0,0 +1 @@
+import './foo.css'
diff --git a/playground/backend-integration/frontend/entrypoints/main.ts b/playground/backend-integration/frontend/entrypoints/main.ts
index f5a332191dd9e4..d63a57a023847e 100644
--- a/playground/backend-integration/frontend/entrypoints/main.ts
+++ b/playground/backend-integration/frontend/entrypoints/main.ts
@@ -1,4 +1,5 @@
import 'vite/modulepreload-polyfill'
+import('../dynamic/foo') // should be dynamic import to split chunks
export const colorClass = 'text-black'
diff --git a/playground/backend-integration/vite.config.js b/playground/backend-integration/vite.config.js
index b9e2c9f35c6fee..881eac1a14688e 100644
--- a/playground/backend-integration/vite.config.js
+++ b/playground/backend-integration/vite.config.js
@@ -19,7 +19,7 @@ function BackendIntegrationExample() {
.map((filename) => [path.relative(root, filename), filename])
entrypoints.push(['tailwindcss-colors', 'tailwindcss/colors.js'])
- entrypoints.push(['foo.css', path.resolve(__dirname, './dir/foo.css')])
+ entrypoints.push(['bar.css', path.resolve(__dirname, './dir/foo.css')])
return {
build: {
diff --git a/playground/css/__tests__/postcss-plugins-different-dir/postcss-plugins-different-dir.spec.ts b/playground/css/__tests__/postcss-plugins-different-dir/postcss-plugins-different-dir.spec.ts
index fb748bf2c8fff2..1d21eb760dabfd 100644
--- a/playground/css/__tests__/postcss-plugins-different-dir/postcss-plugins-different-dir.spec.ts
+++ b/playground/css/__tests__/postcss-plugins-different-dir/postcss-plugins-different-dir.spec.ts
@@ -21,7 +21,7 @@ test.runIf(isServe)('postcss plugins in different dir', async () => {
await server.listen()
try {
await page.goto(`http://localhost:${port}`)
- const tailwindStyle = await page.$('.tailwind-style')
+ const tailwindStyle = page.locator('#tailwind-style')
expect(await getBgColor(tailwindStyle)).toBe('rgb(254, 226, 226)')
expect(await getColor(tailwindStyle)).toBe('rgb(136, 136, 136)')
} finally {
diff --git a/playground/glob-import/__tests__/glob-import.spec.ts b/playground/glob-import/__tests__/glob-import.spec.ts
index 931edfd99138de..239278477eea2c 100644
--- a/playground/glob-import/__tests__/glob-import.spec.ts
+++ b/playground/glob-import/__tests__/glob-import.spec.ts
@@ -11,6 +11,7 @@ import {
page,
removeFile,
untilBrowserLogAfter,
+ untilUpdated,
viteTestUrl,
withRetry,
} from '~utils'
@@ -48,7 +49,7 @@ const allResult = {
'/dir/baz.json': json,
'/dir/foo.css': isBuild
? {
- default: '.foo{color:#00f}\n',
+ default: '.foo{color:#00f}',
}
: {
default: '.foo {\n color: blue;\n}\n',
@@ -131,6 +132,12 @@ test('unassigned import processes', async () => {
)
})
+test('import glob in package', async () => {
+ expect(await page.textContent('.in-package')).toBe(
+ JSON.stringify(['/pkg-pages/foo.js']),
+ )
+})
+
if (!isBuild) {
test('hmr for adding/removing files', async () => {
const resultElement = page.locator('.result')
@@ -190,6 +197,22 @@ if (!isBuild) {
response = await request.catch(() => ({ status: () => -1 }))
expect(response.status()).toBe(-1)
})
+
+ test('hmr for adding/removing files in package', async () => {
+ const resultElement = page.locator('.in-package')
+
+ addFile('pkg-pages/bar.js', '// empty')
+ await untilUpdated(
+ () => resultElement.textContent(),
+ JSON.stringify(['/pkg-pages/foo.js', '/pkg-pages/bar.js'].sort()),
+ )
+
+ removeFile('pkg-pages/bar.js')
+ await untilUpdated(
+ () => resultElement.textContent(),
+ JSON.stringify(['/pkg-pages/foo.js']),
+ )
+ })
}
test('tree-shake eager css', async () => {
diff --git a/playground/glob-import/import-meta-glob-pkg/index.js b/playground/glob-import/import-meta-glob-pkg/index.js
new file mode 100644
index 00000000000000..44705cf18f9f22
--- /dev/null
+++ b/playground/glob-import/import-meta-glob-pkg/index.js
@@ -0,0 +1,4 @@
+export const g = import.meta.glob('/pkg-pages/*.js')
+document.querySelector('.in-package').textContent = JSON.stringify(
+ Object.keys(g).sort(),
+)
diff --git a/playground/glob-import/import-meta-glob-pkg/package.json b/playground/glob-import/import-meta-glob-pkg/package.json
new file mode 100644
index 00000000000000..7138de851543cf
--- /dev/null
+++ b/playground/glob-import/import-meta-glob-pkg/package.json
@@ -0,0 +1,5 @@
+{
+ "name": "@vitejs/test-import-meta-glob-pkg",
+ "type": "module",
+ "main": "./index.js"
+}
diff --git a/playground/glob-import/index.html b/playground/glob-import/index.html
index b726965ff62067..3b72430668e14d 100644
--- a/playground/glob-import/index.html
+++ b/playground/glob-import/index.html
@@ -23,6 +23,8 @@