Skip to content

Commit

Permalink
Merge branch 'main' into define-quick-check
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy committed Oct 31, 2023
2 parents 2b7df8a + 2124264 commit 45031ee
Show file tree
Hide file tree
Showing 39 changed files with 400 additions and 242 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ jobs:

- name: Set node version to ${{ matrix.node_version }}
if: steps.changed-files.outputs.only_changed != 'true'
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node_version }}
cache: "pnpm"
Expand Down Expand Up @@ -137,7 +137,7 @@ jobs:
uses: pnpm/[email protected]

- name: Set node version to 18
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: 18
cache: "pnpm"
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:
uses: pnpm/[email protected]

- name: Set node version to 18
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: 18
registry-url: https://registry.npmjs.org/
Expand Down
25 changes: 25 additions & 0 deletions docs/guide/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ Some configuration fields under `compilerOptions` in `tsconfig.json` require spe

#### `isolatedModules`

- [TypeScript documentation](https://www.typescriptlang.org/tsconfig#isolatedModules)

Should be set to `true`.

It is because `esbuild` only performs transpilation without type information, it doesn't support certain features like const enum and implicit type-only imports.
Expand All @@ -67,8 +69,12 @@ However, some libraries (e.g. [`vue`](https:/vuejs/core/issues/1228)

#### `useDefineForClassFields`

- [TypeScript documentation](https://www.typescriptlang.org/tsconfig#useDefineForClassFields)

Starting from Vite 2.5.0, the default value will be `true` if the TypeScript target is `ESNext` or `ES2022` or newer. It is consistent with the [behavior of `tsc` 4.3.2 and later](https:/microsoft/TypeScript/pull/42663). It is also the standard ECMAScript runtime behavior.

Other TypeScript targets will default to `false`.

But it may be counter-intuitive for those coming from other programming languages or older versions of TypeScript.
You can read more about the transition in the [TypeScript 3.7 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier).

Expand All @@ -78,13 +84,32 @@ Most libraries expect `"useDefineForClassFields": true`, such as [MobX](https://

But a few libraries haven't transitioned to this new default yet, including [`lit-element`](https:/lit/lit-element/issues/1030). Please explicitly set `useDefineForClassFields` to `false` in these cases.

#### `target`

- [TypeScript documentation](https://www.typescriptlang.org/tsconfig#target)

Vite does not transpile TypeScript with the configured `target` value by default, following the same behaviour as `esbuild`.

The [`esbuild.target`](/config/shared-options.html#esbuild) option can be used instead, which defaults to `esnext` for minimal transpilation. In builds, the [`build.target`](/config/build-options.html#build-target) option takes higher priority and can also be set if needed.

::: warning `useDefineForClassFields`
If `target` is not `ESNext` or `ES2022` or newer, or if there's no `tsconfig.json` file, `useDefineForClassFields` will default to `false` which can be problematic with the default `esbuild.target` value of `esnext`. It may transpile to [static initialization blocks](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks#browser_compatibility) which may not be supported in your browser.

As such, it is recommended to set `target` to `ESNext` or `ES2022` or newer, or set `useDefineForClassFields` to `true` explicitly when configuring `tsconfig.json`.
:::

#### Other Compiler Options Affecting the Build Result

- [`extends`](https://www.typescriptlang.org/tsconfig#extends)
- [`importsNotUsedAsValues`](https://www.typescriptlang.org/tsconfig#importsNotUsedAsValues)
- [`preserveValueImports`](https://www.typescriptlang.org/tsconfig#preserveValueImports)
- [`verbatimModuleSyntax`](https://www.typescriptlang.org/tsconfig#verbatimModuleSyntax)
- [`jsx`](https://www.typescriptlang.org/tsconfig#jsx)
- [`jsxFactory`](https://www.typescriptlang.org/tsconfig#jsxFactory)
- [`jsxFragmentFactory`](https://www.typescriptlang.org/tsconfig#jsxFragmentFactory)
- [`jsxImportSource`](https://www.typescriptlang.org/tsconfig#jsxImportSource)
- [`experimentalDecorators`](https://www.typescriptlang.org/tsconfig#experimentalDecorators)
- [`alwaysStrict`](https://www.typescriptlang.org/tsconfig#alwaysStrict)

If migrating your codebase to `"isolatedModules": true` is an insurmountable effort, you may be able to get around it with a third-party plugin such as [rollup-plugin-friendly-type-imports](https://www.npmjs.com/package/rollup-plugin-friendly-type-imports). However, this approach is not officially supported by Vite.

Expand Down
51 changes: 48 additions & 3 deletions docs/guide/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,29 @@ In Vite 4, `worker.plugins` accepted an array of plugins (`(Plugin | Plugin[])[]

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

In Vite 4, accessing a path 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` is set to `'spa'` (default). From Vite 5, it will fallback to index.html.

Note that the browser will no longer show the 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">`).
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">`).

### Align dev and preview HTML serving behaviour

In Vite 4, the dev and preview servers serve HTML based on its directory structure and trailing slash differently. This causes inconsistencies when testing your built app. Vite 5 refactors into a single behaviour like below, given the following file structure:

```
├── index.html
├── file.html
└── dir
└── index.html
```

| Request | Before (dev) | Before (preview) | After (dev & preview) |
| ----------------- | ---------------------------- | ----------------- | ---------------------------- |
| `/dir/index.html` | `/dir/index.html` | `/dir/index.html` | `/dir/index.html` |
| `/dir` | `/index.html` (SPA fallback) | `/dir/index.html` | `/dir.html` (SPA fallback) |
| `/dir/` | `/dir/index.html` | `/dir/index.html` | `/dir/index.html` |
| `/file.html` | `/file.html` | `/file.html` | `/file.html` |
| `/file` | `/index.html` (SPA fallback) | `/file.html` | `/file.html` |
| `/file/` | `/index.html` (SPA fallback) | `/file.html` | `/index.html` (SPA fallback) |

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

Expand All @@ -117,6 +136,31 @@ CLI shortcuts, like `r` to restart the dev server, now require an additional `En

This change prevents Vite from swallowing and controlling OS-specific shortcuts, allowing better compatibility when combining the Vite dev server with other processes, and avoids the [previous caveats](https:/vitejs/vite/pull/14342).

### 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.

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

You need to set `compilerOptions.experimentalDecorators` to `true` in `tsconfig.json` to use decorators.

- **`useDefineForClassFields` defaults depend on the TypeScript `target` value**

If `target` is not `ESNext` or `ES2022` or newer, or if there's no `tsconfig.json` file, `useDefineForClassFields` will default to `false` which can be problematic with the default `esbuild.target` value of `esnext`. It may transpile to [static initialization blocks](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks#browser_compatibility) which may not be supported in your browser.

As such, it is recommended to set `target` to `ESNext` or `ES2022` or newer, or set `useDefineForClassFields` to `true` explicitly when configuring `tsconfig.json`.

```jsonc
{
"compilerOptions": {
// Set true if you use decorators
"experimentalDecorators": true,
// Set true if you see parsing errors in your browser
"useDefineForClassFields": true
}
}
```

### Remove `--https` flag and `https: true`

`--https` flag sets `https: true`. This config was meant to be used together with the automatic https certification generation feature which [was dropped in Vite 3](https://v3.vitejs.dev/guide/migration.html#automatic-https-certificate-generation). This config no longer makes sense as it will make Vite start a HTTPS server without a certificate.
Expand Down Expand Up @@ -150,6 +194,7 @@ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))
- Default exports of CSS files (e.g `import style from './foo.css'`): Use the `?inline` query instead
- `import.meta.globEager`: Use `import.meta.glob('*', { eager: true })` instead
- `ssr.format: 'cjs'` and `legacy.buildSsrCjsExternalHeuristics` ([#13816](https:/vitejs/vite/discussions/13816))
- `server.middlewareMode: 'ssr'` and `server.middlewareMode: 'html'`: Use [`appType`](/config/shared-options.md#apptype) + [`server.middlewareMode: true`](/config/server-options.md#server-middlewaremode) instead ([#8452](https:/vitejs/vite/pull/8452))

## Advanced

Expand Down
2 changes: 1 addition & 1 deletion packages/create-vite/template-react-ts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"@vitejs/plugin-react": "^4.1.0",
"eslint": "^8.52.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"eslint-plugin-react-refresh": "^0.4.4",
"typescript": "^5.2.2",
"vite": "^5.0.0-beta.13"
}
Expand Down
2 changes: 1 addition & 1 deletion packages/create-vite/template-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"eslint": "^8.52.0",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"eslint-plugin-react-refresh": "^0.4.4",
"vite": "^5.0.0-beta.13"
}
}
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:/vitejs/vite/commit/f36fcd2)), closes [#14786](https:/vitejs/vite/issues/14786)
* fix(deps): update all non-major dependencies (#14729) ([d5d96e7](https:/vitejs/vite/commit/d5d96e7)), closes [#14729](https:/vitejs/vite/issues/14729)
* fix(worker): force rollup to build workerImportMetaUrl under watch mode (#14712) ([8db40ee](https:/vitejs/vite/commit/8db40ee)), closes [#14712](https:/vitejs/vite/issues/14712)
* fix(html)!: align html serving between dev and preview (#14756) ([4f71ae8](https:/vitejs/vite/commit/4f71ae8)), closes [#14756](https:/vitejs/vite/issues/14756)
* refactor!: remove non boolean middleware mode (#14792) ([deb5515](https:/vitejs/vite/commit/deb5515)), closes [#14792](https:/vitejs/vite/issues/14792)
* refactor(esbuild)!: remove esbuild 0.17 -> 0.18 compat (#14804) ([7234021](https:/vitejs/vite/commit/7234021)), closes [#14804](https:/vitejs/vite/issues/14804)
* chore: update license (#14790) ([ac5d8a7](https:/vitejs/vite/commit/ac5d8a7)), closes [#14790](https:/vitejs/vite/issues/14790)
* chore(shortcuts): resolve generic type error (#14802) ([a090742](https:/vitejs/vite/commit/a090742)), closes [#14802](https:/vitejs/vite/issues/14802)
* feat: add a runtime warning for the old object type transformIndexHtml hook (#14791) ([17fb5ee](https:/vitejs/vite/commit/17fb5ee)), closes [#14791](https:/vitejs/vite/issues/14791)



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

* fix: skip watchPackageDataPlugin for worker builds (#14762) ([9babef5](https:/vitejs/vite/commit/9babef5)), closes [#14762](https:/vitejs/vite/issues/14762)
Expand Down
51 changes: 22 additions & 29 deletions packages/vite/LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,28 @@ License: MIT
By: LarsDenBakker
Repository: rollup/plugins

> The MIT License (MIT)
>
> Copyright (c) 2019 RollupJS Plugin Contributors (https:/rollup/plugins/graphs/contributors)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.
---------------------------------------

## @rollup/pluginutils
Expand Down Expand Up @@ -889,35 +911,6 @@ Repository: senchalabs/connect
---------------------------------------

## connect-history-api-fallback
License: MIT
By: Ben Ripkens, Craig Myles
Repository: http:/bripkens/connect-history-api-fallback.git

> The MIT License
>
> Copyright (c) 2022 Ben Blackmore and contributors
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.
---------------------------------------

## convert-source-map
License: MIT
By: Thorsten Lorenz
Expand Down
3 changes: 1 addition & 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 @@ -98,7 +98,6 @@
"cac": "^6.7.14",
"chokidar": "^3.5.3",
"connect": "^3.7.0",
"connect-history-api-fallback": "^2.0.0",
"convert-source-map": "^2.0.0",
"cors": "^2.8.5",
"cross-spawn": "^7.0.3",
Expand Down
9 changes: 9 additions & 0 deletions packages/vite/src/node/__tests__/plugins/define.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,13 @@ describe('definePlugin', () => {
'const hot = import.meta.hot;\n',
)
})

test('preserve import.meta.env.UNKNOWN with override', async () => {
const transform = await createDefinePluginTransform({
'import.meta.env.UNKNOWN': 'import.meta.env.UNKNOWN',
})
expect(await transform('const foo = import.meta.env.UNKNOWN;')).toBe(
'const foo = import.meta.env.UNKNOWN;\n',
)
})
})
15 changes: 0 additions & 15 deletions packages/vite/src/node/__tests__/plugins/esbuild.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,21 +383,6 @@ describe('transformWithEsbuild', () => {
const actual = await transformClassCode('es2022', {})
expect(actual).toBe(defineForClassFieldsFalseTransformedCode)
})

test('useDefineForClassFields: false and static property should not be transpile to static block', async () => {
const result = await transformWithEsbuild(
`
class foo {
static bar = 'bar'
}
`,
'bar.ts',
{
target: 'esnext',
},
)
expect(result?.code).not.toContain('static {')
})
})
})

Expand Down
24 changes: 3 additions & 21 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -670,8 +670,6 @@ export async function resolveConfig(
const server = resolveServerOptions(resolvedRoot, config.server, logger)
const ssr = resolveSSROptions(config.ssr, resolveOptions.preserveSymlinks)

const middlewareMode = config?.server?.middlewareMode

const optimizeDeps = config.optimizeDeps || {}

const BASE_URL = resolvedBase
Expand Down Expand Up @@ -796,7 +794,7 @@ export async function resolveConfig(
},
},
worker: resolvedWorkerOptions,
appType: config.appType ?? (middlewareMode === 'ssr' ? 'custom' : 'spa'),
appType: config.appType ?? 'spa',
experimental: {
importGlobRestoreExtension: false,
hmrPartialAccept: false,
Expand Down Expand Up @@ -824,24 +822,6 @@ export async function resolveConfig(
.map((hook) => hook(resolved)),
)

// validate config

if (middlewareMode === 'ssr') {
logger.warn(
colors.yellow(
`Setting server.middlewareMode to 'ssr' is deprecated, set server.middlewareMode to \`true\`${
config.appType === 'custom' ? '' : ` and appType to 'custom'`
} instead`,
),
)
} else if (middlewareMode === 'html') {
logger.warn(
colors.yellow(
`Setting server.middlewareMode to 'html' is deprecated, set server.middlewareMode to \`true\` instead`,
),
)
}

debug?.(`using resolved config: %O`, {
...resolved,
plugins: resolved.plugins.map((p) => p.name),
Expand All @@ -851,6 +831,8 @@ export async function resolveConfig(
},
})

// validate config

if (config.build?.terserOptions && config.build.minify !== 'terser') {
logger.warn(
colors.yellow(
Expand Down
12 changes: 3 additions & 9 deletions packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
import { transformWithEsbuild } from '../plugins/esbuild'
import { ESBUILD_MODULES_TARGET } from '../constants'
import { esbuildCjsExternalPlugin, esbuildDepPlugin } from './esbuildDepPlugin'
import { resolveTsconfigRaw, scanImports } from './scan'
import { scanImports } from './scan'
import { createOptimizeDepsIncludeResolver, expandGlobIds } from './resolve'
export {
initDepsOptimizer,
Expand Down Expand Up @@ -730,12 +730,8 @@ async function prepareEsbuildOptimizerRun(

const optimizeDeps = getDepOptimizationConfig(config, ssr)

const {
plugins: pluginsFromConfig = [],
tsconfig,
tsconfigRaw,
...esbuildOptions
} = optimizeDeps?.esbuildOptions ?? {}
const { plugins: pluginsFromConfig = [], ...esbuildOptions } =
optimizeDeps?.esbuildOptions ?? {}

await Promise.all(
Object.keys(depsInfo).map(async (id) => {
Expand Down Expand Up @@ -826,8 +822,6 @@ async function prepareEsbuildOptimizerRun(
metafile: true,
plugins,
charset: 'utf8',
tsconfig,
tsconfigRaw: resolveTsconfigRaw(tsconfig, tsconfigRaw),
...esbuildOptions,
supported: {
'dynamic-import': true,
Expand Down
Loading

0 comments on commit 45031ee

Please sign in to comment.