Skip to content

Commit

Permalink
Merge branch 'vitejs:main' into chore/http-server-type
Browse files Browse the repository at this point in the history
  • Loading branch information
lzt1008 committed Oct 31, 2023
2 parents 3db374a + 9866be0 commit 8477e1a
Show file tree
Hide file tree
Showing 14 changed files with 144 additions and 125 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ jobs:

- name: Get changed files
id: changed-files
uses: tj-actions/changed-files@fea790cb660e33aef4bdf07304e28fedd77dfa13 # v39.2.4
uses: tj-actions/changed-files@bfc49f4cff6934aa236c171f9bcbf1dd6b1ef438 # v40.0.1
with:
files: |
docs/**
Expand Down
2 changes: 1 addition & 1 deletion docs/config/server-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ Set to `true` to exit if port is already in use, instead of automatically trying

## server.https

- **Type:** `boolean | https.ServerOptions`
- **Type:** `https.ServerOptions`

Enable TLS + HTTP/2. Note this downgrades to TLS only when the [`server.proxy` option](#server-proxy) is also used.

Expand Down
14 changes: 7 additions & 7 deletions docs/guide/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Vite is now using Rollup 4 which also brings along its breaking changes, in part
- For Vite plugins, `this.resolve` `skipSelf` option is now `true` by default.
- For Vite plugins, `this.parse` now only supports the `allowReturnOutsideFunction` option for now.

Read the full breaking changes in [Rollup's release notes](https://github.com/rollup/rollup/releases/tag/v4.0.0) for build-related changes in `build.rollupOptions`.
Read the full breaking changes in [Rollup's release notes](https://github.com/rollup/rollup/releases/tag/v4.0.0) for build-related changes in [`build.rollupOptions`](/config/build-options.md#build-rollupoptions).

## Deprecate CJS Node API

Expand All @@ -34,7 +34,7 @@ See the [troubleshooting guide](/guide/troubleshooting.html#vite-cjs-node-api-de

## Rework `define` and `import.meta.env.*` replacement strategy

In Vite 4, the `define` and `import.meta.env.*` features use different replacement strategies in dev and build:
In Vite 4, the [`define`](/config/shared-options.md#define) and [`import.meta.env.*`](/guide/env-and-mode.md#env-variables) features use different replacement strategies in dev and build:

- In dev, both features are injected as global variables to `globalThis` and `import.meta` respectively.
- In build, both features are statically replaced with a regex.
Expand Down Expand Up @@ -98,11 +98,11 @@ Note that these changes matches the Node.js behaviour, so you can also run the i

### `worker.plugins` is now a function

In Vite 4, `worker.plugins` accepted an array of plugins (`(Plugin | Plugin[])[]`). From Vite 5, it needs to be configured as a function that returns an array of plugins (`() => (Plugin | Plugin[])[]`). This change is required so parallel worker builds run more consistently and predictably.
In Vite 4, [`worker.plugins`](/config/worker-options.md#worker-plugins) accepted an array of plugins (`(Plugin | Plugin[])[]`). From Vite 5, it needs to be configured as a function that returns an array of plugins (`() => (Plugin | Plugin[])[]`). This change is required so parallel worker builds run more consistently and predictably.

### Allow path containing `.` to fallback to index.html

In Vite 4, accessing a path in dev containing `.` did not fallback to index.html even if `appType` is set to `'spa'` (default). From Vite 5, it will fallback to index.html.
In Vite 4, accessing a path in dev containing `.` did not fallback to index.html even if [`appType`](/config/shared-options.md#apptype) is set to `'spa'` (default). From Vite 5, it will fallback to index.html.

Note that the browser will no longer show a 404 error message in the console if you point the image path to a non-existent file (e.g. `<img src="./file-does-not-exist.png">`).

Expand All @@ -128,7 +128,7 @@ In Vite 4, the dev and preview servers serve HTML based on its directory structu

### Manifest files are now generated in `.vite` directory by default

In Vite 4, the manifest files (`build.manifest`, `build.ssrManifest`) was generated in the root of `build.outDir` by default. From Vite 5, those will be generated in the `.vite` directory in the `build.outDir` by default.
In Vite 4, the manifest files ([`build.manifest`](/config/build-options.md#build-manifest), [`build.ssrManifest`](/config/build-options.md#build-ssrmanifest)) was generated in the root of [`build.outDir`](/config/build-options.md#build-outdir) by default. From Vite 5, those will be generated in the `.vite` directory in the `build.outDir` by default.

### CLI shortcuts require an additional `Enter` press

Expand All @@ -138,7 +138,7 @@ This change prevents Vite from swallowing and controlling OS-specific shortcuts,

### Update `experimentalDecorators` and `useDefineForClassFields` TypeScript behaviour

Vite 5 uses esbuild 0.19 and removes the compatibility layer for esbuild 0.18, which changes how `experimentalDecorators` and `useDefineForClassFields` are handled.
Vite 5 uses esbuild 0.19 and removes the compatibility layer for esbuild 0.18, which changes how [`experimentalDecorators`](https://www.typescriptlang.org/tsconfig#experimentalDecorators) and [`useDefineForClassFields`](https://www.typescriptlang.org/tsconfig#useDefineForClassFields) are handled.

- **`experimentalDecorators` is not enabled by default**

Expand Down Expand Up @@ -217,7 +217,7 @@ Also there are other breaking changes which only affect few users.
- [[#14723] fix(resolve)!: remove special .mjs handling](https://github.com/vitejs/vite/pull/14723)
- In the past, when a library `"exports"` field maps to an `.mjs` file, Vite will still try to match the `"browser"` and `"module"` fields to fix compatibility with certain libraries. This behavior is now removed to align with the exports resolution algorithm.
- [[#14733] feat(resolve)!: remove `resolve.browserField`](https://github.com/vitejs/vite/pull/14733)
- `resolve.browserField` has been deprecated since Vite 3 in favour of an updated default of `['browser', 'module', 'jsnext:main', 'jsnext']` for `resolve.mainFields`.
- `resolve.browserField` has been deprecated since Vite 3 in favour of an updated default of `['browser', 'module', 'jsnext:main', 'jsnext']` for [`resolve.mainFields`](/config/shared-options.md#resolve-mainfields).

## Migration from v3

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
"playwright-chromium": "^1.39.0",
"prettier": "3.0.3",
"rimraf": "^5.0.5",
"rollup": "^4.1.4",
"rollup": "^4.2.0",
"simple-git-hooks": "^2.9.0",
"tslib": "^2.6.2",
"tsx": "^3.14.0",
Expand Down
14 changes: 14 additions & 0 deletions packages/vite/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
## 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)
* fix(deps): update all non-major dependencies (#14729) ([d5d96e7](https://github.com/vitejs/vite/commit/d5d96e7)), closes [#14729](https://github.com/vitejs/vite/issues/14729)
* fix(worker): force rollup to build workerImportMetaUrl under watch mode (#14712) ([8db40ee](https://github.com/vitejs/vite/commit/8db40ee)), closes [#14712](https://github.com/vitejs/vite/issues/14712)
* fix(html)!: align html serving between dev and preview (#14756) ([4f71ae8](https://github.com/vitejs/vite/commit/4f71ae8)), closes [#14756](https://github.com/vitejs/vite/issues/14756)
* refactor!: remove non boolean middleware mode (#14792) ([deb5515](https://github.com/vitejs/vite/commit/deb5515)), closes [#14792](https://github.com/vitejs/vite/issues/14792)
* refactor(esbuild)!: remove esbuild 0.17 -> 0.18 compat (#14804) ([7234021](https://github.com/vitejs/vite/commit/7234021)), closes [#14804](https://github.com/vitejs/vite/issues/14804)
* chore: update license (#14790) ([ac5d8a7](https://github.com/vitejs/vite/commit/ac5d8a7)), closes [#14790](https://github.com/vitejs/vite/issues/14790)
* chore(shortcuts): resolve generic type error (#14802) ([a090742](https://github.com/vitejs/vite/commit/a090742)), closes [#14802](https://github.com/vitejs/vite/issues/14802)
* feat: add a runtime warning for the old object type transformIndexHtml hook (#14791) ([17fb5ee](https://github.com/vitejs/vite/commit/17fb5ee)), closes [#14791](https://github.com/vitejs/vite/issues/14791)



## 5.0.0-beta.13 (2023-10-27)

* fix: skip watchPackageDataPlugin for worker builds (#14762) ([9babef5](https://github.com/vitejs/vite/commit/9babef5)), closes [#14762](https://github.com/vitejs/vite/issues/14762)
Expand Down
4 changes: 2 additions & 2 deletions 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.13",
"version": "5.0.0-beta.14",
"type": "module",
"license": "MIT",
"author": "Evan You",
Expand Down Expand Up @@ -76,7 +76,7 @@
"dependencies": {
"esbuild": "^0.19.3",
"postcss": "^8.4.31",
"rollup": "^4.1.4"
"rollup": "^4.2.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
Expand Down
10 changes: 10 additions & 0 deletions packages/vite/src/node/__tests__/plugins/define.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ describe('definePlugin', () => {
)
})

test('should not replace if not defined', async () => {
const transform = await createDefinePluginTransform({
__APP_VERSION__: JSON.stringify('1.0'),
})
expect(await transform('const version = "1.0";')).toBe(undefined)
expect(await transform('const version = import.meta.SOMETHING')).toBe(
undefined,
)
})

test('replaces import.meta.env.SSR with false', async () => {
const transform = await createDefinePluginTransform()
expect(await transform('const isSSR = import.meta.env.SSR;')).toBe(
Expand Down
17 changes: 1 addition & 16 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ export interface UserConfig {
*/
format?: 'es' | 'iife'
/**
* Vite plugins that apply to worker bundle. The plugins retured by this function
* Vite plugins that apply to worker bundle. The plugins returned by this function
* should be new instances every time it is called, because they are used for each
* rollup worker bundling process.
*/
Expand Down Expand Up @@ -483,21 +483,6 @@ export async function resolveConfig(
customLogger: config.customLogger,
})

let foundDiscouragedVariableName
if (
(foundDiscouragedVariableName = Object.keys(config.define ?? {}).find((k) =>
['process', 'global'].includes(k),
))
) {
logger.warn(
colors.yellow(
`Replacing ${colors.bold(
foundDiscouragedVariableName,
)} using the define option is discouraged. See https://vitejs.dev/config/shared-options.html#define for more details.`,
),
)
}

// resolve root
const resolvedRoot = normalizePath(
config.root ? path.resolve(config.root) : process.cwd(),
Expand Down
22 changes: 10 additions & 12 deletions packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,18 +83,16 @@ export function definePlugin(config: ResolvedConfig): Plugin {
})
}

const defineKeys = Object.keys(define)
const pattern = defineKeys.length
? new RegExp(
// Mustn't be preceded by a char that can be part of an identifier
// or a '.' that isn't part of a spread operator
'(?<![\\p{L}\\p{N}_$]|(?<!\\.\\.)\\.)(' +
defineKeys.map(escapeRegex).join('|') +
// Mustn't be followed by a char that can be part of an identifier
// or an assignment (but allow equality operators)
')(?:(?<=\\.)|(?![\\p{L}\\p{N}_$]|\\s*?=[^=]))',
'gu',
)
// 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')
}
if (Object.keys(importMetaKeys).length) {
patternKeys.push('import.meta.env', 'import.meta.hot')
}
const pattern = patternKeys.length
? new RegExp(patternKeys.map(escapeRegex).join('|'))
: null

return [define, pattern] as const
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
},

shouldTransformCachedModule({ id }) {
if (isBuild && isWorkerQueryId(id) && config.build.watch) {
if (isBuild && config.build.watch && isWorkerQueryId(id)) {
return true
}
},
Expand Down
24 changes: 18 additions & 6 deletions packages/vite/src/node/plugins/workerImportMetaUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,17 @@ function getWorkerType(raw: string, clean: string, i: number): WorkerType {
return 'classic'
}

function isIncludeWorkerImportMetaUrl(code: string): boolean {
if (
(code.includes('new Worker') || code.includes('new SharedWorker')) &&
code.includes('new URL') &&
code.includes(`import.meta.url`)
) {
return true
}
return false
}

export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
const isBuild = config.command === 'build'
let workerResolver: ResolveFn
Expand All @@ -113,14 +124,15 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
return {
name: 'vite:worker-import-meta-url',

shouldTransformCachedModule({ code }) {
if (isBuild && config.build.watch && isIncludeWorkerImportMetaUrl(code)) {
return true
}
},

async transform(code, id, options) {
const ssr = options?.ssr === true
if (
!options?.ssr &&
(code.includes('new Worker') || code.includes('new SharedWorker')) &&
code.includes('new URL') &&
code.includes(`import.meta.url`)
) {
if (!options?.ssr && isIncludeWorkerImportMetaUrl(code)) {
const query = parseRequest(id)
let s: MagicString | undefined
const cleanString = stripLiteral(code)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/transformRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ async function handleModuleSoftInvalidation(

if (ssr ? mod.ssrTransformResult : mod.transformResult) {
throw new Error(
`Internal server error: Soft-invalidated module "${mod.url}" should not have existing tranform result`,
`Internal server error: Soft-invalidated module "${mod.url}" should not have existing transform result`,
)
}

Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/ssr/ssrTransform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type {
import { extract_names as extractNames } from 'periscopic'
import { walk as eswalk } from 'estree-walker'
import type { RawSourceMap } from '@ampproject/remapping'
import { parseAst as rollupParseAst } from 'rollup/parseAst'
import { parseAstAsync as rollupParseAstAsync } from 'rollup/parseAst'
import type { TransformResult } from '../server/transformRequest'
import { combineSourcemaps } from '../utils'
import { isJSONRequest } from '../plugins/json'
Expand Down Expand Up @@ -75,7 +75,7 @@ async function ssrTransformScript(

let ast: any
try {
ast = rollupParseAst(code)
ast = await rollupParseAstAsync(code)
} catch (err) {
if (!err.loc || !err.loc.line) throw err
const line = err.loc.line
Expand Down
Loading

0 comments on commit 8477e1a

Please sign in to comment.