Skip to content

Commit

Permalink
Merge branch 'main' into chore/http-server-type
Browse files Browse the repository at this point in the history
  • Loading branch information
lzt1008 committed Nov 2, 2023
2 parents 8477e1a + 997f2d5 commit e2ffa20
Show file tree
Hide file tree
Showing 30 changed files with 208 additions and 155 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ To develop and test the core `vite` package:

You can alternatively use [Vite.js Docker Dev](https://github.com/nystudio107/vitejs-docker-dev) for a containerized Docker setup for Vite.js development.

> Vite uses pnpm v7. If you are working on multiple projects with different versions of pnpm, it's recommended to enable [Corepack](https://github.com/nodejs/corepack) by running `corepack enable`.
> Vite uses pnpm v8. If you are working on multiple projects with different versions of pnpm, it's recommended to enable [Corepack](https://github.com/nodejs/corepack) by running `corepack enable`.
### Ignoring commits when running `git blame`

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<br/>
<p align="center">
<a href="https://npmjs.com/package/vite"><img src="https://img.shields.io/npm/v/vite.svg" alt="npm package"></a>
<a href="https://nodejs.org/en/about/releases/"><img src="https://img.shields.io/node/v/vite.svg" alt="node compatibility"></a>
<a href="https://nodejs.org/en/about/previous-releases"><img src="https://img.shields.io/node/v/vite.svg" alt="node compatibility"></a>
<a href="https://github.com/vitejs/vite/actions/workflows/ci.yml"><img src="https://github.com/vitejs/vite/actions/workflows/ci.yml/badge.svg?branch=main" alt="build status"></a>
<a href="https://pr.new/vitejs/vite"><img src="https://developer.stackblitz.com/img/start_pr_dark_small.svg" alt="Start new PR in StackBlitz Codeflow"></a>
<a href="https://chat.vitejs.dev"><img src="https://img.shields.io/badge/chat-discord-blue?style=flat&logo=discord" alt="discord chat"></a>
Expand Down
9 changes: 8 additions & 1 deletion docs/.vitepress/theme/composables/sponsor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,14 @@ const viteSponsors: Pick<Sponsors, 'special' | 'gold'> = {
img: '/astro.svg',
},
],
gold: [],
gold: [
// through GitHub -> OpenCollective
{
name: 'Remix',
url: 'https://remix.run/',
img: '/remix.svg',
},
],
}

export function useSponsor() {
Expand Down
10 changes: 10 additions & 0 deletions docs/guide/api-hmr.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,16 @@ if (import.meta.hot) {
The `import.meta.hot.data` object is persisted across different instances of the same updated module. It can be used to pass on information from a previous version of the module to the next one.
Note that re-assignment of `data` itself is not supported. Instead, you should mutate properties of the `data` object so information added from other handlers are preserved.
```js
// ok
import.meta.hot.data.someValue = 'hello'

// not supported
import.meta.hot.data = { someValue: 'hello' }
```
## `hot.decline()`
This is currently a noop and is there for backward compatibility. This could change in the future if there is a new usage for it. To indicate that the module is not hot-updatable, use `hot.invalidate()`.
Expand Down
10 changes: 0 additions & 10 deletions docs/guide/env-and-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,6 @@ Vite exposes env variables on the special **`import.meta.env`** object. Some bui

- **`import.meta.env.SSR`**: {boolean} whether the app is running in the [server](./ssr.md#conditional-logic).

### Production Replacement

During production, these env variables are **statically replaced**. It is therefore necessary to always reference them using the full static string. For example, dynamic key access like `import.meta.env[key]` will not work.

It will also replace these strings appearing in JavaScript strings and Vue templates. This should be a rare case, but it can be unintended. You may see errors like `Missing Semicolon` or `Unexpected token` in this case, for example when `"process.env.NODE_ENV"` is transformed to `""development": "`. There are ways to work around this behavior:

- For JavaScript strings, you can break the string up with a Unicode zero-width space, e.g. `'import.meta\u200b.env.MODE'`.

- For Vue templates or other HTML that gets compiled into JavaScript strings, you can use the [`<wbr>` tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr), e.g. `import.meta.<wbr>env.MODE`.

## `.env` Files

Vite uses [dotenv](https://github.com/motdotla/dotenv) to load additional environment variables from the following files in your [environment directory](/config/shared-options.md#envdir):
Expand Down
6 changes: 4 additions & 2 deletions docs/guide/performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ Vite's internal and official plugins are optimized to do the least amount of wor

However, the performance of community plugins is out of Vite's control, which may affect the developer experience. Here are a few things you can look out for when using additional Vite plugins:

1. The `buildStart`, `config`, and `configResolved` hooks should not run long and extensive operations. These hooks are awaited during dev server startup, which delays when you can access the site in the browser.
1. Large dependencies that are only used in certain cases should be dynamically imported to reduce the Node.js startup time. Example refactors: [vite-plugin-react#212](https://github.com/vitejs/vite-plugin-react/pull/212) and [vite-plugin-pwa#224](https://github.com/vite-pwa/vite-plugin-pwa/pull/244).

2. The `resolveId`, `load`, and `transform` hooks may cause some files to load slower than others. While sometimes unavoidable, it's still worth checking for possible areas to optimize. For example, checking if the `code` contains a specific keyword, or the `id` matches a specific extension, before doing the full transformation.
2. The `buildStart`, `config`, and `configResolved` hooks should not run long and extensive operations. These hooks are awaited during dev server startup, which delays when you can access the site in the browser.

3. The `resolveId`, `load`, and `transform` hooks may cause some files to load slower than others. While sometimes unavoidable, it's still worth checking for possible areas to optimize. For example, checking if the `code` contains a specific keyword, or the `id` matches a specific extension, before doing the full transformation.

The longer it takes to transform a file, the more significant the request waterfall will be when loading the site in the browser.

Expand Down
15 changes: 15 additions & 0 deletions docs/public/remix.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@
"eslint --cache --fix"
]
},
"packageManager": "[email protected].0",
"packageManager": "[email protected].1",
"pnpm": {
"overrides": {
"vite": "workspace:*"
Expand Down
13 changes: 13 additions & 0 deletions packages/vite/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
## 5.0.0-beta.15 (2023-11-01)

* feat: expose parseAst and parseAstAsync from rollup (#14833) ([6229485](https://github.com/vitejs/vite/commit/6229485)), closes [#14833](https://github.com/vitejs/vite/issues/14833)
* feat: upgrade rollup to 4.2.0 and use parseAstAsync (#14821) ([86a5356](https://github.com/vitejs/vite/commit/86a5356)), closes [#14821](https://github.com/vitejs/vite/issues/14821)
* feat(pluginContainer): implement watchChange hook (#14822) ([9369d8d](https://github.com/vitejs/vite/commit/9369d8d)), closes [#14822](https://github.com/vitejs/vite/issues/14822)
* feat(server): add warmupRequest api (#14787) ([8690581](https://github.com/vitejs/vite/commit/8690581)), closes [#14787](https://github.com/vitejs/vite/issues/14787)
* refactor: simplify build optimizer node_env handling (#14829) ([275907b](https://github.com/vitejs/vite/commit/275907b)), closes [#14829](https://github.com/vitejs/vite/issues/14829)
* chore: fix typo (#14820) ([eda1247](https://github.com/vitejs/vite/commit/eda1247)), closes [#14820](https://github.com/vitejs/vite/issues/14820)
* chore: revert "feat: show warning to discourage putting process/global to `define` option (#14447)" ([0426910](https://github.com/vitejs/vite/commit/0426910)), closes [#14447](https://github.com/vitejs/vite/issues/14447) [#14827](https://github.com/vitejs/vite/issues/14827)
* perf(define): create simple regex for checks (#14788) ([bd15537](https://github.com/vitejs/vite/commit/bd15537)), closes [#14788](https://github.com/vitejs/vite/issues/14788)



## 5.0.0-beta.14 (2023-10-30)

* fix(define): correctly replace same define values (#14786) ([f36fcd2](https://github.com/vitejs/vite/commit/f36fcd2)), closes [#14786](https://github.com/vitejs/vite/issues/14786)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vite",
"version": "5.0.0-beta.14",
"version": "5.0.0-beta.15",
"type": "module",
"license": "MIT",
"author": "Evan You",
Expand Down
6 changes: 4 additions & 2 deletions packages/vite/rollup.dts.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default defineConfig({
},
external: [
/^node:*/,
'rollup/parseAst',
...Object.keys(pkg.dependencies),
// lightningcss types are bundled
...Object.keys(pkg.devDependencies).filter((d) => d !== 'lightningcss'),
Expand Down Expand Up @@ -80,13 +81,14 @@ function patchTypes(): Plugin {
},
renderChunk(code, chunk) {
// Validate that chunk imports do not import dev deps
const deps = new Set(Object.keys(pkg.dependencies))
const deps = Object.keys(pkg.dependencies)
for (const id of chunk.imports) {
if (
!id.startsWith('./') &&
!id.startsWith('../') &&
!id.startsWith('node:') &&
!deps.has(id)
!deps.includes(id) &&
!deps.some((name) => id.startsWith(name + '/'))
) {
// If validation failed, only warn and set exit code 1 so that files
// are written to disk for inspection, but the build will fail
Expand Down
7 changes: 4 additions & 3 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import { resolveChokidarOptions } from './watch'
import { completeSystemWrapPlugin } from './plugins/completeSystemWrap'
import { mergeConfig } from './publicUtils'
import { webWorkerPostPlugin } from './plugins/worker'
import { getHookHandler } from './plugins'

export interface BuildOptions {
/**
Expand Down Expand Up @@ -959,7 +960,7 @@ function injectSsrFlagToHooks(plugin: Plugin): Plugin {
function wrapSsrResolveId(hook?: Plugin['resolveId']): Plugin['resolveId'] {
if (!hook) return

const fn = 'handler' in hook ? hook.handler : hook
const fn = getHookHandler(hook)
const handler: Plugin['resolveId'] = function (id, importer, options) {
return fn.call(this, id, importer, injectSsrFlag(options))
}
Expand All @@ -977,7 +978,7 @@ function wrapSsrResolveId(hook?: Plugin['resolveId']): Plugin['resolveId'] {
function wrapSsrLoad(hook?: Plugin['load']): Plugin['load'] {
if (!hook) return

const fn = 'handler' in hook ? hook.handler : hook
const fn = getHookHandler(hook)
const handler: Plugin['load'] = function (id, ...args) {
// @ts-expect-error: Receiving options param to be future-proof if Rollup adds it
return fn.call(this, id, injectSsrFlag(args[0]))
Expand All @@ -996,7 +997,7 @@ function wrapSsrLoad(hook?: Plugin['load']): Plugin['load'] {
function wrapSsrTransform(hook?: Plugin['transform']): Plugin['transform'] {
if (!hook) return

const fn = 'handler' in hook ? hook.handler : hook
const fn = getHookHandler(hook)
const handler: Plugin['transform'] = function (code, importer, ...args) {
// @ts-expect-error: Receiving options param to be future-proof if Rollup adds it
return fn.call(this, code, importer, injectSsrFlag(args[0]))
Expand Down
9 changes: 6 additions & 3 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type { Alias, AliasOptions } from 'dep-types/alias'
import aliasPlugin from '@rollup/plugin-alias'
import { build } from 'esbuild'
import type { RollupOptions } from 'rollup'
import type { HookHandler, Plugin } from './plugin'
import type { HookHandler, Plugin, PluginWithRequiredHook } from './plugin'
import type {
BuildOptions,
RenderBuiltAssetUrl,
Expand Down Expand Up @@ -43,6 +43,7 @@ import {
} from './utils'
import {
createPluginHookUtils,
getHookHandler,
getSortedPluginsByHook,
resolvePlugins,
} from './plugins'
Expand Down Expand Up @@ -383,7 +384,9 @@ export type ResolvedConfig = Readonly<
>

export interface PluginHookUtils {
getSortedPlugins: (hookName: keyof Plugin) => Plugin[]
getSortedPlugins: <K extends keyof Plugin>(
hookName: K,
) => PluginWithRequiredHook<K>[]
getSortedPluginHooks: <K extends keyof Plugin>(
hookName: K,
) => NonNullable<HookHandler<Plugin[K]>>[]
Expand Down Expand Up @@ -1207,7 +1210,7 @@ async function runConfigHook(

for (const p of getSortedPluginsByHook('config', plugins)) {
const hook = p.config
const handler = hook && 'handler' in hook ? hook.handler : hook
const handler = getHookHandler(hook)
if (handler) {
const res = await handler(conf, configEnv)
if (res) {
Expand Down
3 changes: 3 additions & 0 deletions packages/vite/src/node/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,6 @@ export const wildcardHosts = new Set([
export const DEFAULT_DEV_PORT = 5173

export const DEFAULT_PREVIEW_PORT = 4173

export const ASYNC_DISPOSE: typeof Symbol.asyncDispose =
Symbol.asyncDispose || Symbol.for('Symbol.asyncDispose')
1 change: 1 addition & 0 deletions packages/vite/src/node/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type * as Rollup from 'rollup'

export type { Rollup }
export { parseAst, parseAstAsync } from 'rollup/parseAst'
export {
defineConfig,
loadConfigFromFile,
Expand Down
13 changes: 6 additions & 7 deletions packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export type ExportsData = {
jsxLoader?: boolean
}

export interface DepsOptimizer {
export interface DepsOptimizer extends AsyncDisposable {
metadata: DepOptimizationMetadata
scanProcessing?: Promise<void>
registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo
Expand Down Expand Up @@ -755,13 +755,12 @@ async function prepareEsbuildOptimizerRun(
if (optimizerContext.cancelled) return { context: undefined, idToExports }

// esbuild automatically replaces process.env.NODE_ENV for platform 'browser'
// In lib mode, we need to keep process.env.NODE_ENV untouched, so to at build
// time we replace it by __vite_process_env_NODE_ENV. This placeholder will be
// later replaced by the define plugin
// But in lib mode, we need to keep process.env.NODE_ENV untouched
const define = {
'process.env.NODE_ENV': isBuild
? '__vite_process_env_NODE_ENV'
: JSON.stringify(process.env.NODE_ENV || config.mode),
'process.env.NODE_ENV':
isBuild && config.build.lib
? 'process.env.NODE_ENV'
: JSON.stringify(process.env.NODE_ENV || config.mode),
}

const platform =
Expand Down
5 changes: 5 additions & 0 deletions packages/vite/src/node/optimizer/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import colors from 'picocolors'
import { createDebugger, getHash } from '../utils'
import { getDepOptimizationConfig } from '../config'
import type { ResolvedConfig, ViteDevServer } from '..'
import { ASYNC_DISPOSE } from '../constants'
import {
addManuallyIncludedOptimizeDeps,
addOptimizedDepInfo,
Expand Down Expand Up @@ -119,6 +120,9 @@ async function createDepsOptimizer(
resetRegisteredIds,
ensureFirstRun,
close,
[ASYNC_DISPOSE]() {
return this.close()
},
options: getDepOptimizationConfig(config, ssr),
}

Expand Down Expand Up @@ -832,6 +836,7 @@ async function createDevSsrDepsOptimizer(
ensureFirstRun: () => {},

close: async () => {},
[ASYNC_DISPOSE]: async () => {},
options: config.ssr.optimizeDeps,
}
devSsrDepsOptimizerMap.set(config, depsOptimizer)
Expand Down
4 changes: 4 additions & 0 deletions packages/vite/src/node/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,7 @@ export interface Plugin<A = any> extends RollupPlugin<A> {
}

export type HookHandler<T> = T extends ObjectHook<infer H> ? H : T

export type PluginWithRequiredHook<K extends keyof Plugin> = Plugin & {
[P in K]: NonNullable<Plugin[P]>
}
6 changes: 1 addition & 5 deletions packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export function definePlugin(config: ResolvedConfig): Plugin {
'process.env.NODE_ENV': JSON.stringify(nodeEnv),
'global.process.env.NODE_ENV': JSON.stringify(nodeEnv),
'globalThis.process.env.NODE_ENV': JSON.stringify(nodeEnv),
__vite_process_env_NODE_ENV: JSON.stringify(nodeEnv),
})
}

Expand Down Expand Up @@ -69,9 +68,6 @@ export function definePlugin(config: ResolvedConfig): Plugin {
}

// Additional define fixes based on `ssr` value
if (isBuild && !replaceProcessEnv) {
define['__vite_process_env_NODE_ENV'] = 'process.env.NODE_ENV'
}
if ('import.meta.env.SSR' in define) {
define['import.meta.env.SSR'] = ssr + ''
}
Expand All @@ -86,7 +82,7 @@ export function definePlugin(config: ResolvedConfig): Plugin {
// Create regex pattern as a fast check before running esbuild
const patternKeys = Object.keys(userDefine)
if (replaceProcessEnv && Object.keys(processEnv).length) {
patternKeys.push('process.env', '__vite_process_env_NODE_ENV')
patternKeys.push('process.env')
}
if (Object.keys(importMetaKeys).length) {
patternKeys.push('import.meta.env', 'import.meta.hot')
Expand Down
21 changes: 2 additions & 19 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,8 @@ import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import { shouldExternalizeForSSR } from '../ssr/ssrExternal'
import { getDepsOptimizer, optimizedDepNeedsInterop } from '../optimizer'
import { ERR_CLOSED_SERVER } from '../server/pluginContainer'
import { checkPublicFile, urlRE } from './asset'
import {
ERR_OUTDATED_OPTIMIZED_DEP,
throwOutdatedRequest,
} from './optimizedDeps'
import { throwOutdatedRequest } from './optimizedDeps'
import { isCSSRequest, isDirectCSSRequest } from './css'
import { browserExternalId } from './resolve'
import { serializeDefine } from './define'
Expand Down Expand Up @@ -625,20 +621,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
// These requests will also be registered in transformRequest to be awaited
// by the deps optimizer
const url = removeImportQuery(hmrUrl)
server.transformRequest(url, { ssr }).catch((e) => {
if (
e?.code === ERR_OUTDATED_OPTIMIZED_DEP ||
e?.code === ERR_CLOSED_SERVER
) {
// these are expected errors
return
}
// Unexpected error, log the issue but avoid an unhandled exception
config.logger.error(`Pre-transform error: ${e.message}`, {
error: e,
timestamp: true,
})
})
server.warmupRequest(url, { ssr })
}
} else if (!importer.startsWith(withTrailingSlash(clientDir))) {
if (!isInNodeModules(importer)) {
Expand Down
Loading

0 comments on commit e2ffa20

Please sign in to comment.