From 9707f0e9e37e64eeb07fcd96d3e4fee6d19cc3a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Mon, 28 Mar 2022 21:41:00 +0900 Subject: [PATCH 01/93] test: add js sourcemap tests (#7494) --- .../css-sourcemap/__tests__/serve.spec.ts | 23 ++---- .../playground/css-sourcemap/package.json | 1 - .../js-sourcemap/__tests__/build.spec.ts | 13 ++++ .../js-sourcemap/__tests__/serve.spec.ts | 44 +++++++++++ packages/playground/js-sourcemap/bar.ts | 1 + packages/playground/js-sourcemap/foo.js | 1 + packages/playground/js-sourcemap/index.html | 6 ++ packages/playground/js-sourcemap/package.json | 11 +++ .../playground/js-sourcemap/vite.config.js | 8 ++ packages/playground/package.json | 1 + packages/playground/testUtils.ts | 17 +++- packages/playground/vue-sourcemap/Js.vue | 11 +++ packages/playground/vue-sourcemap/Main.vue | 4 + packages/playground/vue-sourcemap/Ts.vue | 11 +++ .../vue-sourcemap/__tests__/serve.spec.ts | 78 +++++++++++++++---- .../playground/vue-sourcemap/package.json | 1 - pnpm-lock.yaml | 9 ++- 17 files changed, 199 insertions(+), 41 deletions(-) create mode 100644 packages/playground/js-sourcemap/__tests__/build.spec.ts create mode 100644 packages/playground/js-sourcemap/__tests__/serve.spec.ts create mode 100644 packages/playground/js-sourcemap/bar.ts create mode 100644 packages/playground/js-sourcemap/foo.js create mode 100644 packages/playground/js-sourcemap/index.html create mode 100644 packages/playground/js-sourcemap/package.json create mode 100644 packages/playground/js-sourcemap/vite.config.js create mode 100644 packages/playground/vue-sourcemap/Js.vue create mode 100644 packages/playground/vue-sourcemap/Ts.vue diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/packages/playground/css-sourcemap/__tests__/serve.spec.ts index 0c6696b0dff7a2..11e33a78af8424 100644 --- a/packages/playground/css-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/css-sourcemap/__tests__/serve.spec.ts @@ -1,11 +1,11 @@ -import { fromComment } from 'convert-source-map' import { URL } from 'url' -import { normalizePath } from 'vite' -import { isBuild, testDir } from 'testUtils' +import { + extractSourcemap, + formatSourcemapForSnapshot, + isBuild +} from 'testUtils' if (!isBuild) { - const root = normalizePath(testDir) - const getStyleTagContentIncluding = async (content: string) => { const styles = await page.$$('style') for (const style of styles) { @@ -17,19 +17,6 @@ if (!isBuild) { throw new Error('Not found') } - const extractSourcemap = (content: string) => { - const lines = content.trim().split('\n') - return fromComment(lines[lines.length - 1]).toObject() - } - - const formatSourcemapForSnapshot = (map: any) => { - const m = { ...map } - delete m.file - delete m.names - m.sources = m.sources.map((source) => source.replace(root, '/root')) - return m - } - test('inline css', async () => { const css = await getStyleTagContentIncluding('.inline ') const map = extractSourcemap(css) diff --git a/packages/playground/css-sourcemap/package.json b/packages/playground/css-sourcemap/package.json index c29f18d4dee0d7..c7e9e61372cefa 100644 --- a/packages/playground/css-sourcemap/package.json +++ b/packages/playground/css-sourcemap/package.json @@ -9,7 +9,6 @@ "preview": "vite preview" }, "devDependencies": { - "convert-source-map": "^1.8.0", "less": "^4.1.2", "magic-string": "^0.25.7", "sass": "^1.43.4", diff --git a/packages/playground/js-sourcemap/__tests__/build.spec.ts b/packages/playground/js-sourcemap/__tests__/build.spec.ts new file mode 100644 index 00000000000000..e36c1f52d2c1f8 --- /dev/null +++ b/packages/playground/js-sourcemap/__tests__/build.spec.ts @@ -0,0 +1,13 @@ +import { isBuild } from 'testUtils' + +if (isBuild) { + test('should not output sourcemap warning (#4939)', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch('Sourcemap is likely to be incorrect') + }) + }) +} else { + test('this file only includes test for build', () => { + expect(true).toBe(true) + }) +} diff --git a/packages/playground/js-sourcemap/__tests__/serve.spec.ts b/packages/playground/js-sourcemap/__tests__/serve.spec.ts new file mode 100644 index 00000000000000..a1ffdddc37ecd5 --- /dev/null +++ b/packages/playground/js-sourcemap/__tests__/serve.spec.ts @@ -0,0 +1,44 @@ +import { URL } from 'url' +import { + extractSourcemap, + formatSourcemapForSnapshot, + isBuild +} from 'testUtils' + +if (!isBuild) { + test('js', async () => { + const res = await page.request.get(new URL('./foo.js', page.url()).href) + const js = await res.text() + const lines = js.split('\n') + expect(lines[lines.length - 1].includes('//')).toBe(false) // expect no sourcemap + }) + + test('ts', async () => { + const res = await page.request.get(new URL('./bar.ts', page.url()).href) + const js = await res.text() + const map = extractSourcemap(js) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AAAO,aAAM,MAAM;", + "sources": Array [ + "/root/bar.ts", + ], + "sourcesContent": Array [ + "export const bar = 'bar' + ", + ], + "version": 3, + } + `) + }) + + test('should not output missing source file warning', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch(/Sourcemap for .+ points to missing source files/) + }) + }) +} else { + test('this file only includes test for serve', () => { + expect(true).toBe(true) + }) +} diff --git a/packages/playground/js-sourcemap/bar.ts b/packages/playground/js-sourcemap/bar.ts new file mode 100644 index 00000000000000..1fc11814f22e80 --- /dev/null +++ b/packages/playground/js-sourcemap/bar.ts @@ -0,0 +1 @@ +export const bar = 'bar' diff --git a/packages/playground/js-sourcemap/foo.js b/packages/playground/js-sourcemap/foo.js new file mode 100644 index 00000000000000..cb356468240d50 --- /dev/null +++ b/packages/playground/js-sourcemap/foo.js @@ -0,0 +1 @@ +export const foo = 'foo' diff --git a/packages/playground/js-sourcemap/index.html b/packages/playground/js-sourcemap/index.html new file mode 100644 index 00000000000000..025b161011a3fa --- /dev/null +++ b/packages/playground/js-sourcemap/index.html @@ -0,0 +1,6 @@ +
+

JS Sourcemap

+
+ + + diff --git a/packages/playground/js-sourcemap/package.json b/packages/playground/js-sourcemap/package.json new file mode 100644 index 00000000000000..e5a97aea80830f --- /dev/null +++ b/packages/playground/js-sourcemap/package.json @@ -0,0 +1,11 @@ +{ + "name": "test-js-sourcemap", + "private": true, + "version": "0.0.0", + "scripts": { + "dev": "vite", + "build": "vite build", + "debug": "node --inspect-brk ../../vite/bin/vite", + "preview": "vite preview" + } +} diff --git a/packages/playground/js-sourcemap/vite.config.js b/packages/playground/js-sourcemap/vite.config.js new file mode 100644 index 00000000000000..bc9d1748cab964 --- /dev/null +++ b/packages/playground/js-sourcemap/vite.config.js @@ -0,0 +1,8 @@ +/** + * @type {import('vite').UserConfig} + */ +module.exports = { + build: { + sourcemap: true + } +} diff --git a/packages/playground/package.json b/packages/playground/package.json index 58ef368099e82f..75b1d15d299319 100644 --- a/packages/playground/package.json +++ b/packages/playground/package.json @@ -3,6 +3,7 @@ "private": true, "version": "1.0.0", "devDependencies": { + "convert-source-map": "^1.8.0", "css-color-names": "^1.0.1" } } diff --git a/packages/playground/testUtils.ts b/packages/playground/testUtils.ts index 0c8186d4ed121d..7d21625dacf874 100644 --- a/packages/playground/testUtils.ts +++ b/packages/playground/testUtils.ts @@ -6,7 +6,8 @@ import fs from 'fs' import path from 'path' import colors from 'css-color-names' import type { ElementHandle } from 'playwright-chromium' -import type { Manifest } from 'vite' +import { Manifest, normalizePath } from 'vite' +import { fromComment } from 'convert-source-map' export function slash(p: string): string { return p.replace(/\\/g, '/') @@ -138,3 +139,17 @@ export async function untilUpdated( * Send the rebuild complete message in build watch */ export { notifyRebuildComplete } from '../../scripts/jestPerTestSetup' + +export const extractSourcemap = (content: string) => { + const lines = content.trim().split('\n') + return fromComment(lines[lines.length - 1]).toObject() +} + +export const formatSourcemapForSnapshot = (map: any) => { + const root = normalizePath(testDir) + const m = { ...map } + delete m.file + delete m.names + m.sources = m.sources.map((source) => source.replace(root, '/root')) + return m +} diff --git a/packages/playground/vue-sourcemap/Js.vue b/packages/playground/vue-sourcemap/Js.vue new file mode 100644 index 00000000000000..3a5577099f67d3 --- /dev/null +++ b/packages/playground/vue-sourcemap/Js.vue @@ -0,0 +1,11 @@ + + + + + diff --git a/packages/playground/vue-sourcemap/Main.vue b/packages/playground/vue-sourcemap/Main.vue index 04ddf50071ccb3..b9b03596f5aea5 100644 --- a/packages/playground/vue-sourcemap/Main.vue +++ b/packages/playground/vue-sourcemap/Main.vue @@ -1,5 +1,7 @@ + + diff --git a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts b/packages/playground/vue-sourcemap/__tests__/serve.spec.ts index 193b0afb9ba73f..08b4c04face111 100644 --- a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/vue-sourcemap/__tests__/serve.spec.ts @@ -1,10 +1,11 @@ -import { fromComment } from 'convert-source-map' -import { normalizePath } from 'vite' -import { isBuild, testDir } from 'testUtils' +import { + extractSourcemap, + formatSourcemapForSnapshot, + isBuild +} from 'testUtils' +import { URL } from 'url' if (!isBuild) { - const root = normalizePath(testDir) - const getStyleTagContentIncluding = async (content: string) => { const styles = await page.$$('style') for (const style of styles) { @@ -16,18 +17,63 @@ if (!isBuild) { throw new Error('Not found') } - const extractSourcemap = (content: string) => { - const lines = content.trim().split('\n') - return fromComment(lines[lines.length - 1]).toObject() - } + test('js', async () => { + const res = await page.request.get(new URL('./Js.vue', page.url()).href) + const js = await res.text() + const map = extractSourcemap(js) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AAKA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;AAGP;AACd,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;;;;;;;wBARlB,oBAAiB,WAAd,MAAU", + "sources": Array [ + "/root/Js.vue", + ], + "sourcesContent": Array [ + " - const formatSourcemapForSnapshot = (map: any) => { - const m = { ...map } - delete m.file - delete m.names - m.sources = m.sources.map((source) => source.replace(root, '/root')) - return m - } + + + + ", + ], + "version": 3, + } + `) + }) + + test('ts', async () => { + const res = await page.request.get(new URL('./Ts.vue', page.url()).href) + const js = await res.text() + const map = extractSourcemap(js) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": ";AAKA,QAAQ,IAAI,WAAW;;;;AAIvB,YAAQ,IAAI,UAAU;;;;;;;;uBARpB,oBAAiB,WAAd,MAAU", + "sources": Array [ + "/root/Ts.vue", + ], + "sourcesContent": Array [ + " + + + + + ", + ], + "version": 3, + } + `) + }) test('css', async () => { const css = await getStyleTagContentIncluding('.css ') diff --git a/packages/playground/vue-sourcemap/package.json b/packages/playground/vue-sourcemap/package.json index 5672b5e3d9d57d..286940b01efa58 100644 --- a/packages/playground/vue-sourcemap/package.json +++ b/packages/playground/vue-sourcemap/package.json @@ -10,7 +10,6 @@ }, "devDependencies": { "@vitejs/plugin-vue": "workspace:*", - "convert-source-map": "^1.8.0", "less": "^4.1.2", "sass": "^1.43.4" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a09304a6c8f50d..def6f1a526907f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -92,8 +92,10 @@ importers: packages/playground: specifiers: + convert-source-map: ^1.8.0 css-color-names: ^1.0.1 devDependencies: + convert-source-map: 1.8.0 css-color-names: 1.0.1 packages/playground/alias: @@ -152,13 +154,11 @@ importers: packages/playground/css-sourcemap: specifiers: - convert-source-map: ^1.8.0 less: ^4.1.2 magic-string: ^0.25.7 sass: ^1.43.4 stylus: ^0.55.0 devDependencies: - convert-source-map: 1.8.0 less: 4.1.2 magic-string: 0.25.7 sass: 1.45.1 @@ -223,6 +223,9 @@ importers: packages/playground/html: specifiers: {} + packages/playground/js-sourcemap: + specifiers: {} + packages/playground/json: specifiers: json-module: file:./json-module @@ -711,7 +714,6 @@ importers: packages/playground/vue-sourcemap: specifiers: '@vitejs/plugin-vue': workspace:* - convert-source-map: ^1.8.0 less: ^4.1.2 sass: ^1.43.4 vue: ^3.2.31 @@ -719,7 +721,6 @@ importers: vue: 3.2.31 devDependencies: '@vitejs/plugin-vue': link:../../plugin-vue - convert-source-map: 1.8.0 less: 4.1.2 sass: 1.45.1 From 01bc415289d747f2db048578ad23d1e995996301 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Wouts?= Date: Tue, 29 Mar 2022 02:14:31 +1100 Subject: [PATCH 02/93] fix: add workaround to fix build-temp-types on Netlify (#7495) --- package.json | 7 +++++++ pnpm-lock.yaml | 9 +++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 878fd5c7de506f..f6166c2985a30c 100644 --- a/package.json +++ b/package.json @@ -90,6 +90,13 @@ "overrides": { "vite": "workspace:*", "@vitejs/plugin-vue": "workspace:*" + }, + "packageExtensions": { + "postcss-load-config": { + "peerDependencies": { + "postcss": "*" + } + } } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index def6f1a526907f..b0574f04c53b86 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4,6 +4,8 @@ overrides: vite: workspace:* '@vitejs/plugin-vue': workspace:* +packageExtensionsChecksum: 696422bac84dd936748019990f84746e + importers: .: @@ -935,7 +937,7 @@ importers: periscopic: 2.0.3 picocolors: 1.0.0 postcss-import: 14.1.0_postcss@8.4.12 - postcss-load-config: 3.1.3_ts-node@10.4.0 + postcss-load-config: 3.1.3_postcss@8.4.12+ts-node@10.4.0 postcss-modules: 4.3.1_postcss@8.4.12 resolve.exports: 1.1.0 rollup-plugin-license: 2.6.1_rollup@2.62.0 @@ -7528,6 +7530,7 @@ packages: resolution: {integrity: sha512-ipM8Ds01ZUophjDTQYSVP70slFSYg3T0/zyfII5vzhN6V57YSxMgG5syXuwi5VtS8wSf3iL30v0uBdoIVx4Q0g==} engines: {node: '>= 10'} peerDependencies: + postcss: '*' ts-node: '>=9.0.0' peerDependenciesMeta: ts-node: @@ -7539,16 +7542,18 @@ packages: yaml: 1.10.2 dev: false - /postcss-load-config/3.1.3_ts-node@10.4.0: + /postcss-load-config/3.1.3_postcss@8.4.12+ts-node@10.4.0: resolution: {integrity: sha512-5EYgaM9auHGtO//ljHH+v/aC/TQ5LHXtL7bQajNAUBKUVKiYE8rYpFms7+V26D9FncaGe2zwCoPQsFKb5zF/Hw==} engines: {node: '>= 10'} peerDependencies: + postcss: '*' ts-node: '>=9.0.0' peerDependenciesMeta: ts-node: optional: true dependencies: lilconfig: 2.0.4 + postcss: 8.4.12 ts-node: 10.4.0_44ef5af6cbbc24239b4e70b5c7b0d7a6 yaml: 1.10.2 dev: true From 28b0660ee471828af0aa0bc29ca5b647fa51ef2e Mon Sep 17 00:00:00 2001 From: patak Date: Mon, 28 Mar 2022 17:18:45 +0200 Subject: [PATCH 03/93] fix: custom event payload type (#7498) --- packages/vite/types/customEvent.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vite/types/customEvent.d.ts b/packages/vite/types/customEvent.d.ts index aacf1554b0de75..af4db5d14fbe97 100644 --- a/packages/vite/types/customEvent.d.ts +++ b/packages/vite/types/customEvent.d.ts @@ -13,4 +13,4 @@ export interface CustomEventMap { } export type InferCustomEventPayload = - T extends keyof CustomEventMap ? CustomEventMap[T] : unknown + T extends keyof CustomEventMap ? CustomEventMap[T] : any From 4ffd82d2d4759bc3efa368bca54613aaa1f45acc Mon Sep 17 00:00:00 2001 From: patak-dev Date: Mon, 28 Mar 2022 20:38:19 +0200 Subject: [PATCH 04/93] release: v2.9.0-beta.10 --- packages/vite/CHANGELOG.md | 13 +++++++++++++ packages/vite/package.json | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/vite/CHANGELOG.md b/packages/vite/CHANGELOG.md index b79c75db3260f0..1a9b06abefcf66 100644 --- a/packages/vite/CHANGELOG.md +++ b/packages/vite/CHANGELOG.md @@ -1,3 +1,16 @@ +## 2.9.0-beta.10 (2022-03-28) + +* fix: Correctly process urls when they are rewritten to contain space (#7452) ([9ee2cf6](https://github.com/vitejs/vite/commit/9ee2cf6)), closes [#7452](https://github.com/vitejs/vite/issues/7452) +* fix: custom event payload type (#7498) ([28b0660](https://github.com/vitejs/vite/commit/28b0660)), closes [#7498](https://github.com/vitejs/vite/issues/7498) +* fix: handle relative path glob raw import, fix #7307 (#7371) ([7f8dc58](https://github.com/vitejs/vite/commit/7f8dc58)), closes [#7307](https://github.com/vitejs/vite/issues/7307) [#7371](https://github.com/vitejs/vite/issues/7371) +* fix: import.meta.url in worker (#7464) ([8ac4b12](https://github.com/vitejs/vite/commit/8ac4b12)), closes [#7464](https://github.com/vitejs/vite/issues/7464) +* fix: optimizeDeps.entries default ignore paths (#7469) ([4c95e99](https://github.com/vitejs/vite/commit/4c95e99)), closes [#7469](https://github.com/vitejs/vite/issues/7469) +* chore(deps): update all non-major dependencies (#7490) ([42c15f6](https://github.com/vitejs/vite/commit/42c15f6)), closes [#7490](https://github.com/vitejs/vite/issues/7490) +* feat(type): support typing for custom events (#7476) ([50a8765](https://github.com/vitejs/vite/commit/50a8765)), closes [#7476](https://github.com/vitejs/vite/issues/7476) +* refactor(types): share hot context type (#7475) ([64ddff0](https://github.com/vitejs/vite/commit/64ddff0)), closes [#7475](https://github.com/vitejs/vite/issues/7475) + + + ## 2.9.0-beta.9 (2022-03-26) * feat: support importing css with ?raw (#5796) ([fedb106](https://github.com/vitejs/vite/commit/fedb106)), closes [#5796](https://github.com/vitejs/vite/issues/5796) diff --git a/packages/vite/package.json b/packages/vite/package.json index f6c177b248289f..918b00aaa46912 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -1,6 +1,6 @@ { "name": "vite", - "version": "2.9.0-beta.9", + "version": "2.9.0-beta.10", "license": "MIT", "author": "Evan You", "description": "Native-ESM powered web dev build tool", From e3c7c7ace9da3d4c38e0ac49dd4b737cdd0c9f75 Mon Sep 17 00:00:00 2001 From: Johannes Maas Date: Tue, 29 Mar 2022 05:53:36 +0200 Subject: [PATCH 05/93] fix: build path error on Windows (#7383) --- packages/vite/src/node/plugins/html.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 30e65a36f83bbe..5f7dae623b0cb4 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -594,7 +594,6 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { } } - const shortEmitName = path.posix.relative(config.root, id) // no use assets plugin because it will emit file let match: RegExpExecArray | null let s: MagicString | undefined @@ -612,8 +611,9 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { if (s) { result = s.toString() } + const relativeUrlPath = path.posix.relative(config.root, id) result = await applyHtmlTransforms(result, postHooks, { - path: '/' + shortEmitName, + path: '/' + relativeUrlPath, filename: id, bundle, chunk @@ -628,6 +628,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { delete bundle[chunk.fileName] } + const shortEmitName = path.relative(config.root, id) this.emitFile({ type: 'asset', fileName: shortEmitName, From 93ae8e5a053f637ff291a76cb0755e2c42cb5d8c Mon Sep 17 00:00:00 2001 From: Lukas Date: Tue, 29 Mar 2022 09:05:30 +0200 Subject: [PATCH 06/93] fix: infer client port from page location (#7463) --- docs/config/index.md | 4 +--- packages/vite/src/client/client.ts | 13 +++++++------ .../vite/src/node/plugins/clientInjections.ts | 19 +++++++++---------- packages/vite/src/node/server/hmr.ts | 2 +- 4 files changed, 18 insertions(+), 20 deletions(-) diff --git a/docs/config/index.md b/docs/config/index.md index a8d8cb36079f0a..f9a1a81dc77dbf 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -550,14 +550,12 @@ export default defineConfig(({ command, mode }) => { ### server.hmr -- **Type:** `boolean | { protocol?: string, host?: string, port?: number | false, path?: string, timeout?: number, overlay?: boolean, clientPort?: number, server?: Server }` +- **Type:** `boolean | { protocol?: string, host?: string, port?: number, path?: string, timeout?: number, overlay?: boolean, clientPort?: number, server?: Server }` Disable or configure HMR connection (in cases where the HMR websocket must use a different address from the http server). Set `server.hmr.overlay` to `false` to disable the server error overlay. - Set `server.hmr.port` to `false` when connecting to a domain without a port. - `clientPort` is an advanced option that overrides the port only on the client side, allowing you to serve the websocket on a different port than the client code looks for it on. Useful if you're using an SSL proxy in front of your dev server. If specifying `server.hmr.server`, Vite will process HMR connection requests through the provided server. If not in middleware mode, Vite will attempt to process HMR connection requests through the existing server. This can be helpful when using self-signed certificates or when you want to expose Vite over a network on a single port. diff --git a/packages/vite/src/client/client.ts b/packages/vite/src/client/client.ts index c180714f5a69bf..0f5929904a73c3 100644 --- a/packages/vite/src/client/client.ts +++ b/packages/vite/src/client/client.ts @@ -7,9 +7,10 @@ import '@vite/env' // injected by the hmr plugin when served declare const __BASE__: string -declare const __HMR_PROTOCOL__: string -declare const __HMR_HOSTNAME__: string -declare const __HMR_PORT__: string | false +declare const __HMR_PROTOCOL__: string | null +declare const __HMR_HOSTNAME__: string | null +declare const __HMR_PORT__: string | null +declare const __HMR_BASE__: string declare const __HMR_TIMEOUT__: number declare const __HMR_ENABLE_OVERLAY__: boolean @@ -18,9 +19,9 @@ console.log('[vite] connecting...') // use server configuration, then fallback to inference const socketProtocol = __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws') -const socketHost = __HMR_PORT__ - ? `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}` - : `${__HMR_HOSTNAME__ || location.hostname}` +const socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${ + __HMR_PORT__ || location.port +}${__HMR_BASE__}` const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr') const base = __BASE__ || '/' diff --git a/packages/vite/src/node/plugins/clientInjections.ts b/packages/vite/src/node/plugins/clientInjections.ts index e86bec0826d72f..92a2ea93284eb1 100644 --- a/packages/vite/src/node/plugins/clientInjections.ts +++ b/packages/vite/src/node/plugins/clientInjections.ts @@ -2,7 +2,7 @@ import path from 'path' import type { Plugin } from '../plugin' import type { ResolvedConfig } from '../config' import { CLIENT_ENTRY, ENV_ENTRY } from '../constants' -import { normalizePath, isObject } from '../utils' +import { normalizePath } from '../utils' // ids in transform are normalized to unix style const normalizedClientEntry = normalizePath(CLIENT_ENTRY) @@ -23,21 +23,19 @@ export function clientInjectionsPlugin(config: ResolvedConfig): Plugin { const protocol = options.protocol || null const timeout = options.timeout || 30000 const overlay = options.overlay !== false - let port: number | string | false | undefined - if (isObject(config.server.hmr)) { - port = config.server.hmr.clientPort || config.server.hmr.port - } + let port: number | string | undefined | null + port = options.clientPort || options.port if (config.server.middlewareMode) { - port = String(port || 24678) - } else { - port = String(port || options.port || config.server.port!) + port = port || 24678 } + port = port ? String(port) : null + let hmrBase = config.base if (options.path) { hmrBase = path.posix.join(hmrBase, options.path) } - if (hmrBase !== '/') { - port = path.posix.normalize(`${port}${hmrBase}`) + if (hmrBase === '/') { + hmrBase = '' } return code @@ -47,6 +45,7 @@ export function clientInjectionsPlugin(config: ResolvedConfig): Plugin { .replace(/__HMR_PROTOCOL__/g, JSON.stringify(protocol)) .replace(/__HMR_HOSTNAME__/g, JSON.stringify(host)) .replace(/__HMR_PORT__/g, JSON.stringify(port)) + .replace(/__HMR_BASE__/g, JSON.stringify(hmrBase)) .replace(/__HMR_TIMEOUT__/g, JSON.stringify(timeout)) .replace(/__HMR_ENABLE_OVERLAY__/g, JSON.stringify(overlay)) } else if (!options?.ssr && code.includes('process.env.NODE_ENV')) { diff --git a/packages/vite/src/node/server/hmr.ts b/packages/vite/src/node/server/hmr.ts index edb73785247b6f..fc18b0aa91c5cb 100644 --- a/packages/vite/src/node/server/hmr.ts +++ b/packages/vite/src/node/server/hmr.ts @@ -18,7 +18,7 @@ const normalizedClientDir = normalizePath(CLIENT_DIR) export interface HmrOptions { protocol?: string host?: string - port?: number | false + port?: number clientPort?: number path?: string timeout?: number From b7cc0dcdf41c09c147356b0ecafa98b69491261c Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Tue, 29 Mar 2022 15:10:23 +0800 Subject: [PATCH 07/93] docs: note url string must be static (#7508) --- docs/guide/assets.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/guide/assets.md b/docs/guide/assets.md index fd5aa46f49467f..53ac153f9465bd 100644 --- a/docs/guide/assets.md +++ b/docs/guide/assets.md @@ -103,8 +103,13 @@ function getImageUrl(name) { } ``` -During the production build, Vite will perform necessary transforms so that the URLs still point to the correct location even after bundling and asset hashing. +During the production build, Vite will perform necessary transforms so that the URLs still point to the correct location even after bundling and asset hashing. However, the URL string must be static so it can be analyzed, otherwise the code will be left as is, which can cause runtime errors if `build.target` does not support `import.meta.url` -::: warning Note: Does not work with SSR +```js +// Vite will not transform this +const imgUrl = new URL(imagePath, import.meta.url).href +``` + +::: warning Does not work with SSR This pattern does not work if you are using Vite for Server-Side Rendering, because `import.meta.url` have different semantics in browsers vs. Node.js. The server bundle also cannot determine the client host URL ahead of time. ::: From 884e994b7322eb4ff96f457fe536affcd0b596d0 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Tue, 29 Mar 2022 15:15:51 +0800 Subject: [PATCH 08/93] docs: note env in command line (#7507) --- docs/guide/env-and-mode.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/env-and-mode.md b/docs/guide/env-and-mode.md index d3a6a575bce64c..a2dee2b0d9d76e 100644 --- a/docs/guide/env-and-mode.md +++ b/docs/guide/env-and-mode.md @@ -37,7 +37,7 @@ Vite uses [dotenv](https://github.com/motdotla/dotenv) to load additional enviro An env file for a specific mode (e.g. `.env.production`) will take higher priority than a generic one (e.g. `.env`). -In addition, environment variables that already exist when Vite is executed have the highest priority and will not be overwritten by `.env` files. +In addition, environment variables that already exist when Vite is executed have the highest priority and will not be overwritten by `.env` files. For example, when running `VITE_SOME_KEY=123 vite build`. `.env` files are loaded at the start of Vite. Restart the server after making changes. ::: From 9ce673202d7cd3853710080f593241973c58d837 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Tue, 29 Mar 2022 16:19:09 +0900 Subject: [PATCH 09/93] fix: import with query with exports/browser field (#7098) --- .../resolve/__tests__/resolve.spec.ts | 5 +- packages/playground/resolve/index.html | 3 +- packages/vite/src/node/plugins/resolve.ts | 48 +++++++++++-------- 3 files changed, 35 insertions(+), 21 deletions(-) diff --git a/packages/playground/resolve/__tests__/resolve.spec.ts b/packages/playground/resolve/__tests__/resolve.spec.ts index c8c85d8df9b806..2deb2fab7f8d40 100644 --- a/packages/playground/resolve/__tests__/resolve.spec.ts +++ b/packages/playground/resolve/__tests__/resolve.spec.ts @@ -17,7 +17,10 @@ test('deep import with exports field', async () => { }) test('deep import with query with exports field', async () => { - expect(await page.textContent('.exports-deep-query')).not.toMatch('fail') + // since it is imported with `?url` it should return a url + expect(await page.textContent('.exports-deep-query')).toMatch( + isBuild ? /base64/ : '/exports-path/deep.json' + ) }) test('deep import with exports field + exposed dir', async () => { diff --git a/packages/playground/resolve/index.html b/packages/playground/resolve/index.html index 2c4ed7b9aa760c..1920ebb675d24c 100644 --- a/packages/playground/resolve/index.html +++ b/packages/playground/resolve/index.html @@ -171,10 +171,11 @@

resolve package that contains # in path

import e from 'resolve-browser-field/ext-index/index.js' import f from 'resolve-browser-field/ext-index' import g from 'resolve-browser-field/no-ext-index/index.js' // no substitution + import h from 'resolve-browser-field/no-ext?query' import { ra, rb, rc, rd, re, rf, rg } from 'resolve-browser-field/relative' - const success = [main, a, c, d, e, f, ra, rc, rd, re, rf] + const success = [main, a, c, d, e, f, h, ra, rc, rd, re, rf] const noSuccess = [b, g, rb, rg] if ( diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 686c08b12c3248..1b59503a9d43ed 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -332,23 +332,28 @@ export function resolvePlugin(baseOptions: InternalResolveOptions): Plugin { } } -function tryFsResolve( - fsPath: string, - options: InternalResolveOptions, - tryIndex = true, - targetWeb = true -): string | undefined { - let file = fsPath +function splitFileAndPostfix(path: string) { + let file = path let postfix = '' - let postfixIndex = fsPath.indexOf('?') + let postfixIndex = path.indexOf('?') if (postfixIndex < 0) { - postfixIndex = fsPath.indexOf('#') + postfixIndex = path.indexOf('#') } if (postfixIndex > 0) { - file = fsPath.slice(0, postfixIndex) - postfix = fsPath.slice(postfixIndex) + file = path.slice(0, postfixIndex) + postfix = path.slice(postfixIndex) } + return { file, postfix } +} + +function tryFsResolve( + fsPath: string, + options: InternalResolveOptions, + tryIndex = true, + targetWeb = true +): string | undefined { + const { file, postfix } = splitFileAndPostfix(fsPath) let res: string | undefined @@ -842,6 +847,7 @@ function resolveExports( if (options.conditions) { conditions.push(...options.conditions) } + return _resolveExports(pkg, key, { browser: targetWeb, require: options.isRequire, @@ -872,12 +878,14 @@ function resolveDeepImport( // map relative based on exports data if (exportsField) { if (isObject(exportsField) && !Array.isArray(exportsField)) { - relativeId = resolveExports( - data, - cleanUrl(relativeId), - options, - targetWeb - ) + // resolve without postfix (see #7098) + const { file, postfix } = splitFileAndPostfix(relativeId) + const exportsId = resolveExports(data, file, options, targetWeb) + if (exportsId !== undefined) { + relativeId = exportsId + postfix + } else { + relativeId = undefined + } } else { // not exposed relativeId = undefined @@ -889,9 +897,11 @@ function resolveDeepImport( ) } } else if (targetWeb && isObject(browserField)) { - const mapped = mapWithBrowserField(relativeId, browserField) + // resolve without postfix (see #7098) + const { file, postfix } = splitFileAndPostfix(relativeId) + const mapped = mapWithBrowserField(file, browserField) if (mapped) { - relativeId = mapped + relativeId = mapped + postfix } else if (mapped === false) { return (webResolvedImports[id] = browserExternalId) } From 2b7dad1ea1d78d7977e0569fcca4c585b4014e85 Mon Sep 17 00:00:00 2001 From: Artur Date: Tue, 29 Mar 2022 12:16:52 +0300 Subject: [PATCH 10/93] fix: make @fs URLs work with special characters (#7510) --- .../fs-serve/__tests__/fs-serve.spec.ts | 16 +++++++++++ .../playground/fs-serve/root/src/index.html | 28 +++++++++++++++++++ .../safe.json" | 3 ++ .../safe.txt" | 1 + .../src/node/server/middlewares/static.ts | 2 +- 5 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 "packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.json" create mode 100644 "packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.txt" diff --git a/packages/playground/fs-serve/__tests__/fs-serve.spec.ts b/packages/playground/fs-serve/__tests__/fs-serve.spec.ts index c618186b9bcd64..eba1e441881710 100644 --- a/packages/playground/fs-serve/__tests__/fs-serve.spec.ts +++ b/packages/playground/fs-serve/__tests__/fs-serve.spec.ts @@ -23,6 +23,15 @@ describe('main', () => { expect(await page.textContent('.safe-fetch-status')).toBe('200') }) + test('safe fetch with special characters', async () => { + expect( + await page.textContent('.safe-fetch-subdir-special-characters') + ).toMatch('KEY=safe') + expect( + await page.textContent('.safe-fetch-subdir-special-characters-status') + ).toBe('200') + }) + test('unsafe fetch', async () => { expect(await page.textContent('.unsafe-fetch')).toMatch('403 Restricted') expect(await page.textContent('.unsafe-fetch-status')).toBe('403') @@ -33,6 +42,13 @@ describe('main', () => { expect(await page.textContent('.safe-fs-fetch-status')).toBe('200') }) + test('safe fs fetch with special characters', async () => { + expect(await page.textContent('.safe-fs-fetch-special-characters')).toBe( + stringified + ) + expect(await page.textContent('.safe-fs-fetch-status')).toBe('200') + }) + test('unsafe fs fetch', async () => { expect(await page.textContent('.unsafe-fs-fetch')).toBe('') expect(await page.textContent('.unsafe-fs-fetch-status')).toBe('403') diff --git a/packages/playground/fs-serve/root/src/index.html b/packages/playground/fs-serve/root/src/index.html index 9e4f728a593a91..951e14ad2cce91 100644 --- a/packages/playground/fs-serve/root/src/index.html +++ b/packages/playground/fs-serve/root/src/index.html @@ -11,6 +11,8 @@

Safe Fetch

Safe Fetch Subdirectory


 

+

+

 
 

Unsafe Fetch


@@ -19,6 +21,8 @@ 

Unsafe Fetch

Safe /@fs/ Fetch


 

+

+

 
 

Unsafe /@fs/ Fetch


@@ -56,6 +60,16 @@ 

Denied

text('.safe-fetch-subdir', JSON.stringify(data)) }) + // inside allowed dir, with special characters, safe fetch + fetch('/src/special%20characters%20%C3%A5%C3%A4%C3%B6/safe.txt') + .then((r) => { + text('.safe-fetch-subdir-special-characters-status', r.status) + return r.text() + }) + .then((data) => { + text('.safe-fetch-subdir-special-characters', JSON.stringify(data)) + }) + // outside of allowed dir, treated as unsafe fetch('/unsafe.txt') .then((r) => { @@ -92,6 +106,20 @@

Denied

console.error(e) }) + // not imported before, inside root with special characters, treated as safe + fetch( + '/@fs/' + + ROOT + + '/root/src/special%20characters%20%C3%A5%C3%A4%C3%B6/safe.json' + ) + .then((r) => { + text('.safe-fs-fetch-special-characters-status', r.status) + return r.json() + }) + .then((data) => { + text('.safe-fs-fetch-special-characters', JSON.stringify(data)) + }) + // .env, denied by default fetch('/@fs/' + ROOT + '/root/.env') .then((r) => { diff --git "a/packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.json" "b/packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.json" new file mode 100644 index 00000000000000..84f96593c10bad --- /dev/null +++ "b/packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.json" @@ -0,0 +1,3 @@ +{ + "msg": "safe" +} diff --git "a/packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.txt" "b/packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.txt" new file mode 100644 index 00000000000000..3f3d0607101642 --- /dev/null +++ "b/packages/playground/fs-serve/root/src/special characters \303\245\303\244\303\266/safe.txt" @@ -0,0 +1 @@ +KEY=safe diff --git a/packages/vite/src/node/server/middlewares/static.ts b/packages/vite/src/node/server/middlewares/static.ts index a6623338783cc8..5fb4f7fad2e055 100644 --- a/packages/vite/src/node/server/middlewares/static.ts +++ b/packages/vite/src/node/server/middlewares/static.ts @@ -111,7 +111,7 @@ export function serveRawFsMiddleware( // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` return function viteServeRawFsMiddleware(req, res, next) { - let url = req.url! + let url = decodeURI(req.url!) // In some cases (e.g. linked monorepos) files outside of root will // reference assets that are also out of served root. In such cases // the paths are rewritten to `/@fs/` prefixed paths and must be served by From 90df0bb7c610834f875dbfdb8dd3452f44f15627 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Tue, 29 Mar 2022 20:08:34 +0900 Subject: [PATCH 11/93] fix: tailwind css sourcemap warning (#7480) --- .../__tests__/build.spec.ts | 13 ++++ .../__tests__/serve.spec.ts | 13 ++++ .../playground/tailwind-sourcemap/index.html | 9 +++ .../tailwind-sourcemap/package.json | 14 ++++ .../tailwind-sourcemap/postcss.config.js | 5 ++ .../tailwind-sourcemap/tailwind.config.js | 7 ++ .../tailwind-sourcemap/tailwind.css | 3 + .../tailwind-sourcemap/vite.config.js | 11 +++ packages/vite/src/node/plugins/css.ts | 30 ++++++-- pnpm-lock.yaml | 68 ++++++++++++++++++- 10 files changed, 164 insertions(+), 9 deletions(-) create mode 100644 packages/playground/tailwind-sourcemap/__tests__/build.spec.ts create mode 100644 packages/playground/tailwind-sourcemap/__tests__/serve.spec.ts create mode 100644 packages/playground/tailwind-sourcemap/index.html create mode 100644 packages/playground/tailwind-sourcemap/package.json create mode 100644 packages/playground/tailwind-sourcemap/postcss.config.js create mode 100644 packages/playground/tailwind-sourcemap/tailwind.config.js create mode 100644 packages/playground/tailwind-sourcemap/tailwind.css create mode 100644 packages/playground/tailwind-sourcemap/vite.config.js diff --git a/packages/playground/tailwind-sourcemap/__tests__/build.spec.ts b/packages/playground/tailwind-sourcemap/__tests__/build.spec.ts new file mode 100644 index 00000000000000..e36c1f52d2c1f8 --- /dev/null +++ b/packages/playground/tailwind-sourcemap/__tests__/build.spec.ts @@ -0,0 +1,13 @@ +import { isBuild } from 'testUtils' + +if (isBuild) { + test('should not output sourcemap warning (#4939)', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch('Sourcemap is likely to be incorrect') + }) + }) +} else { + test('this file only includes test for build', () => { + expect(true).toBe(true) + }) +} diff --git a/packages/playground/tailwind-sourcemap/__tests__/serve.spec.ts b/packages/playground/tailwind-sourcemap/__tests__/serve.spec.ts new file mode 100644 index 00000000000000..d961f75e4536e5 --- /dev/null +++ b/packages/playground/tailwind-sourcemap/__tests__/serve.spec.ts @@ -0,0 +1,13 @@ +import { isBuild } from 'testUtils' + +if (!isBuild) { + test('should not output missing source file warning', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch(/Sourcemap for .+ points to missing source files/) + }) + }) +} else { + test('this file only includes test for serve', () => { + expect(true).toBe(true) + }) +} diff --git a/packages/playground/tailwind-sourcemap/index.html b/packages/playground/tailwind-sourcemap/index.html new file mode 100644 index 00000000000000..95c8c5da7716d1 --- /dev/null +++ b/packages/playground/tailwind-sourcemap/index.html @@ -0,0 +1,9 @@ +
+

Tailwind Sourcemap

+ +

foo

+
+ + diff --git a/packages/playground/tailwind-sourcemap/package.json b/packages/playground/tailwind-sourcemap/package.json new file mode 100644 index 00000000000000..5c374f3bf47f1b --- /dev/null +++ b/packages/playground/tailwind-sourcemap/package.json @@ -0,0 +1,14 @@ +{ + "name": "test-tailwind-sourcemap", + "private": true, + "version": "0.0.0", + "scripts": { + "dev": "vite", + "build": "vite build", + "debug": "node --inspect-brk ../../vite/bin/vite", + "preview": "vite preview" + }, + "dependencies": { + "tailwindcss": "^3.0.23" + } +} diff --git a/packages/playground/tailwind-sourcemap/postcss.config.js b/packages/playground/tailwind-sourcemap/postcss.config.js new file mode 100644 index 00000000000000..eab3760cbc7b42 --- /dev/null +++ b/packages/playground/tailwind-sourcemap/postcss.config.js @@ -0,0 +1,5 @@ +module.exports = { + plugins: { + tailwindcss: { config: __dirname + '/tailwind.config.js' } + } +} diff --git a/packages/playground/tailwind-sourcemap/tailwind.config.js b/packages/playground/tailwind-sourcemap/tailwind.config.js new file mode 100644 index 00000000000000..f89a536ccd742f --- /dev/null +++ b/packages/playground/tailwind-sourcemap/tailwind.config.js @@ -0,0 +1,7 @@ +module.exports = { + content: ['./index.html'], + theme: { + extend: {} + }, + plugins: [] +} diff --git a/packages/playground/tailwind-sourcemap/tailwind.css b/packages/playground/tailwind-sourcemap/tailwind.css new file mode 100644 index 00000000000000..b5c61c956711f9 --- /dev/null +++ b/packages/playground/tailwind-sourcemap/tailwind.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; diff --git a/packages/playground/tailwind-sourcemap/vite.config.js b/packages/playground/tailwind-sourcemap/vite.config.js new file mode 100644 index 00000000000000..70fea77247bcd4 --- /dev/null +++ b/packages/playground/tailwind-sourcemap/vite.config.js @@ -0,0 +1,11 @@ +/** + * @type {import('vite').UserConfig} + */ +module.exports = { + css: { + devSourcemap: true + }, + build: { + sourcemap: true + } +} diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 4933f8455931c1..afd9e7849b7432 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -783,7 +783,9 @@ async function compileCSS( map: { inline: false, annotation: false, - sourcesContent: false + // postcss may return virtual files + // we cannot obtain content of them, so this needs to be enabled + sourcesContent: true // when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources` // prev: preprocessorMap, } @@ -862,19 +864,33 @@ export function formatPostcssSourceMap( file: string ): ExistingRawSourceMap { const inputFileDir = path.dirname(file) - const sources = rawMap.sources + + const sources: string[] = [] + const sourcesContent: string[] = [] + for (const [i, source] of rawMap.sources.entries()) { // remove from sources, to prevent source map to be combined incorrectly - .filter((source) => source !== '') - .map((source) => { - const cleanSource = cleanUrl(decodeURIComponent(source)) - return normalizePath(path.resolve(inputFileDir, cleanSource)) - }) + if (source === '') continue + + const cleanSource = cleanUrl(decodeURIComponent(source)) + + // postcss returns virtual files + if (/^<.+>$/.test(cleanSource)) { + sources.push(`\0${cleanSource}`) + } else { + sources.push(normalizePath(path.resolve(inputFileDir, cleanSource))) + } + + if (rawMap.sourcesContent) { + sourcesContent.push(rawMap.sourcesContent[i]) + } + } return { file, mappings: rawMap.mappings, names: rawMap.names, sources, + sourcesContent, version: rawMap.version } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b0574f04c53b86..461ca065e2e18d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -666,6 +666,12 @@ importers: devDependencies: '@vitejs/plugin-vue': link:../../plugin-vue + packages/playground/tailwind-sourcemap: + specifiers: + tailwindcss: ^3.0.23 + dependencies: + tailwindcss: 3.0.23_ts-node@10.4.0 + packages/playground/tsconfig-json: specifiers: {} @@ -3553,7 +3559,6 @@ packages: readdirp: 3.6.0 optionalDependencies: fsevents: 2.3.2 - dev: true /chownr/2.0.0: resolution: {integrity: sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==} @@ -7526,6 +7531,16 @@ packages: postcss: 8.4.5 dev: false + /postcss-js/4.0.0_postcss@8.4.12: + resolution: {integrity: sha512-77QESFBwgX4irogGVPgQ5s07vLvFqWr228qZY+w6lW599cRlK/HmnlivnnVUxkjHnCu4J16PDMHcH+e+2HbvTQ==} + engines: {node: ^12 || ^14 || >= 16} + peerDependencies: + postcss: ^8.3.3 + dependencies: + camelcase-css: 2.0.1 + postcss: 8.4.12 + dev: false + /postcss-load-config/3.1.0_ts-node@10.4.0: resolution: {integrity: sha512-ipM8Ds01ZUophjDTQYSVP70slFSYg3T0/zyfII5vzhN6V57YSxMgG5syXuwi5VtS8wSf3iL30v0uBdoIVx4Q0g==} engines: {node: '>= 10'} @@ -7556,7 +7571,6 @@ packages: postcss: 8.4.12 ts-node: 10.4.0_44ef5af6cbbc24239b4e70b5c7b0d7a6 yaml: 1.10.2 - dev: true /postcss-modules-extract-imports/3.0.0_postcss@8.4.12: resolution: {integrity: sha512-bdHleFnP3kZ4NYDhuGlVK+CMrQ/pqUm8bx/oGL93K6gVwiclvX5x0n76fYMKuIGKzlABOy13zsvqjb0f92TEXw==} @@ -7623,6 +7637,16 @@ packages: dependencies: postcss-selector-parser: 6.0.8 + /postcss-nested/5.0.6_postcss@8.4.12: + resolution: {integrity: sha512-rKqm2Fk0KbA8Vt3AdGN0FB9OBOMDVajMG6ZCf/GoHgdxUJ4sBFp0A/uMIRm+MJUdo33YXEtjqIz8u7DAp8B7DA==} + engines: {node: '>=12.0'} + peerDependencies: + postcss: ^8.2.14 + dependencies: + postcss: 8.4.12 + postcss-selector-parser: 6.0.8 + dev: false + /postcss-selector-parser/6.0.8: resolution: {integrity: sha512-D5PG53d209Z1Uhcc0qAZ5U3t5HagH3cxu+WLZ22jt3gLUpXM4eXXfiO14jiDWST3NNooX/E8wISfOhZ9eIjGTQ==} engines: {node: '>=4'} @@ -7630,6 +7654,14 @@ packages: cssesc: 3.0.0 util-deprecate: 1.0.2 + /postcss-selector-parser/6.0.9: + resolution: {integrity: sha512-UO3SgnZOVTwu4kyLR22UQ1xZh086RyNZppb7lLAKBFK8a32ttG5i87Y/P3+2bRSjZNyJ1B7hfFNo273tKe9YxQ==} + engines: {node: '>=4'} + dependencies: + cssesc: 3.0.0 + util-deprecate: 1.0.2 + dev: false + /postcss-value-parser/3.3.1: resolution: {integrity: sha512-pISE66AbVkp4fDQ7VHBwRNXzAAKJjw4Vw7nWI/+Q3vuly7SNfgYXvm6i5IgFylHGK5sP/xHAbB7N49OS4gWNyQ==} dev: false @@ -8861,6 +8893,38 @@ packages: - ts-node dev: false + /tailwindcss/3.0.23_ts-node@10.4.0: + resolution: {integrity: sha512-+OZOV9ubyQ6oI2BXEhzw4HrqvgcARY38xv3zKcjnWtMIZstEsXdI9xftd1iB7+RbOnj2HOEzkA0OyB5BaSxPQA==} + engines: {node: '>=12.13.0'} + hasBin: true + peerDependencies: + autoprefixer: ^10.0.2 + dependencies: + arg: 5.0.1 + chalk: 4.1.2 + chokidar: 3.5.3 + color-name: 1.1.4 + cosmiconfig: 7.0.1 + detective: 5.2.0 + didyoumean: 1.2.2 + dlv: 1.1.3 + fast-glob: 3.2.11 + glob-parent: 6.0.2 + is-glob: 4.0.3 + normalize-path: 3.0.0 + object-hash: 2.2.0 + postcss: 8.4.12 + postcss-js: 4.0.0_postcss@8.4.12 + postcss-load-config: 3.1.3_postcss@8.4.12+ts-node@10.4.0 + postcss-nested: 5.0.6_postcss@8.4.12 + postcss-selector-parser: 6.0.9 + postcss-value-parser: 4.2.0 + quick-lru: 5.1.1 + resolve: 1.22.0 + transitivePeerDependencies: + - ts-node + dev: false + /tar/6.1.11: resolution: {integrity: sha512-an/KZQzQUkZCkuoAA64hM92X0Urb6VpRhAFllDzz44U2mcD5scmT3zBc4VgVpkugF580+DQn8eAFSyoQt0tznA==} engines: {node: '>= 10'} From 4d5521854c0b7213ec7d061dedd7f34e54919944 Mon Sep 17 00:00:00 2001 From: ygj6 <7699524+ygj6@users.noreply.github.com> Date: Tue, 29 Mar 2022 20:44:59 +0800 Subject: [PATCH 12/93] docs: declare the scope of define expressions (#7511) --- docs/config/index.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/config/index.md b/docs/config/index.md index f9a1a81dc77dbf..9fc9273c691f56 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -156,6 +156,8 @@ export default defineConfig(({ command, mode }) => { - Starting from `2.0.0-beta.70`, string values will be used as raw expressions, so if defining a string constant, it needs to be explicitly quoted (e.g. with `JSON.stringify`). + - To be consistent with [esbuild behavior](https://esbuild.github.io/api/#define), expressions must either be a JSON object (null, boolean, number, string, array, or object) or a single identifier. + - Replacements are performed only when the match is surrounded by word boundaries (`\b`). ::: warning From 9481c7d1dca1155f73d21e913bd97ddd8d92a428 Mon Sep 17 00:00:00 2001 From: yoho Date: Tue, 29 Mar 2022 23:00:41 +0800 Subject: [PATCH 13/93] fix: worker match only run in js (#7500) --- packages/playground/vue/Main.vue | 3 ++- packages/playground/vue/__tests__/vue.spec.ts | 6 ++++++ packages/playground/vue/worker.vue | 17 +++++++++++++++++ packages/playground/vue/workerTest.js | 1 + packages/playground/worker/index.html | 5 +++++ packages/vite/src/node/build.ts | 2 -- .../src/node/plugins/assetImportMetaUrl.ts | 19 +++++++++++++++---- packages/vite/src/node/plugins/index.ts | 5 +++-- .../src/node/plugins/workerImportMetaUrl.ts | 16 +++++++++++++--- packages/vite/src/node/utils.ts | 1 + 10 files changed, 63 insertions(+), 12 deletions(-) create mode 100644 packages/playground/vue/worker.vue create mode 100644 packages/playground/vue/workerTest.js diff --git a/packages/playground/vue/Main.vue b/packages/playground/vue/Main.vue index d10ae401f7aa8e..87319acdf6f736 100644 --- a/packages/playground/vue/Main.vue +++ b/packages/playground/vue/Main.vue @@ -20,6 +20,7 @@ + diff --git a/packages/playground/vue/workerTest.js b/packages/playground/vue/workerTest.js new file mode 100644 index 00000000000000..fcde5e19b30677 --- /dev/null +++ b/packages/playground/vue/workerTest.js @@ -0,0 +1 @@ +self.postMessage('worker load!') diff --git a/packages/playground/worker/index.html b/packages/playground/worker/index.html index 60289ff84d6a06..fb4b3e9e85bfc8 100644 --- a/packages/playground/worker/index.html +++ b/packages/playground/worker/index.html @@ -1,3 +1,8 @@ +

worker template error match:

+ + const worker = new Worker(new URL('./worker.js', import.meta.url)) + +

format iife:

Expected values:
diff --git a/packages/vite/src/node/build.ts b/packages/vite/src/node/build.ts index 6b4d38836b6c51..d898b090fcdf6c 100644 --- a/packages/vite/src/node/build.ts +++ b/packages/vite/src/node/build.ts @@ -19,7 +19,6 @@ import type { } from 'rollup' import type Rollup from 'rollup' import { buildReporterPlugin } from './plugins/reporter' -import { buildHtmlPlugin } from './plugins/html' import { buildEsbuildPlugin } from './plugins/esbuild' import { terserPlugin } from './plugins/terser' import type { Terser } from 'types/terser' @@ -310,7 +309,6 @@ export function resolveBuildPlugins(config: ResolvedConfig): { return { pre: [ watchPackageDataPlugin(config), - buildHtmlPlugin(config), commonjsPlugin(options.commonjsOptions), dataURIPlugin(), dynamicImportVars(options.dynamicImportVarsOptions), diff --git a/packages/vite/src/node/plugins/assetImportMetaUrl.ts b/packages/vite/src/node/plugins/assetImportMetaUrl.ts index b0c59bed808604..a3f8e441b0f933 100644 --- a/packages/vite/src/node/plugins/assetImportMetaUrl.ts +++ b/packages/vite/src/node/plugins/assetImportMetaUrl.ts @@ -3,7 +3,12 @@ import MagicString from 'magic-string' import path from 'path' import { fileToUrl } from './asset' import type { ResolvedConfig } from '../config' -import { multilineCommentsRE, singlelineCommentsRE } from '../utils' +import { + multilineCommentsRE, + singlelineCommentsRE, + stringsRE, + blankReplacer +} from '../utils' /** * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL @@ -27,12 +32,18 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin { const importMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*,?\s*\)/g const noCommentsCode = code - .replace(multilineCommentsRE, (m) => ' '.repeat(m.length)) - .replace(singlelineCommentsRE, (m) => ' '.repeat(m.length)) + .replace(multilineCommentsRE, blankReplacer) + .replace(singlelineCommentsRE, blankReplacer) + .replace(stringsRE, (m) => `'${'\0'.repeat(m.length - 2)}'`) + let s: MagicString | null = null let match: RegExpExecArray | null while ((match = importMetaUrlRE.exec(noCommentsCode))) { - const { 0: exp, 1: rawUrl, index } = match + const { 0: exp, 1: emptyUrl, index } = match + + const urlStart = exp.indexOf(emptyUrl) + index + const urlEnd = urlStart + emptyUrl.length + const rawUrl = code.slice(urlStart, urlEnd) if (!s) s = new MagicString(code) diff --git a/packages/vite/src/node/plugins/index.ts b/packages/vite/src/node/plugins/index.ts index 825798a73c8493..d294233b92ae17 100644 --- a/packages/vite/src/node/plugins/index.ts +++ b/packages/vite/src/node/plugins/index.ts @@ -9,7 +9,7 @@ import { importAnalysisPlugin } from './importAnalysis' import { cssPlugin, cssPostPlugin } from './css' import { assetPlugin } from './asset' import { clientInjectionsPlugin } from './clientInjections' -import { htmlInlineProxyPlugin } from './html' +import { buildHtmlPlugin, htmlInlineProxyPlugin } from './html' import { wasmPlugin } from './wasm' import { modulePreloadPolyfillPlugin } from './modulePreloadPolyfill' import { webWorkerPlugin } from './worker' @@ -61,12 +61,13 @@ export async function resolvePlugins( ), wasmPlugin(config), webWorkerPlugin(config), - workerImportMetaUrlPlugin(config), assetPlugin(config), ...normalPlugins, definePlugin(config), cssPostPlugin(config), config.build.ssr ? ssrRequireHookPlugin(config) : null, + isBuild && buildHtmlPlugin(config), + workerImportMetaUrlPlugin(config), ...buildPlugins.pre, ...postPlugins, ...buildPlugins.post, diff --git a/packages/vite/src/node/plugins/workerImportMetaUrl.ts b/packages/vite/src/node/plugins/workerImportMetaUrl.ts index 233d83d066bcb7..4b5711cf3a6248 100644 --- a/packages/vite/src/node/plugins/workerImportMetaUrl.ts +++ b/packages/vite/src/node/plugins/workerImportMetaUrl.ts @@ -7,7 +7,8 @@ import { cleanUrl, injectQuery, multilineCommentsRE, - singlelineCommentsRE + singlelineCommentsRE, + stringsRE } from '../utils' import path from 'path' import { bundleWorkerEntry } from './worker' @@ -122,12 +123,21 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin { const noCommentsCode = code .replace(multilineCommentsRE, blankReplacer) .replace(singlelineCommentsRE, blankReplacer) + + const noStringCode = noCommentsCode.replace( + stringsRE, + (m) => `'${' '.repeat(m.length - 2)}'` + ) let match: RegExpExecArray | null let s: MagicString | null = null - while ((match = importMetaUrlRE.exec(noCommentsCode))) { - const { 0: allExp, 2: exp, 3: rawUrl, index } = match + while ((match = importMetaUrlRE.exec(noStringCode))) { + const { 0: allExp, 2: exp, 3: emptyUrl, index } = match const urlIndex = allExp.indexOf(exp) + index + const urlStart = allExp.indexOf(emptyUrl) + index + const urlEnd = urlStart + emptyUrl.length + const rawUrl = code.slice(urlStart, urlEnd) + if (options?.ssr) { this.error( `\`new URL(url, import.meta.url)\` is not supported in SSR.`, diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index edb3410751868a..0e3fe49c9cb584 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -732,3 +732,4 @@ export function parseRequest(id: string): Record | null { } export const blankReplacer = (match: string) => ' '.repeat(match.length) +export const stringsRE = /"[^"]*"|'[^']*'|`[^`]*`/g From b16b8964e633cbf1ee2b051044af2660f1636558 Mon Sep 17 00:00:00 2001 From: Dany Castillo <31006608+dcastil@users.noreply.github.com> Date: Tue, 29 Mar 2022 18:05:54 +0200 Subject: [PATCH 14/93] docs: add wildcard to suggested .gitignore entry in docs (#7512) --- docs/guide/env-and-mode.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/env-and-mode.md b/docs/guide/env-and-mode.md index a2dee2b0d9d76e..1649feda8c7501 100644 --- a/docs/guide/env-and-mode.md +++ b/docs/guide/env-and-mode.md @@ -57,7 +57,7 @@ If you want to customize env variables prefix, see [envPrefix](/config/index#env :::warning SECURITY NOTES -- `.env.*.local` files are local-only and can contain sensitive variables. You should add `.local` to your `.gitignore` to avoid them being checked into git. +- `.env.*.local` files are local-only and can contain sensitive variables. You should add `*.local` to your `.gitignore` to avoid them being checked into git. - Since any variables exposed to your Vite source code will end up in your client bundle, `VITE_*` variables should _not_ contain any sensitive information. ::: From f05a81387b6901622c86c2833f42420b8e18e95e Mon Sep 17 00:00:00 2001 From: yoho Date: Wed, 30 Mar 2022 00:11:54 +0800 Subject: [PATCH 15/93] fix: import url worker two times (#7468) --- .../worker/__tests__/es/es-worker.spec.ts | 4 +- .../worker/emit-chunk-nested-worker.js | 25 +++- .../worker/emit-chunk-sub-worker.js | 14 +- packages/playground/worker/index.html | 10 +- .../playground/worker/module-and-worker.js | 5 + .../worker/worker/main-format-es.js | 20 ++- .../playground/worker/worker/main-module.js | 1 + packages/vite/src/node/plugins/define.ts | 8 +- packages/vite/src/node/plugins/worker.ts | 127 +++++++++++++++--- .../src/node/plugins/workerImportMetaUrl.ts | 17 +-- 10 files changed, 181 insertions(+), 50 deletions(-) create mode 100644 packages/playground/worker/module-and-worker.js diff --git a/packages/playground/worker/__tests__/es/es-worker.spec.ts b/packages/playground/worker/__tests__/es/es-worker.spec.ts index 51497a0f5ebadd..c7fd0d6c19e4bc 100644 --- a/packages/playground/worker/__tests__/es/es-worker.spec.ts +++ b/packages/playground/worker/__tests__/es/es-worker.spec.ts @@ -60,7 +60,7 @@ if (isBuild) { // assert correct files test('inlined code generation', async () => { const files = fs.readdirSync(assetsDir) - expect(files.length).toBe(20) + expect(files.length).toBe(22) const index = files.find((f) => f.includes('main-module')) const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8') const worker = files.find((f) => f.includes('my-worker')) @@ -94,7 +94,7 @@ test('classic worker', async () => { test('emit chunk', async () => { expect(await page.textContent('.emti-chunk-worker')).toMatch( - '{"msg1":"module1","msg2":"module2","msg3":"module3"}' + '["A string",{"type":"emit-chunk-sub-worker","data":"A string"},{"type":"module-and-worker:worker","data":"A string"},{"type":"module-and-worker:module","data":"module and worker"},{"type":"emit-chunk-sub-worker","data":{"module":"module and worker","msg1":"module1","msg2":"module2","msg3":"module3"}}]' ) expect(await page.textContent('.emti-chunk-dynamic-import-worker')).toMatch( '"A string/es/"' diff --git a/packages/playground/worker/emit-chunk-nested-worker.js b/packages/playground/worker/emit-chunk-nested-worker.js index dff0f5bc64c5ad..6cb72b9488cfaf 100644 --- a/packages/playground/worker/emit-chunk-nested-worker.js +++ b/packages/playground/worker/emit-chunk-nested-worker.js @@ -1,7 +1,28 @@ import SubWorker from './emit-chunk-sub-worker?worker' - const subWorker = new SubWorker() subWorker.onmessage = (event) => { - self.postMessage(event.data) + self.postMessage({ + type: 'emit-chunk-sub-worker', + data: event.data + }) } + +const moduleWorker = new Worker( + new URL('./module-and-worker.js', import.meta.url), + { type: 'module' } +) + +moduleWorker.onmessage = (event) => { + self.postMessage({ + type: 'module-and-worker:worker', + data: event.data + }) +} + +import('./module-and-worker').then((res) => { + self.postMessage({ + type: 'module-and-worker:module', + data: res.module + }) +}) diff --git a/packages/playground/worker/emit-chunk-sub-worker.js b/packages/playground/worker/emit-chunk-sub-worker.js index bd6b1f6e4f7419..5d20becc781dd7 100644 --- a/packages/playground/worker/emit-chunk-sub-worker.js +++ b/packages/playground/worker/emit-chunk-sub-worker.js @@ -1,6 +1,8 @@ -Promise.all([import('./modules/module2'), import('./modules/module3')]).then( - (data) => { - const _data = { ...data[0], ...data[1] } - self.postMessage(_data) - } -) +Promise.all([ + import('./module-and-worker'), + import('./modules/module2'), + import('./modules/module3') +]).then((data) => { + const _data = { ...data[0], ...data[1], ...data[2] } + self.postMessage(_data) +}) diff --git a/packages/playground/worker/index.html b/packages/playground/worker/index.html index fb4b3e9e85bfc8..aec3995b60a06e 100644 --- a/packages/playground/worker/index.html +++ b/packages/playground/worker/index.html @@ -62,7 +62,9 @@

format iife:

- worker emit chunk + worker emit chunk
+ module and worker:worker in worker file
+ module and worker:module in worker file
.emti-chunk-worker

@@ -73,6 +75,12 @@

+

+ module and worker:worker in simple file + .module-and-worker-worker +

+ + @@ -268,6 +272,12 @@

document.querySelector('.import-meta-url-img-comma-nl').src = metaUrlWithCommaNL + import classNames from './css/foo.module.css' + document.querySelector('#foo').className = classNames['foo-module'] + + import someString from './static/foo.txt?raw' + document.querySelector('.raw-query').textContent = someString + const metaUrlNonExistent = new URL('non-existent', import.meta.url).pathname text('.non-existent-import-meta-url', metaUrlNonExistent) diff --git a/packages/playground/assets/static/foo.txt b/packages/playground/assets/static/foo.txt new file mode 100644 index 00000000000000..19102815663d23 --- /dev/null +++ b/packages/playground/assets/static/foo.txt @@ -0,0 +1 @@ +foo \ No newline at end of file diff --git a/packages/vite/src/node/build.ts b/packages/vite/src/node/build.ts index 3541cc377dc411..ff03352a20d7a7 100644 --- a/packages/vite/src/node/build.ts +++ b/packages/vite/src/node/build.ts @@ -39,6 +39,7 @@ import { getDepsCacheDir, findKnownImports } from './optimizer' import { assetImportMetaUrlPlugin } from './plugins/assetImportMetaUrl' import { loadFallbackPlugin } from './plugins/loadFallback' import { watchPackageDataPlugin } from './packages' +import { ensureWatchPlugin } from './plugins/ensureWatch' export interface BuildOptions { /** @@ -308,6 +309,7 @@ export function resolveBuildPlugins(config: ResolvedConfig): { return { pre: [ + ...(options.watch ? [ensureWatchPlugin()] : []), watchPackageDataPlugin(config), commonjsPlugin(options.commonjsOptions), dataURIPlugin(), diff --git a/packages/vite/src/node/plugins/ensureWatch.ts b/packages/vite/src/node/plugins/ensureWatch.ts new file mode 100644 index 00000000000000..30a6fb3d6df819 --- /dev/null +++ b/packages/vite/src/node/plugins/ensureWatch.ts @@ -0,0 +1,17 @@ +import type { Plugin } from '../plugin' +import { cleanUrl, queryRE } from '../utils' + +/** + * plugin to ensure rollup can watch correctly. + */ +export function ensureWatchPlugin(): Plugin { + return { + name: 'vite:ensure-watch', + load(id) { + if (queryRE.test(id)) { + this.addWatchFile(cleanUrl(id)) + } + return null + } + } +} diff --git a/packages/vite/src/node/plugins/index.ts b/packages/vite/src/node/plugins/index.ts index d294233b92ae17..2d34b99aebf1c5 100644 --- a/packages/vite/src/node/plugins/index.ts +++ b/packages/vite/src/node/plugins/index.ts @@ -17,6 +17,7 @@ import { preAliasPlugin } from './preAlias' import { definePlugin } from './define' import { ssrRequireHookPlugin } from './ssrRequireHook' import { workerImportMetaUrlPlugin } from './workerImportMetaUrl' +import { ensureWatchPlugin } from './ensureWatch' import { metadataPlugin } from './metadata' export async function resolvePlugins( @@ -26,12 +27,14 @@ export async function resolvePlugins( postPlugins: Plugin[] ): Promise { const isBuild = config.command === 'build' + const isWatch = isBuild && !!config.build.watch const buildPlugins = isBuild ? (await import('../build')).resolveBuildPlugins(config) : { pre: [], post: [] } return [ + isWatch ? ensureWatchPlugin() : null, isBuild ? metadataPlugin() : null, isBuild ? null : preAliasPlugin(), aliasPlugin({ entries: config.resolve.alias }), diff --git a/scripts/jestPerTestSetup.ts b/scripts/jestPerTestSetup.ts index 150c02eed5b76c..fcdca77ee9a6eb 100644 --- a/scripts/jestPerTestSetup.ts +++ b/scripts/jestPerTestSetup.ts @@ -175,6 +175,7 @@ afterAll(async () => { global.serverLogs = [] await global.page?.close() await server?.close() + global.watcher?.close() const beforeAllErr = getBeforeAllError() if (beforeAllErr) { throw beforeAllErr @@ -200,7 +201,7 @@ function startStaticServer(config?: InlineConfig): Promise { } // start static file server - const serve = sirv(resolve(rootDir, 'dist')) + const serve = sirv(resolve(rootDir, 'dist'), { dev: !!config?.build?.watch }) const httpServer = (server = http.createServer((req, res) => { if (req.url === '/ping') { res.statusCode = 200 From dfce28355c42d38425bc3374ed944ac324f50882 Mon Sep 17 00:00:00 2001 From: yoho Date: Tue, 12 Apr 2022 02:59:02 +0800 Subject: [PATCH 64/93] feat: clean string module lex string template (#7667) --- .../src/node/__tests__/cleanString.spec.ts | 52 ++++++++ packages/vite/src/node/cleanString.ts | 113 +++++++++++++++++- 2 files changed, 164 insertions(+), 1 deletion(-) diff --git a/packages/vite/src/node/__tests__/cleanString.spec.ts b/packages/vite/src/node/__tests__/cleanString.spec.ts index 883dc67abfe2f9..1065a2d4985ceb 100644 --- a/packages/vite/src/node/__tests__/cleanString.spec.ts +++ b/packages/vite/src/node/__tests__/cleanString.spec.ts @@ -106,3 +106,55 @@ test('find empty string flag in raw index', () => { const bStart = clean.indexOf('\0\0\0\0\0', bIndex) expect(str.slice(bStart, bStart + 5)).toMatch('bbbbb') }) + +test('template string nested', () => { + let str = '`aaaa`' + let res = '`\0\0\0\0`' + let clean = emptyString(str) + expect(clean).toMatch(res) + + str = '`aaaa` `aaaa`' + res = '`\0\0\0\0` `\0\0\0\0`' + clean = emptyString(str) + expect(clean).toMatch(res) + + str = '`aa${a}aa`' + res = '`\0\0${a}\0\0`' + clean = emptyString(str) + expect(clean).toMatch(res) + + str = '`aa${a + `a` + a}aa`' + res = '`\0\0${a + `\0` + a}\0\0`' + clean = emptyString(str) + expect(clean).toMatch(res) + + str = '`aa${a + `a` + a}aa` `aa${a + `a` + a}aa`' + res = '`\0\0${a + `\0` + a}\0\0` `\0\0${a + `\0` + a}\0\0`' + clean = emptyString(str) + expect(clean).toMatch(res) + + str = '`aa${a + `aaaa${c + (a = {b: 1}) + d}` + a}aa`' + res = '`\0\0${a + `\0\0\0\0${c + (a = {b: 1}) + d}` + a}\0\0`' + clean = emptyString(str) + expect(clean).toMatch(res) + + str = + '`aa${a + `aaaa${c + (a = {b: 1}) + d}` + a}aa` `aa${a + `aaaa${c + (a = {b: 1}) + d}` + a}aa`' + res = + '`\0\0${a + `\0\0\0\0${c + (a = {b: 1}) + d}` + a}\0\0` `\0\0${a + `\0\0\0\0${c + (a = {b: 1}) + d}` + a}\0\0`' + clean = emptyString(str) + expect(clean).toMatch(res) + + str = '`aaaa' + res = '' + try { + clean = emptyString(str) + } catch {} + expect(clean).toMatch(res) + + str = + "" + res = `` + clean = emptyString(str) + expect(clean).toMatch(res) +}) diff --git a/packages/vite/src/node/cleanString.ts b/packages/vite/src/node/cleanString.ts index d26274397124ff..05163ea055b631 100644 --- a/packages/vite/src/node/cleanString.ts +++ b/packages/vite/src/node/cleanString.ts @@ -1,3 +1,4 @@ +import type { RollupError } from 'rollup' // bank on the non-overlapping nature of regex matches and combine all filters into one giant regex // /`([^`\$\{\}]|\$\{(`|\g<1>)*\})*`/g can match nested string template // but js not support match expression(\g<0>). so clean string template(`...`) in other ways. @@ -8,7 +9,117 @@ const stringBlankReplacer = (s: string) => `${s[0]}${'\0'.repeat(s.length - 2)}${s[0]}` export function emptyString(raw: string): string { - return raw.replace(cleanerRE, (s: string) => + let res = raw.replace(cleanerRE, (s: string) => s[0] === '/' ? blankReplacer(s) : stringBlankReplacer(s) ) + + let lastEnd = 0 + let start = 0 + while ((start = res.indexOf('`', lastEnd)) >= 0) { + let clean + ;[clean, lastEnd] = lexStringTemplateExpression(res, start) + res = replaceAt(res, start, lastEnd, clean) + } + + return res +} + +const enum LexerState { + inTemplateString, + inInterpolationExpression, + inObjectExpression +} + +function replaceAt( + string: string, + start: number, + end: number, + replacement: string +): string { + return string.slice(0, start) + replacement + string.slice(end) +} + +/** + * lex string template and clean it. + */ +function lexStringTemplateExpression( + code: string, + start: number +): [string, number] { + let state = LexerState.inTemplateString as LexerState + let clean = '`' + const opStack: LexerState[] = [state] + + function pushStack(newState: LexerState) { + state = newState + opStack.push(state) + } + + function popStack() { + opStack.pop() + state = opStack[opStack.length - 1] + } + + let i = start + 1 + outer: for (; i < code.length; i++) { + const char = code.charAt(i) + switch (state) { + case LexerState.inTemplateString: + if (char === '$' && code.charAt(i + 1) === '{') { + pushStack(LexerState.inInterpolationExpression) + clean += '${' + i++ // jump next + } else if (char === '`') { + popStack() + clean += char + if (opStack.length === 0) { + break outer + } + } else { + clean += '\0' + } + break + case LexerState.inInterpolationExpression: + if (char === '{') { + pushStack(LexerState.inObjectExpression) + clean += char + } else if (char === '}') { + popStack() + clean += char + } else if (char === '`') { + pushStack(LexerState.inTemplateString) + clean += char + } else { + clean += char + } + break + case LexerState.inObjectExpression: + if (char === '}') { + popStack() + clean += char + } else if (char === '`') { + pushStack(LexerState.inTemplateString) + clean += char + } else { + clean += char + } + break + default: + throw new Error('unknown string template lexer state') + } + } + + if (opStack.length !== 0) { + error(start) + } + + return [clean, i + 1] +} + +function error(pos: number) { + const err = new Error( + `can not match string template expression.` + ) as RollupError + err.pos = pos + throw err } From 66b6dc508086a4ab75af4dacc849c50a58c7aebc Mon Sep 17 00:00:00 2001 From: Rom Date: Tue, 12 Apr 2022 06:40:07 +0200 Subject: [PATCH 65/93] fix: `$ vite preview` 404 handling (#7665) --- packages/vite/src/node/preview.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/preview.ts b/packages/vite/src/node/preview.ts index c00f62a9cb8f0c..23b905fd01a719 100644 --- a/packages/vite/src/node/preview.ts +++ b/packages/vite/src/node/preview.ts @@ -1,4 +1,5 @@ import path from 'path' +import fs from 'fs' import sirv from 'sirv' import connect from 'connect' import compression from './server/middlewares/compression' @@ -90,11 +91,20 @@ export async function preview( config.base, sirv(distDir, { etag: true, - dev: true, - single: true + dev: true }) ) + app.use(config.base, (_, res, next) => { + const file = path.join(distDir, './404.html') + if (fs.existsSync(file)) { + res.statusCode = 404 + res.end(fs.readFileSync(file)) + } else { + next() + } + }) + const options = config.preview const hostname = resolveHostname(options.host) const port = options.port ?? 4173 From 0c928aa079df5060c5bc7a745a128be62fd86cd2 Mon Sep 17 00:00:00 2001 From: Haoqun Jiang Date: Tue, 12 Apr 2022 17:29:25 +0800 Subject: [PATCH 66/93] refactor: esbuild handles `target` and `useDefineForClassFields` (#7698) --- packages/vite/src/node/plugins/esbuild.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/packages/vite/src/node/plugins/esbuild.ts b/packages/vite/src/node/plugins/esbuild.ts index db216c7d6b0d77..c982b4e61f30c8 100644 --- a/packages/vite/src/node/plugins/esbuild.ts +++ b/packages/vite/src/node/plugins/esbuild.ts @@ -81,6 +81,7 @@ export async function transformWithEsbuild( // these fields would affect the compilation result // https://esbuild.github.io/content-types/#tsconfig-json const meaningfulFields: Array = [ + 'target', 'jsxFactory', 'jsxFragmentFactory', 'useDefineForClassFields', @@ -98,17 +99,9 @@ export async function transformWithEsbuild( compilerOptionsForFile[field] = loadedCompilerOptions[field] } } - - // align with TypeScript 4.3 - // https://github.com/microsoft/TypeScript/pull/42663 - if (loadedCompilerOptions.target?.toLowerCase() === 'esnext') { - compilerOptionsForFile.useDefineForClassFields = - loadedCompilerOptions.useDefineForClassFields ?? true - } } tsconfigRaw = { - ...tsconfigRaw, compilerOptions: { ...compilerOptionsForFile, ...tsconfigRaw?.compilerOptions From 8f28350291dde55e9d20b05f124b53867bcaf8e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Tue, 12 Apr 2022 18:32:02 +0900 Subject: [PATCH 67/93] chore(create-vite): add isolatedModules (#7697) --- packages/create-vite/template-lit-ts/tsconfig.json | 1 + packages/create-vite/template-svelte-ts/tsconfig.json | 3 ++- packages/create-vite/template-vanilla-ts/tsconfig.json | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/create-vite/template-lit-ts/tsconfig.json b/packages/create-vite/template-lit-ts/tsconfig.json index 03ecaf410c88be..2ec691c81c2b38 100644 --- a/packages/create-vite/template-lit-ts/tsconfig.json +++ b/packages/create-vite/template-lit-ts/tsconfig.json @@ -11,6 +11,7 @@ "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "moduleResolution": "node", + "isolatedModules": true, "allowSyntheticDefaultImports": true, "experimentalDecorators": true, "forceConsistentCasingInFileNames": true, diff --git a/packages/create-vite/template-svelte-ts/tsconfig.json b/packages/create-vite/template-svelte-ts/tsconfig.json index 4d6c04cf0ab13b..96bfd81aaf1203 100644 --- a/packages/create-vite/template-svelte-ts/tsconfig.json +++ b/packages/create-vite/template-svelte-ts/tsconfig.json @@ -13,7 +13,8 @@ * of JS in `.svelte` files. */ "allowJs": true, - "checkJs": true + "checkJs": true, + "isolatedModules": true }, "include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"], "references": [{ "path": "./tsconfig.node.json" }] diff --git a/packages/create-vite/template-vanilla-ts/tsconfig.json b/packages/create-vite/template-vanilla-ts/tsconfig.json index 1885c8f9b00106..05f80b91398b98 100644 --- a/packages/create-vite/template-vanilla-ts/tsconfig.json +++ b/packages/create-vite/template-vanilla-ts/tsconfig.json @@ -8,6 +8,7 @@ "strict": true, "sourceMap": true, "resolveJsonModule": true, + "isolatedModules": true, "esModuleInterop": true, "noEmit": true, "noUnusedLocals": true, From 7e6a2c8f7d140186576b9492639f462b3eb99e12 Mon Sep 17 00:00:00 2001 From: patak-dev Date: Tue, 12 Apr 2022 14:54:15 +0200 Subject: [PATCH 68/93] chore: revert removed line in #7698 --- packages/vite/src/node/plugins/esbuild.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/vite/src/node/plugins/esbuild.ts b/packages/vite/src/node/plugins/esbuild.ts index c982b4e61f30c8..9e8bae24424d76 100644 --- a/packages/vite/src/node/plugins/esbuild.ts +++ b/packages/vite/src/node/plugins/esbuild.ts @@ -102,6 +102,7 @@ export async function transformWithEsbuild( } tsconfigRaw = { + ...tsconfigRaw, compilerOptions: { ...compilerOptionsForFile, ...tsconfigRaw?.compilerOptions From 88581807cce75bbb104ef4c1cb3dd483b748d3fd Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Tue, 12 Apr 2022 21:52:50 +0800 Subject: [PATCH 69/93] perf(css): hoist at rules with regex (#7691) --- .../src/node/__tests__/plugins/css.spec.ts | 36 +++++++++++++- packages/vite/src/node/plugins/css.ts | 48 ++++++++----------- 2 files changed, 55 insertions(+), 29 deletions(-) diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index 539ec2f1af1810..9b652a563ccb0a 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -1,4 +1,4 @@ -import { cssUrlRE, cssPlugin } from '../../plugins/css' +import { cssUrlRE, cssPlugin, hoistAtRules } from '../../plugins/css' import { resolveConfig } from '../../config' import fs from 'fs' import path from 'path' @@ -114,3 +114,37 @@ describe('css path resolutions', () => { mockFs.mockReset() }) }) + +describe('hoist @ rules', () => { + test('hoist @import', async () => { + const css = `.foo{color:red;}@import "bla";` + const result = await hoistAtRules(css) + expect(result).toBe(`@import "bla";.foo{color:red;}`) + }) + + test('hoist @import with semicolon in quotes', async () => { + const css = `.foo{color:red;}@import "bla;bar";` + const result = await hoistAtRules(css) + expect(result).toBe(`@import "bla;bar";.foo{color:red;}`) + }) + + test('hoist @charset', async () => { + const css = `.foo{color:red;}@charset "utf-8";` + const result = await hoistAtRules(css) + expect(result).toBe(`@charset "utf-8";.foo{color:red;}`) + }) + + test('hoist one @charset only', async () => { + const css = `.foo{color:red;}@charset "utf-8";@charset "utf-8";` + const result = await hoistAtRules(css) + expect(result).toBe(`@charset "utf-8";.foo{color:red;}`) + }) + + test('hoist @import and @charset', async () => { + const css = `.foo{color:red;}@import "bla";@charset "utf-8";.bar{color:grren;}@import "baz";` + const result = await hoistAtRules(css) + expect(result).toBe( + `@charset "utf-8";@import "bla";@import "baz";.foo{color:red;}.bar{color:grren;}` + ) + }) +}) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index adef254950c5e5..08bdfbeed4e616 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -1106,36 +1106,28 @@ async function minifyCSS(css: string, config: ResolvedConfig) { return code } -// #1845 -// CSS @import can only appear at top of the file. We need to hoist all @import -// to top when multiple files are concatenated. -// #6333 -// CSS @charset must be the top-first in the file, hoist to top too -async function hoistAtRules(css: string) { - const postcss = await import('postcss') - return (await postcss.default([AtRuleHoistPlugin]).process(css)).css -} - -const AtRuleHoistPlugin: PostCSS.PluginCreator = () => { - return { - postcssPlugin: 'vite-hoist-at-rules', - Once(root) { - const imports: PostCSS.AtRule[] = [] - let charset: PostCSS.AtRule | undefined - root.walkAtRules((rule) => { - if (rule.name === 'import') { - // record in reverse so that can simply prepend to preserve order - imports.unshift(rule) - } else if (!charset && rule.name === 'charset') { - charset = rule - } - }) - imports.forEach((i) => root.prepend(i)) - if (charset) root.prepend(charset) +export async function hoistAtRules(css: string) { + const s = new MagicString(css) + // #1845 + // CSS @import can only appear at top of the file. We need to hoist all @import + // to top when multiple files are concatenated. + // match until semicolon that's not in quotes + s.replace(/@import\s*(?:"[^"]*"|'[^']*'|[^;]*).*?;/gm, (match) => { + s.appendLeft(0, match) + return '' + }) + // #6333 + // CSS @charset must be the top-first in the file, hoist the first to top + let foundCharset = false + s.replace(/@charset\s*(?:"[^"]*"|'[^']*'|[^;]*).*?;/gm, (match) => { + if (!foundCharset) { + s.prepend(match) + foundCharset = true } - } + return '' + }) + return s.toString() } -AtRuleHoistPlugin.postcss = true // Preprocessor support. This logic is largely replicated from @vue/compiler-sfc From 23fdef1dec68ff5552f140659e83a18dc8b0b060 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Tue, 12 Apr 2022 23:23:44 +0800 Subject: [PATCH 70/93] chore: type unknown env as any (#7702) --- docs/guide/env-and-mode.md | 2 +- packages/vite/types/importMeta.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guide/env-and-mode.md b/docs/guide/env-and-mode.md index 1649feda8c7501..b2b1264e85a8e4 100644 --- a/docs/guide/env-and-mode.md +++ b/docs/guide/env-and-mode.md @@ -42,7 +42,7 @@ In addition, environment variables that already exist when Vite is executed have `.env` files are loaded at the start of Vite. Restart the server after making changes. ::: -Loaded env variables are also exposed to your client source code via `import.meta.env`. +Loaded env variables are also exposed to your client source code via `import.meta.env` as strings. To prevent accidentally leaking env variables to the client, only variables prefixed with `VITE_` are exposed to your Vite-processed code. e.g. the following file: diff --git a/packages/vite/types/importMeta.d.ts b/packages/vite/types/importMeta.d.ts index 9b57fd120a7ba9..900b975d37d6ad 100644 --- a/packages/vite/types/importMeta.d.ts +++ b/packages/vite/types/importMeta.d.ts @@ -36,7 +36,7 @@ interface ImportMeta { } interface ImportMetaEnv { - [key: string]: string | boolean | undefined + [key: string]: any BASE_URL: string MODE: string DEV: boolean From 7ddbf96ae11bf0eeef97ffc00dcf5ac4c561cc20 Mon Sep 17 00:00:00 2001 From: yoho Date: Tue, 12 Apr 2022 23:25:37 +0800 Subject: [PATCH 71/93] feat: explicit the word boundary (#6876) --- .../assets/__tests__/assets.spec.ts | 7 +++++++ packages/playground/assets/index.html | 19 +++++++++++++++++ packages/vite/src/node/plugins/html.ts | 21 ++++++++++++------- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/packages/playground/assets/__tests__/assets.spec.ts b/packages/playground/assets/__tests__/assets.spec.ts index e08de24265e24a..75c0e57952db24 100644 --- a/packages/playground/assets/__tests__/assets.spec.ts +++ b/packages/playground/assets/__tests__/assets.spec.ts @@ -307,3 +307,10 @@ if (!isBuild) { await untilUpdated(() => getColor('.import-css'), 'rgb(0, 255, 136)') }) } + +test('html import word boundary', async () => { + expect(await page.textContent('.obj-import-express')).toMatch( + 'ignore object import prop' + ) + expect(await page.textContent('.string-import-express')).toMatch('no load') +}) diff --git a/packages/playground/assets/index.html b/packages/playground/assets/index.html index b0ec76f5483b6f..6678a2da7c2106 100644 --- a/packages/playground/assets/index.html +++ b/packages/playground/assets/index.html @@ -176,9 +176,28 @@

new URL(`non-existent`, import.meta.url)

simple script tag import-expression

+ +

url in style tag

url

diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 25ad91582140c3..5c86b6c0ac6073 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -35,6 +35,7 @@ import type { TextNode } from '@vue/compiler-dom' import { NodeTypes } from '@vue/compiler-dom' +import { emptyString } from '../cleanString' interface ScriptAssetsUrl { start: number @@ -44,8 +45,9 @@ interface ScriptAssetsUrl { const htmlProxyRE = /\?html-proxy=?[&inline\-css]*&index=(\d+)\.(js|css)$/ const inlineCSSRE = /__VITE_INLINE_CSS__([^_]+_\d+)__/g +// Do not allow preceding '.', but do allow preceding '...' for spread operations +const inlineImportRE = /(? htmlProxyRE.test(id) @@ -303,14 +305,19 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { } } else if (node.children.length) { const scriptNode = node.children.pop()! as TextNode - const code = scriptNode.content + const cleanCode = emptyString(scriptNode.content) + let match: RegExpExecArray | null - while ((match = inlineImportRE.exec(code))) { - const { 0: full, 1: url, index } = match - const startUrl = full.indexOf(url) - const start = scriptNode.loc.start.offset + index + startUrl + 1 + while ((match = inlineImportRE.exec(cleanCode))) { + const { 1: url, index } = match + const startUrl = cleanCode.indexOf(url, index) + const start = startUrl + 1 const end = start + url.length - 2 - scriptUrls.push({ start, end, url: url.slice(1, -1) }) + scriptUrls.push({ + start: start + scriptNode.loc.start.offset, + end: end + scriptNode.loc.start.offset, + url: scriptNode.content.slice(start, end) + }) } } } From 83d32d965e3abd78fe390e347923e68dfb6de773 Mon Sep 17 00:00:00 2001 From: Rongjian Zhang Date: Wed, 13 Apr 2022 02:50:19 +0800 Subject: [PATCH 72/93] fix: default value of assetsDir option (#7703) --- packages/vite/src/node/cli.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vite/src/node/cli.ts b/packages/vite/src/node/cli.ts index 9cec6ebd9cfd68..89412a825e9fc1 100644 --- a/packages/vite/src/node/cli.ts +++ b/packages/vite/src/node/cli.ts @@ -130,7 +130,7 @@ cli .option('--outDir ', `[string] output directory (default: dist)`) .option( '--assetsDir ', - `[string] directory under outDir to place assets in (default: _assets)` + `[string] directory under outDir to place assets in (default: assets)` ) .option( '--assetsInlineLimit ', From 48e038cc53d609120ffcb0b04c2a6e24cfdebb7b Mon Sep 17 00:00:00 2001 From: patak Date: Wed, 13 Apr 2022 06:34:32 +0200 Subject: [PATCH 73/93] feat: optimizeDeps.disabled (#7646) --- packages/playground/vue-jsx/vite.config.js | 3 ++- packages/vite/src/node/config.ts | 15 ++++++++++----- packages/vite/src/node/optimizer/index.ts | 6 ++++++ packages/vite/src/node/server/index.ts | 10 ++++++++-- 4 files changed, 26 insertions(+), 8 deletions(-) diff --git a/packages/playground/vue-jsx/vite.config.js b/packages/playground/vue-jsx/vite.config.js index d6eb84e05f4e4a..4c7370a0ce4787 100644 --- a/packages/playground/vue-jsx/vite.config.js +++ b/packages/playground/vue-jsx/vite.config.js @@ -35,5 +35,6 @@ export default defineComponent(() => { build: { // to make tests faster minify: false - } + }, + optimizeDeps: false } diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index 9910cbb3a8b004..b02ac6e496593e 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -145,8 +145,10 @@ export interface UserConfig { preview?: PreviewOptions /** * Dep optimization options + * + * false disables optimization completely (experimental) */ - optimizeDeps?: DepOptimizationOptions + optimizeDeps?: DepOptimizationOptions | false /** * SSR specific options * @alpha @@ -463,6 +465,8 @@ export async function resolveConfig( const server = resolveServerOptions(resolvedRoot, config.server) + const optimizeDeps = config.optimizeDeps || {} + const resolved: ResolvedConfig = { ...config, configFile: configFile ? normalizePath(configFile) : undefined, @@ -497,11 +501,12 @@ export async function resolveConfig( packageCache: new Map(), createResolver, optimizeDeps: { - ...config.optimizeDeps, + disabled: config.optimizeDeps === false, + ...optimizeDeps, esbuildOptions: { - keepNames: config.optimizeDeps?.keepNames, + keepNames: optimizeDeps.keepNames, preserveSymlinks: config.resolve?.preserveSymlinks, - ...config.optimizeDeps?.esbuildOptions + ...optimizeDeps.esbuildOptions } }, worker: resolvedWorkerOptions @@ -605,7 +610,7 @@ export async function resolveConfig( } }) - if (config.optimizeDeps?.keepNames) { + if (optimizeDeps.keepNames) { logDeprecationWarning( 'optimizeDeps.keepNames', 'Use "optimizeDeps.esbuildOptions.keepNames" instead.' diff --git a/packages/vite/src/node/optimizer/index.ts b/packages/vite/src/node/optimizer/index.ts index 88c41801938b98..13c322610cf493 100644 --- a/packages/vite/src/node/optimizer/index.ts +++ b/packages/vite/src/node/optimizer/index.ts @@ -101,6 +101,12 @@ export interface DepOptimizationOptions { * @experimental */ extensions?: string[] + /** + * Disables dependencies optimizations + * @default false + * @experimental + */ + disabled?: boolean } export interface DepOptimizationResult { diff --git a/packages/vite/src/node/server/index.ts b/packages/vite/src/node/server/index.ts index de80ac1147ff0f..bf13ba683a9b93 100644 --- a/packages/vite/src/node/server/index.ts +++ b/packages/vite/src/node/server/index.ts @@ -571,6 +571,12 @@ export async function createServer( // error handler middlewares.use(errorMiddleware(server, !!middlewareMode)) + const initOptimizer = () => { + if (!config.optimizeDeps.disabled) { + server._optimizedDeps = createOptimizedDeps(server) + } + } + if (!middlewareMode && httpServer) { let isOptimized = false // overwrite listen to init optimizer before server start @@ -579,7 +585,7 @@ export async function createServer( if (!isOptimized) { try { await container.buildStart({}) - server._optimizedDeps = createOptimizedDeps(server) + initOptimizer() isOptimized = true } catch (e) { httpServer.emit('error', e) @@ -590,7 +596,7 @@ export async function createServer( }) as any } else { await container.buildStart({}) - server._optimizedDeps = createOptimizedDeps(server) + initOptimizer() } return server From d6830e3d70b693945113b7504b25be8a18b27815 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Wed, 13 Apr 2022 12:36:35 +0800 Subject: [PATCH 74/93] fix(ssr): properly transform export default with expressions (#7705) --- .../node/ssr/__tests__/ssrTransform.spec.ts | 23 +++++++++++++++++++ packages/vite/src/node/ssr/ssrTransform.ts | 7 +++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts index e086365ee25f16..a5f915edea97fd 100644 --- a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts +++ b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts @@ -657,3 +657,26 @@ export function fn1() { " `) }) + +// https://github.com/vitest-dev/vitest/issues/1141 +test('export default expression', async () => { + // esbuild transform result of following TS code + // export default function getRandom() { + // return Math.random() + // } + const code = ` +export default (function getRandom() { + return Math.random(); +}); +`.trim() + + expect((await ssrTransform(code, null, null)).code).toMatchInlineSnapshot(` + "__vite_ssr_exports__.default = (function getRandom() { + return Math.random(); + });" + `) + + expect( + (await ssrTransform(`export default (class A {});`, null, null)).code + ).toMatchInlineSnapshot(`"__vite_ssr_exports__.default = (class A {});"`) +}) diff --git a/packages/vite/src/node/ssr/ssrTransform.ts b/packages/vite/src/node/ssr/ssrTransform.ts index 56b75f8dd14913..79ccd25f9ca8ff 100644 --- a/packages/vite/src/node/ssr/ssrTransform.ts +++ b/packages/vite/src/node/ssr/ssrTransform.ts @@ -143,7 +143,12 @@ export async function ssrTransform( // default export if (node.type === 'ExportDefaultDeclaration') { - if ('id' in node.declaration && node.declaration.id) { + const expressionTypes = ['FunctionExpression', 'ClassExpression'] + if ( + 'id' in node.declaration && + node.declaration.id && + !expressionTypes.includes(node.declaration.type) + ) { // named hoistable/class exports // export default function foo() {} // export default class A {} From ba9a1ffe9ea5414d6e232a7ded9d341014a4e726 Mon Sep 17 00:00:00 2001 From: patak Date: Wed, 13 Apr 2022 15:32:15 +0200 Subject: [PATCH 75/93] fix: revert optimizeDeps false, keep optimizedDeps.disabled (#7715) --- packages/playground/vue-jsx/vite.config.js | 4 +++- packages/vite/src/node/config.ts | 5 +---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/playground/vue-jsx/vite.config.js b/packages/playground/vue-jsx/vite.config.js index 4c7370a0ce4787..2f4ea255c95094 100644 --- a/packages/playground/vue-jsx/vite.config.js +++ b/packages/playground/vue-jsx/vite.config.js @@ -36,5 +36,7 @@ export default defineComponent(() => { // to make tests faster minify: false }, - optimizeDeps: false + optimizeDeps: { + disabled: true + } } diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index b02ac6e496593e..f633d1158bfa95 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -145,10 +145,8 @@ export interface UserConfig { preview?: PreviewOptions /** * Dep optimization options - * - * false disables optimization completely (experimental) */ - optimizeDeps?: DepOptimizationOptions | false + optimizeDeps?: DepOptimizationOptions /** * SSR specific options * @alpha @@ -501,7 +499,6 @@ export async function resolveConfig( packageCache: new Map(), createResolver, optimizeDeps: { - disabled: config.optimizeDeps === false, ...optimizeDeps, esbuildOptions: { keepNames: optimizeDeps.keepNames, From f699afb9531201dc24566821fcab55d3e70a2708 Mon Sep 17 00:00:00 2001 From: patak-dev Date: Wed, 13 Apr 2022 15:47:32 +0200 Subject: [PATCH 76/93] release: v2.9.2 --- packages/vite/CHANGELOG.md | 32 ++++++++++++++++++++++++++++++++ packages/vite/package.json | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/packages/vite/CHANGELOG.md b/packages/vite/CHANGELOG.md index 0f91a004602caa..b011910c8615cc 100644 --- a/packages/vite/CHANGELOG.md +++ b/packages/vite/CHANGELOG.md @@ -1,3 +1,35 @@ +## 2.9.2 (2022-04-13) + +* fix: `$ vite preview` 404 handling (#7665) ([66b6dc5](https://github.com/vitejs/vite/commit/66b6dc5)), closes [#7665](https://github.com/vitejs/vite/issues/7665) +* fix: build should also respect esbuild=false config (#7602) ([2dc0e80](https://github.com/vitejs/vite/commit/2dc0e80)), closes [#7602](https://github.com/vitejs/vite/issues/7602) +* fix: default value of assetsDir option (#7703) ([83d32d9](https://github.com/vitejs/vite/commit/83d32d9)), closes [#7703](https://github.com/vitejs/vite/issues/7703) +* fix: detect env hmr (#7595) ([212d454](https://github.com/vitejs/vite/commit/212d454)), closes [#7595](https://github.com/vitejs/vite/issues/7595) +* fix: EACCES permission denied due to resolve new paths default (#7612) ([1dd019f](https://github.com/vitejs/vite/commit/1dd019f)), closes [#7612](https://github.com/vitejs/vite/issues/7612) +* fix: fix HMR propagation when imports not analyzed (#7561) ([57e7914](https://github.com/vitejs/vite/commit/57e7914)), closes [#7561](https://github.com/vitejs/vite/issues/7561) +* fix: nested comments and strings, new regexp utils (#7650) ([93900f0](https://github.com/vitejs/vite/commit/93900f0)), closes [#7650](https://github.com/vitejs/vite/issues/7650) +* fix: revert optimizeDeps false, keep optimizedDeps.disabled (#7715) ([ba9a1ff](https://github.com/vitejs/vite/commit/ba9a1ff)), closes [#7715](https://github.com/vitejs/vite/issues/7715) +* fix: update watch mode (#7132) ([9ed1672](https://github.com/vitejs/vite/commit/9ed1672)), closes [#7132](https://github.com/vitejs/vite/issues/7132) +* fix: update ws types (#7605) ([b620587](https://github.com/vitejs/vite/commit/b620587)), closes [#7605](https://github.com/vitejs/vite/issues/7605) +* fix: use correct proxy config in preview (#7604) ([cf59005](https://github.com/vitejs/vite/commit/cf59005)), closes [#7604](https://github.com/vitejs/vite/issues/7604) +* fix(css): hoist charset (#7678) ([29e622c](https://github.com/vitejs/vite/commit/29e622c)), closes [#7678](https://github.com/vitejs/vite/issues/7678) +* fix(css): include inline css module in bundle (#7591) ([45b9273](https://github.com/vitejs/vite/commit/45b9273)), closes [#7591](https://github.com/vitejs/vite/issues/7591) +* fix(deps): update all non-major dependencies (#7668) ([485263c](https://github.com/vitejs/vite/commit/485263c)), closes [#7668](https://github.com/vitejs/vite/issues/7668) +* fix(less): handles rewriting relative paths passed Less's `data-uri` function. (#7400) ([08e39b7](https://github.com/vitejs/vite/commit/08e39b7)), closes [#7400](https://github.com/vitejs/vite/issues/7400) +* fix(resolver): skip known ESM entries when resolving a `require` call (#7582) ([5d6ea8e](https://github.com/vitejs/vite/commit/5d6ea8e)), closes [#7582](https://github.com/vitejs/vite/issues/7582) +* fix(ssr): properly transform export default with expressions (#7705) ([d6830e3](https://github.com/vitejs/vite/commit/d6830e3)), closes [#7705](https://github.com/vitejs/vite/issues/7705) +* feat: clean string module lex string template (#7667) ([dfce283](https://github.com/vitejs/vite/commit/dfce283)), closes [#7667](https://github.com/vitejs/vite/issues/7667) +* feat: explicit the word boundary (#6876) ([7ddbf96](https://github.com/vitejs/vite/commit/7ddbf96)), closes [#6876](https://github.com/vitejs/vite/issues/6876) +* feat: optimizeDeps.disabled (#7646) ([48e038c](https://github.com/vitejs/vite/commit/48e038c)), closes [#7646](https://github.com/vitejs/vite/issues/7646) +* chore: fix term cases (#7553) ([c296130](https://github.com/vitejs/vite/commit/c296130)), closes [#7553](https://github.com/vitejs/vite/issues/7553) +* chore: revert removed line in #7698 ([7e6a2c8](https://github.com/vitejs/vite/commit/7e6a2c8)), closes [#7698](https://github.com/vitejs/vite/issues/7698) +* chore: type unknown env as any (#7702) ([23fdef1](https://github.com/vitejs/vite/commit/23fdef1)), closes [#7702](https://github.com/vitejs/vite/issues/7702) +* chore(deps): update all non-major dependencies (#7603) ([fc51a15](https://github.com/vitejs/vite/commit/fc51a15)), closes [#7603](https://github.com/vitejs/vite/issues/7603) +* perf(css): hoist at rules with regex (#7691) ([8858180](https://github.com/vitejs/vite/commit/8858180)), closes [#7691](https://github.com/vitejs/vite/issues/7691) +* refactor: esbuild handles `target` and `useDefineForClassFields` (#7698) ([0c928aa](https://github.com/vitejs/vite/commit/0c928aa)), closes [#7698](https://github.com/vitejs/vite/issues/7698) +* docs: update release notes (#7563) ([a74bd7b](https://github.com/vitejs/vite/commit/a74bd7b)), closes [#7563](https://github.com/vitejs/vite/issues/7563) + + + ## 2.9.1 (2022-03-31) * fix: allow port 0 to be provided to server (#7530) ([173e4c9](https://github.com/vitejs/vite/commit/173e4c9)), closes [#7530](https://github.com/vitejs/vite/issues/7530) diff --git a/packages/vite/package.json b/packages/vite/package.json index adf73956a5c33a..1a749f662be43a 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -1,6 +1,6 @@ { "name": "vite", - "version": "2.9.1", + "version": "2.9.2", "license": "MIT", "author": "Evan You", "description": "Native-ESM powered web dev build tool", From 720e73c5f507eb3c142c53e4bc2e3d025e9a9f8a Mon Sep 17 00:00:00 2001 From: patak-dev Date: Wed, 13 Apr 2022 15:49:07 +0200 Subject: [PATCH 77/93] release: plugin-vue-jsx@1.3.10 --- packages/plugin-vue-jsx/CHANGELOG.md | 6 ++++++ packages/plugin-vue-jsx/package.json | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/plugin-vue-jsx/CHANGELOG.md b/packages/plugin-vue-jsx/CHANGELOG.md index 3a1b9e681b45ea..94effd95f316b6 100644 --- a/packages/plugin-vue-jsx/CHANGELOG.md +++ b/packages/plugin-vue-jsx/CHANGELOG.md @@ -1,3 +1,9 @@ +## 1.3.10 (2022-04-13) + +* fix(deps): update all non-major dependencies (#7668) ([485263c](https://github.com/vitejs/vite/commit/485263c)), closes [#7668](https://github.com/vitejs/vite/issues/7668) + + + ## 1.3.9 (2022-03-30) * fix(deps): update all non-major dependencies (#7392) ([b63fc3b](https://github.com/vitejs/vite/commit/b63fc3b)), closes [#7392](https://github.com/vitejs/vite/issues/7392) diff --git a/packages/plugin-vue-jsx/package.json b/packages/plugin-vue-jsx/package.json index d8057b91f8ab24..151d0a71ce648c 100644 --- a/packages/plugin-vue-jsx/package.json +++ b/packages/plugin-vue-jsx/package.json @@ -1,6 +1,6 @@ { "name": "@vitejs/plugin-vue-jsx", - "version": "1.3.9", + "version": "1.3.10", "license": "MIT", "author": "Evan You", "files": [ From 070321bd6d38cee05e9ab4a96fc3a06d07f699ea Mon Sep 17 00:00:00 2001 From: patak-dev Date: Wed, 13 Apr 2022 15:51:10 +0200 Subject: [PATCH 78/93] release: plugin-react@1.3.1 --- packages/plugin-react/CHANGELOG.md | 8 ++++++++ packages/plugin-react/package.json | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/plugin-react/CHANGELOG.md b/packages/plugin-react/CHANGELOG.md index c05c0989d6beb4..958c8270b6f221 100644 --- a/packages/plugin-react/CHANGELOG.md +++ b/packages/plugin-react/CHANGELOG.md @@ -1,3 +1,11 @@ +## 1.3.1 (2022-04-13) + +* fix(deps): update all non-major dependencies (#7668) ([485263c](https://github.com/vitejs/vite/commit/485263c)), closes [#7668](https://github.com/vitejs/vite/issues/7668) +* chore: fix term cases (#7553) ([c296130](https://github.com/vitejs/vite/commit/c296130)), closes [#7553](https://github.com/vitejs/vite/issues/7553) +* chore(deps): update all non-major dependencies (#7603) ([fc51a15](https://github.com/vitejs/vite/commit/fc51a15)), closes [#7603](https://github.com/vitejs/vite/issues/7603) + + + ## 1.3.0 (2022-03-30) * feat(plugin-react): adding jsxPure option (#7088) ([d451435](https://github.com/vitejs/vite/commit/d451435)), closes [#7088](https://github.com/vitejs/vite/issues/7088) diff --git a/packages/plugin-react/package.json b/packages/plugin-react/package.json index e7fc9544120b11..6608eef784fa22 100644 --- a/packages/plugin-react/package.json +++ b/packages/plugin-react/package.json @@ -1,6 +1,6 @@ { "name": "@vitejs/plugin-react", - "version": "1.3.0", + "version": "1.3.1", "license": "MIT", "author": "Evan You", "contributors": [ From e7ea19ad2204a12fadc37f5ecd6ab0eea2d23373 Mon Sep 17 00:00:00 2001 From: patak-dev Date: Wed, 13 Apr 2022 15:52:05 +0200 Subject: [PATCH 79/93] release: plugin-legacy@1.8.1 --- packages/plugin-legacy/CHANGELOG.md | 7 +++++++ packages/plugin-legacy/package.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/plugin-legacy/CHANGELOG.md b/packages/plugin-legacy/CHANGELOG.md index ced87d2efd665c..5c00212554ce8c 100644 --- a/packages/plugin-legacy/CHANGELOG.md +++ b/packages/plugin-legacy/CHANGELOG.md @@ -1,3 +1,10 @@ +## 1.8.1 (2022-04-13) + +* fix(deps): update all non-major dependencies (#7668) ([485263c](https://github.com/vitejs/vite/commit/485263c)), closes [#7668](https://github.com/vitejs/vite/issues/7668) +* docs(legacy): note works in build only (#7596) ([f26b14a](https://github.com/vitejs/vite/commit/f26b14a)), closes [#7596](https://github.com/vitejs/vite/issues/7596) + + + ## 1.8.0 (2022-03-30) * fix(deps): update all non-major dependencies (#6782) ([e38be3e](https://github.com/vitejs/vite/commit/e38be3e)), closes [#6782](https://github.com/vitejs/vite/issues/6782) diff --git a/packages/plugin-legacy/package.json b/packages/plugin-legacy/package.json index eb974d790f1e71..4c6783abc04bc8 100644 --- a/packages/plugin-legacy/package.json +++ b/packages/plugin-legacy/package.json @@ -1,6 +1,6 @@ { "name": "@vitejs/plugin-legacy", - "version": "1.8.0", + "version": "1.8.1", "license": "MIT", "author": "Evan You", "files": [ From adacaba1cf03256cf18a3494b4d7b053605d4a46 Mon Sep 17 00:00:00 2001 From: patak-dev Date: Wed, 13 Apr 2022 15:53:05 +0200 Subject: [PATCH 80/93] release: create-vite@2.9.1 --- packages/create-vite/CHANGELOG.md | 10 ++++++++++ packages/create-vite/package.json | 2 +- packages/create-vite/template-lit-ts/package.json | 2 +- packages/create-vite/template-lit/package.json | 2 +- packages/create-vite/template-preact-ts/package.json | 2 +- packages/create-vite/template-preact/package.json | 2 +- packages/create-vite/template-react-ts/package.json | 2 +- packages/create-vite/template-react/package.json | 2 +- packages/create-vite/template-svelte-ts/package.json | 2 +- packages/create-vite/template-svelte/package.json | 2 +- packages/create-vite/template-vanilla-ts/package.json | 2 +- packages/create-vite/template-vanilla/package.json | 2 +- packages/create-vite/template-vue-ts/package.json | 4 ++-- packages/create-vite/template-vue/package.json | 4 ++-- 14 files changed, 25 insertions(+), 15 deletions(-) diff --git a/packages/create-vite/CHANGELOG.md b/packages/create-vite/CHANGELOG.md index bf69fae7e535ad..cac7f2664ecaed 100644 --- a/packages/create-vite/CHANGELOG.md +++ b/packages/create-vite/CHANGELOG.md @@ -1,3 +1,13 @@ +## 2.9.1 (2022-04-13) + +* chore: fix term cases (#7553) ([c296130](https://github.com/vitejs/vite/commit/c296130)), closes [#7553](https://github.com/vitejs/vite/issues/7553) +* chore: update @types/react version (#7655) ([eb57627](https://github.com/vitejs/vite/commit/eb57627)), closes [#7655](https://github.com/vitejs/vite/issues/7655) +* chore: update vue template setup api doc url (#7628) ([4433df4](https://github.com/vitejs/vite/commit/4433df4)), closes [#7628](https://github.com/vitejs/vite/issues/7628) +* chore(create-vite-app): upgrade react to 18 (#7597) ([8b21029](https://github.com/vitejs/vite/commit/8b21029)), closes [#7597](https://github.com/vitejs/vite/issues/7597) +* chore(create-vite): add isolatedModules (#7697) ([8f28350](https://github.com/vitejs/vite/commit/8f28350)), closes [#7697](https://github.com/vitejs/vite/issues/7697) + + + ## 2.9.0 (2022-03-30) * chore: add isolatedModules to create-vite > template-vue-ts > tsconfig (#7304) ([21990ea](https://github.com/vitejs/vite/commit/21990ea)), closes [#7304](https://github.com/vitejs/vite/issues/7304) diff --git a/packages/create-vite/package.json b/packages/create-vite/package.json index 72955697360477..dcaf3962c987cf 100644 --- a/packages/create-vite/package.json +++ b/packages/create-vite/package.json @@ -1,6 +1,6 @@ { "name": "create-vite", - "version": "2.9.0", + "version": "2.9.1", "license": "MIT", "author": "Evan You", "bin": { diff --git a/packages/create-vite/template-lit-ts/package.json b/packages/create-vite/template-lit-ts/package.json index 061def321a22e6..6a928d05bb9e84 100644 --- a/packages/create-vite/template-lit-ts/package.json +++ b/packages/create-vite/template-lit-ts/package.json @@ -19,7 +19,7 @@ "lit": "^2.0.2" }, "devDependencies": { - "vite": "^2.9.0", + "vite": "^2.9.2", "typescript": "^4.5.4" } } diff --git a/packages/create-vite/template-lit/package.json b/packages/create-vite/template-lit/package.json index 89f4fee41576c6..7889bec19759ff 100644 --- a/packages/create-vite/template-lit/package.json +++ b/packages/create-vite/template-lit/package.json @@ -17,6 +17,6 @@ "lit": "^2.0.2" }, "devDependencies": { - "vite": "^2.9.0" + "vite": "^2.9.2" } } diff --git a/packages/create-vite/template-preact-ts/package.json b/packages/create-vite/template-preact-ts/package.json index dfa6659650c5ae..aaf8aea0372e52 100644 --- a/packages/create-vite/template-preact-ts/package.json +++ b/packages/create-vite/template-preact-ts/package.json @@ -13,6 +13,6 @@ "devDependencies": { "@preact/preset-vite": "^2.1.5", "typescript": "^4.5.4", - "vite": "^2.9.0" + "vite": "^2.9.2" } } diff --git a/packages/create-vite/template-preact/package.json b/packages/create-vite/template-preact/package.json index 02528128f6442e..19198fc9e66d67 100644 --- a/packages/create-vite/template-preact/package.json +++ b/packages/create-vite/template-preact/package.json @@ -12,6 +12,6 @@ }, "devDependencies": { "@preact/preset-vite": "^2.1.5", - "vite": "^2.9.0" + "vite": "^2.9.2" } } diff --git a/packages/create-vite/template-react-ts/package.json b/packages/create-vite/template-react-ts/package.json index 69274929dd903d..ea89f3a68d8c45 100644 --- a/packages/create-vite/template-react-ts/package.json +++ b/packages/create-vite/template-react-ts/package.json @@ -16,6 +16,6 @@ "@types/react-dom": "^18.0.0", "@vitejs/plugin-react": "^1.3.0", "typescript": "^4.6.3", - "vite": "^2.9.1" + "vite": "^2.9.2" } } diff --git a/packages/create-vite/template-react/package.json b/packages/create-vite/template-react/package.json index 4f443aefcb3cdb..f81b751dc8f30c 100644 --- a/packages/create-vite/template-react/package.json +++ b/packages/create-vite/template-react/package.json @@ -15,6 +15,6 @@ "@types/react": "^18.0.0", "@types/react-dom": "^18.0.0", "@vitejs/plugin-react": "^1.3.0", - "vite": "^2.9.1" + "vite": "^2.9.2" } } diff --git a/packages/create-vite/template-svelte-ts/package.json b/packages/create-vite/template-svelte-ts/package.json index 32e080146e0b6e..bed1e3caedeef0 100644 --- a/packages/create-vite/template-svelte-ts/package.json +++ b/packages/create-vite/template-svelte-ts/package.json @@ -17,6 +17,6 @@ "svelte-preprocess": "^4.9.8", "tslib": "^2.3.1", "typescript": "^4.5.4", - "vite": "^2.9.0" + "vite": "^2.9.2" } } diff --git a/packages/create-vite/template-svelte/package.json b/packages/create-vite/template-svelte/package.json index da049c170731b9..661a174421d156 100644 --- a/packages/create-vite/template-svelte/package.json +++ b/packages/create-vite/template-svelte/package.json @@ -11,6 +11,6 @@ "devDependencies": { "@sveltejs/vite-plugin-svelte": "^1.0.0-next.30", "svelte": "^3.44.0", - "vite": "^2.9.0" + "vite": "^2.9.2" } } diff --git a/packages/create-vite/template-vanilla-ts/package.json b/packages/create-vite/template-vanilla-ts/package.json index 8dd7a0bb800909..adedc3d4e83a65 100644 --- a/packages/create-vite/template-vanilla-ts/package.json +++ b/packages/create-vite/template-vanilla-ts/package.json @@ -9,6 +9,6 @@ }, "devDependencies": { "typescript": "^4.5.4", - "vite": "^2.9.0" + "vite": "^2.9.2" } } diff --git a/packages/create-vite/template-vanilla/package.json b/packages/create-vite/template-vanilla/package.json index ff318e00f14fd1..ee68e7cd13e903 100644 --- a/packages/create-vite/template-vanilla/package.json +++ b/packages/create-vite/template-vanilla/package.json @@ -8,6 +8,6 @@ "preview": "vite preview" }, "devDependencies": { - "vite": "^2.9.0" + "vite": "^2.9.2" } } diff --git a/packages/create-vite/template-vue-ts/package.json b/packages/create-vite/template-vue-ts/package.json index 1d8ff2b3e19d56..2ad29ac0b91725 100644 --- a/packages/create-vite/template-vue-ts/package.json +++ b/packages/create-vite/template-vue-ts/package.json @@ -11,9 +11,9 @@ "vue": "^3.2.25" }, "devDependencies": { - "@vitejs/plugin-vue": "^2.3.0", + "@vitejs/plugin-vue": "^2.3.1", "typescript": "^4.5.4", - "vite": "^2.9.0", + "vite": "^2.9.2", "vue-tsc": "^0.29.8" } } diff --git a/packages/create-vite/template-vue/package.json b/packages/create-vite/template-vue/package.json index 707b664d3dfff7..531986717154ee 100644 --- a/packages/create-vite/template-vue/package.json +++ b/packages/create-vite/template-vue/package.json @@ -11,7 +11,7 @@ "vue": "^3.2.25" }, "devDependencies": { - "@vitejs/plugin-vue": "^2.3.0", - "vite": "^2.9.0" + "@vitejs/plugin-vue": "^2.3.1", + "vite": "^2.9.2" } } From 26862c4b7aabd876ece0197ae9f6404fdfcec408 Mon Sep 17 00:00:00 2001 From: patak Date: Wed, 13 Apr 2022 18:24:18 +0200 Subject: [PATCH 81/93] fix: revert #7665 (#7716) --- packages/vite/src/node/preview.ts | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/packages/vite/src/node/preview.ts b/packages/vite/src/node/preview.ts index 23b905fd01a719..c00f62a9cb8f0c 100644 --- a/packages/vite/src/node/preview.ts +++ b/packages/vite/src/node/preview.ts @@ -1,5 +1,4 @@ import path from 'path' -import fs from 'fs' import sirv from 'sirv' import connect from 'connect' import compression from './server/middlewares/compression' @@ -91,20 +90,11 @@ export async function preview( config.base, sirv(distDir, { etag: true, - dev: true + dev: true, + single: true }) ) - app.use(config.base, (_, res, next) => { - const file = path.join(distDir, './404.html') - if (fs.existsSync(file)) { - res.statusCode = 404 - res.end(fs.readFileSync(file)) - } else { - next() - } - }) - const options = config.preview const hostname = resolveHostname(options.host) const port = options.port ?? 4173 From cb5c3f99bfe8ea1f4b43a1d81030b95bc704720b Mon Sep 17 00:00:00 2001 From: patak-dev Date: Wed, 13 Apr 2022 18:35:02 +0200 Subject: [PATCH 82/93] release: v2.9.3 --- packages/vite/CHANGELOG.md | 6 ++++++ packages/vite/package.json | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/vite/CHANGELOG.md b/packages/vite/CHANGELOG.md index b011910c8615cc..822d801d57537e 100644 --- a/packages/vite/CHANGELOG.md +++ b/packages/vite/CHANGELOG.md @@ -1,3 +1,9 @@ +## 2.9.3 (2022-04-13) + +* fix: revert #7665 (#7716) ([26862c4](https://github.com/vitejs/vite/commit/26862c4)), closes [#7665](https://github.com/vitejs/vite/issues/7665) [#7716](https://github.com/vitejs/vite/issues/7716) + + + ## 2.9.2 (2022-04-13) * fix: `$ vite preview` 404 handling (#7665) ([66b6dc5](https://github.com/vitejs/vite/commit/66b6dc5)), closes [#7665](https://github.com/vitejs/vite/issues/7665) diff --git a/packages/vite/package.json b/packages/vite/package.json index 1a749f662be43a..eeecf5b2160544 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -1,6 +1,6 @@ { "name": "vite", - "version": "2.9.2", + "version": "2.9.3", "license": "MIT", "author": "Evan You", "description": "Native-ESM powered web dev build tool", From a5c2a7803eeed55e023bec464f6b193ed5ddac79 Mon Sep 17 00:00:00 2001 From: Hugo ATTAL Date: Wed, 13 Apr 2022 21:39:46 +0200 Subject: [PATCH 83/93] fix: handle url imports with semicolon (fix #7717) (#7718) --- .../vite/src/node/__tests__/plugins/css.spec.ts | 14 ++++++++++++++ packages/vite/src/node/plugins/css.ts | 11 +++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index 9b652a563ccb0a..078cec2e0f3d77 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -122,6 +122,20 @@ describe('hoist @ rules', () => { expect(result).toBe(`@import "bla";.foo{color:red;}`) }) + test('hoist @import url with semicolon', async () => { + const css = `.foo{color:red;}@import url("bla;bla");` + const result = await hoistAtRules(css) + expect(result).toBe(`@import url("bla;bla");.foo{color:red;}`) + }) + + test('hoist @import url data with semicolon', async () => { + const css = `.foo{color:red;}@import url(data:image/png;base64,iRxVB0);` + const result = await hoistAtRules(css) + expect(result).toBe( + `@import url(data:image/png;base64,iRxVB0);.foo{color:red;}` + ) + }) + test('hoist @import with semicolon in quotes', async () => { const css = `.foo{color:red;}@import "bla;bar";` const result = await hoistAtRules(css) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 08bdfbeed4e616..0a14e091c53637 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -1112,10 +1112,13 @@ export async function hoistAtRules(css: string) { // CSS @import can only appear at top of the file. We need to hoist all @import // to top when multiple files are concatenated. // match until semicolon that's not in quotes - s.replace(/@import\s*(?:"[^"]*"|'[^']*'|[^;]*).*?;/gm, (match) => { - s.appendLeft(0, match) - return '' - }) + s.replace( + /@import\s*(?:url\([^\)]*\)|"[^"]*"|'[^']*'|[^;]*).*?;/gm, + (match) => { + s.appendLeft(0, match) + return '' + } + ) // #6333 // CSS @charset must be the top-first in the file, hoist the first to top let foundCharset = false From 6c27f14997db377c7baa5cc6721a9c3f74964a98 Mon Sep 17 00:00:00 2001 From: patak-dev Date: Wed, 13 Apr 2022 21:52:47 +0200 Subject: [PATCH 84/93] release: v2.9.4 --- packages/vite/CHANGELOG.md | 6 ++++++ packages/vite/package.json | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/vite/CHANGELOG.md b/packages/vite/CHANGELOG.md index 822d801d57537e..8ed8c8cf8ba692 100644 --- a/packages/vite/CHANGELOG.md +++ b/packages/vite/CHANGELOG.md @@ -1,3 +1,9 @@ +## 2.9.4 (2022-04-13) + +* fix: handle url imports with semicolon (fix #7717) (#7718) ([a5c2a78](https://github.com/vitejs/vite/commit/a5c2a78)), closes [#7717](https://github.com/vitejs/vite/issues/7717) [#7718](https://github.com/vitejs/vite/issues/7718) + + + ## 2.9.3 (2022-04-13) * fix: revert #7665 (#7716) ([26862c4](https://github.com/vitejs/vite/commit/26862c4)), closes [#7665](https://github.com/vitejs/vite/issues/7665) [#7716](https://github.com/vitejs/vite/issues/7716) diff --git a/packages/vite/package.json b/packages/vite/package.json index eeecf5b2160544..1ab75ada9c7cd3 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -1,6 +1,6 @@ { "name": "vite", - "version": "2.9.3", + "version": "2.9.4", "license": "MIT", "author": "Evan You", "description": "Native-ESM powered web dev build tool", From c4450757d4c87de671a985714139d17349f905d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Thu, 14 Apr 2022 23:16:14 +0900 Subject: [PATCH 85/93] chore: format css minify esbuild error (#7731) --- packages/vite/src/node/plugins/css.ts | 31 +++++++++++++++++---------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 0a14e091c53637..2f5ab3df58b46a 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -1092,18 +1092,27 @@ async function doImportCSSReplace( } async function minifyCSS(css: string, config: ResolvedConfig) { - const { code, warnings } = await transform(css, { - loader: 'css', - minify: true, - target: config.build.cssTarget || undefined - }) - if (warnings.length) { - const msgs = await formatMessages(warnings, { kind: 'warning' }) - config.logger.warn( - colors.yellow(`warnings when minifying css:\n${msgs.join('\n')}`) - ) + try { + const { code, warnings } = await transform(css, { + loader: 'css', + minify: true, + target: config.build.cssTarget || undefined + }) + if (warnings.length) { + const msgs = await formatMessages(warnings, { kind: 'warning' }) + config.logger.warn( + colors.yellow(`warnings when minifying css:\n${msgs.join('\n')}`) + ) + } + return code + } catch (e) { + if (e.errors) { + const msgs = await formatMessages(e.errors, { kind: 'error' }) + e.frame = '\n' + msgs.join('\n') + e.loc = e.errors[0].location + } + throw e } - return code } export async function hoistAtRules(css: string) { From fa86d69ca54e9a538302c8fcc300c5bfba0ce59f Mon Sep 17 00:00:00 2001 From: patak Date: Thu, 14 Apr 2022 16:40:53 +0200 Subject: [PATCH 86/93] fix: revert #7582, fix #7721 and #7736 (#7737) --- .../resolve/__tests__/resolve.spec.ts | 10 ++------ packages/playground/resolve/index.html | 20 ++++------------ packages/playground/resolve/package.json | 3 +-- .../index.cjs | 8 ------- .../require-pkg-with-esm-entries/index.cjs | 9 ------- .../require-pkg-with-esm-entries/package.json | 9 ------- .../dep.cjs | 0 .../require-pkg-with-module-field/index.cjs | 8 +++++++ .../package.json | 2 +- packages/playground/resolve/vite.config.js | 5 +--- packages/vite/src/node/constants.ts | 15 ------------ packages/vite/src/node/plugins/resolve.ts | 6 ----- pnpm-lock.yaml | 24 +++---------------- 13 files changed, 20 insertions(+), 99 deletions(-) delete mode 100644 packages/playground/resolve/require-pkg-with-browser-and-module-field/index.cjs delete mode 100644 packages/playground/resolve/require-pkg-with-esm-entries/index.cjs delete mode 100644 packages/playground/resolve/require-pkg-with-esm-entries/package.json rename packages/playground/resolve/{require-pkg-with-browser-and-module-field => require-pkg-with-module-field}/dep.cjs (100%) create mode 100644 packages/playground/resolve/require-pkg-with-module-field/index.cjs rename packages/playground/resolve/{require-pkg-with-browser-and-module-field => require-pkg-with-module-field}/package.json (68%) diff --git a/packages/playground/resolve/__tests__/resolve.spec.ts b/packages/playground/resolve/__tests__/resolve.spec.ts index 46f8f6138b39a4..2deb2fab7f8d40 100644 --- a/packages/playground/resolve/__tests__/resolve.spec.ts +++ b/packages/playground/resolve/__tests__/resolve.spec.ts @@ -61,14 +61,8 @@ test('dont add extension to directory name (./dir-with-ext.js/index.js)', async expect(await page.textContent('.dir-with-ext')).toMatch('[success]') }) -test('resolve to the `browser` field instead of `module` when the importer is a `require` call', async () => { - expect( - await page.textContent('.require-pkg-with-browser-and-module-field') - ).toMatch('[success]') -}) - -test('resolve to the `main` field instead of `module` when the importer is a `require` call', async () => { - expect(await page.textContent('.require-pkg-with-esm-entries')).toMatch( +test('do not resolve to the `module` field if the importer is a `require` call', async () => { + expect(await page.textContent('.require-pkg-with-module-field')).toMatch( '[success]' ) }) diff --git a/packages/playground/resolve/index.html b/packages/playground/resolve/index.html index 2478c89b495f49..1920ebb675d24c 100644 --- a/packages/playground/resolve/index.html +++ b/packages/playground/resolve/index.html @@ -58,17 +58,8 @@

Resolve file name containing dot

Browser Field

fail

-

- Resolve to the `browser` field instead of `module` when the importer is a - `require` call -

-

fail

- -

- Resolve to the `main` field instead of `module` when the importer is a - `require` call -

-

fail

+

Don't resolve to the `module` field if the importer is a `require` call

+

fail

CSS Entry

@@ -194,11 +185,8 @@

resolve package that contains # in path

text('.browser', main) } - import { msg as requireBrowserMsg } from 'require-pkg-with-browser-and-module-field' - text('.require-pkg-with-browser-and-module-field', requireBrowserMsg) - - import { msg as requireMainMsg } from 'require-pkg-with-esm-entries' - text('.require-pkg-with-esm-entries', requireMainMsg) + import { msg as requireButWithModuleFieldMsg } from 'require-pkg-with-module-field' + text('.require-pkg-with-module-field', requireButWithModuleFieldMsg) import { msg as customExtMsg } from './custom-ext' text('.custom-ext', customExtMsg) diff --git a/packages/playground/resolve/package.json b/packages/playground/resolve/package.json index 4b8d497b3dbb27..dda4476bc6ae82 100644 --- a/packages/playground/resolve/package.json +++ b/packages/playground/resolve/package.json @@ -12,8 +12,7 @@ "@babel/runtime": "^7.16.0", "es5-ext": "0.10.53", "normalize.css": "^8.0.1", - "require-pkg-with-browser-and-module-field": "link:./require-pkg-with-browser-and-module-field", - "require-pkg-with-esm-entries": "link:./require-pkg-with-esm-entries", + "require-pkg-with-module-field": "link:./require-pkg-with-module-field", "resolve-browser-field": "link:./browser-field", "resolve-custom-condition": "link:./custom-condition", "resolve-custom-main-field": "link:./custom-main-field", diff --git a/packages/playground/resolve/require-pkg-with-browser-and-module-field/index.cjs b/packages/playground/resolve/require-pkg-with-browser-and-module-field/index.cjs deleted file mode 100644 index 86d3360ab38dcb..00000000000000 --- a/packages/playground/resolve/require-pkg-with-browser-and-module-field/index.cjs +++ /dev/null @@ -1,8 +0,0 @@ -const dep = require('./dep.cjs') - -const msg = - dep === '1.111222233334444555566e+21' - ? '[success] require-pkg-with-browser-and-module-field' - : '[failed] require-pkg-with-browser-and-module-field' - -exports.msg = msg diff --git a/packages/playground/resolve/require-pkg-with-esm-entries/index.cjs b/packages/playground/resolve/require-pkg-with-esm-entries/index.cjs deleted file mode 100644 index 55958fbdba26ee..00000000000000 --- a/packages/playground/resolve/require-pkg-with-esm-entries/index.cjs +++ /dev/null @@ -1,9 +0,0 @@ -const fromEvent = require('callbag-from-event') - -const msg = - // should be the exported function instead of the ES Module record (`{ default: ... }`) - typeof fromEvent === 'function' - ? '[success] require-pkg-with-esm-entries' - : '[failed] require-pkg-with-esm-entries' - -exports.msg = msg diff --git a/packages/playground/resolve/require-pkg-with-esm-entries/package.json b/packages/playground/resolve/require-pkg-with-esm-entries/package.json deleted file mode 100644 index b845364bb6f19a..00000000000000 --- a/packages/playground/resolve/require-pkg-with-esm-entries/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "require-pkg-with-esm-entries", - "private": true, - "version": "1.0.0", - "main": "./index.cjs", - "dependencies": { - "callbag-from-event": "1.3.0" - } -} diff --git a/packages/playground/resolve/require-pkg-with-browser-and-module-field/dep.cjs b/packages/playground/resolve/require-pkg-with-module-field/dep.cjs similarity index 100% rename from packages/playground/resolve/require-pkg-with-browser-and-module-field/dep.cjs rename to packages/playground/resolve/require-pkg-with-module-field/dep.cjs diff --git a/packages/playground/resolve/require-pkg-with-module-field/index.cjs b/packages/playground/resolve/require-pkg-with-module-field/index.cjs new file mode 100644 index 00000000000000..da215f306d1ac1 --- /dev/null +++ b/packages/playground/resolve/require-pkg-with-module-field/index.cjs @@ -0,0 +1,8 @@ +const dep = require('./dep.cjs') + +const msg = + dep === '1.111222233334444555566e+21' + ? '[success] require-pkg-with-module-field' + : '[failed] require-pkg-with-module-field' + +exports.msg = msg diff --git a/packages/playground/resolve/require-pkg-with-browser-and-module-field/package.json b/packages/playground/resolve/require-pkg-with-module-field/package.json similarity index 68% rename from packages/playground/resolve/require-pkg-with-browser-and-module-field/package.json rename to packages/playground/resolve/require-pkg-with-module-field/package.json index 2a0419b331c407..e409343a7567d5 100644 --- a/packages/playground/resolve/require-pkg-with-browser-and-module-field/package.json +++ b/packages/playground/resolve/require-pkg-with-module-field/package.json @@ -1,5 +1,5 @@ { - "name": "require-pkg-with-browser-and-module-field", + "name": "require-pkg-with-module-field", "private": true, "version": "1.0.0", "main": "./index.cjs", diff --git a/packages/playground/resolve/vite.config.js b/packages/playground/resolve/vite.config.js index c1282f4ffc789d..0550d1ecf6f044 100644 --- a/packages/playground/resolve/vite.config.js +++ b/packages/playground/resolve/vite.config.js @@ -42,9 +42,6 @@ module.exports = { } ], optimizeDeps: { - include: [ - 'require-pkg-with-browser-and-module-field', - 'require-pkg-with-esm-entries' - ] + include: ['require-pkg-with-module-field'] } } diff --git a/packages/vite/src/node/constants.ts b/packages/vite/src/node/constants.ts index 1741bf2dd7a94b..9612cd8c96460d 100644 --- a/packages/vite/src/node/constants.ts +++ b/packages/vite/src/node/constants.ts @@ -6,21 +6,6 @@ export const DEFAULT_MAIN_FIELDS = [ 'jsnext' ] -/** - * A non-exhaustive list of known-to-be-ES-module entry names. - * From - */ -export const KNOWN_ESM_MAIN_FIELDS = [ - 'module', - 'jsnext:main', - 'jsnext', - 'esnext', - 'es2015', - 'es2020', - 'fesm2015', - 'fesm2020' -] - export const DEFAULT_EXTENSIONS = [ '.mjs', '.js', diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 10e2989af1114f..1b59503a9d43ed 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -7,7 +7,6 @@ import { SPECIAL_QUERY_RE, DEFAULT_EXTENSIONS, DEFAULT_MAIN_FIELDS, - KNOWN_ESM_MAIN_FIELDS, OPTIMIZABLE_ENTRY_RE, DEP_VERSION_RE } from '../constants' @@ -778,11 +777,6 @@ export function resolvePackageEntry( if (!entryPoint || entryPoint.endsWith('.mjs')) { for (const field of options.mainFields || DEFAULT_MAIN_FIELDS) { - // If the initiator is a `require` call, don't use the ESM entries - if (options.isRequire && KNOWN_ESM_MAIN_FIELDS.includes(field)) { - continue - } - if (typeof data[field] === 'string') { entryPoint = data[field] break diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fbc05e51fbfc7a..09d96eb30938d7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -461,8 +461,7 @@ importers: '@babel/runtime': ^7.16.0 es5-ext: 0.10.53 normalize.css: ^8.0.1 - require-pkg-with-browser-and-module-field: link:./require-pkg-with-browser-and-module-field - require-pkg-with-esm-entries: link:./require-pkg-with-esm-entries + require-pkg-with-module-field: link:./require-pkg-with-module-field resolve-browser-field: link:./browser-field resolve-custom-condition: link:./custom-condition resolve-custom-main-field: link:./custom-main-field @@ -473,8 +472,7 @@ importers: '@babel/runtime': 7.16.5 es5-ext: 0.10.53 normalize.css: 8.0.1 - require-pkg-with-browser-and-module-field: link:require-pkg-with-browser-and-module-field - require-pkg-with-esm-entries: link:require-pkg-with-esm-entries + require-pkg-with-module-field: link:require-pkg-with-module-field resolve-browser-field: link:browser-field resolve-custom-condition: link:custom-condition resolve-custom-main-field: link:custom-main-field @@ -506,18 +504,12 @@ importers: packages/playground/resolve/inline-package: specifiers: {} - packages/playground/resolve/require-pkg-with-browser-and-module-field: + packages/playground/resolve/require-pkg-with-module-field: specifiers: bignumber.js: 9.0.2 dependencies: bignumber.js: 9.0.2 - packages/playground/resolve/require-pkg-with-esm-entries: - specifiers: - callbag-from-event: 1.3.0 - dependencies: - callbag-from-event: 1.3.0 - packages/playground/ssr-deps: specifiers: bcrypt: ^5.0.1 @@ -3497,16 +3489,6 @@ packages: get-intrinsic: 1.1.1 dev: true - /callbag-from-event/1.3.0: - resolution: {integrity: sha512-cAu82hKKFmMtKTmd50p/nlMfs1oKz+PGUZmmwhbzPbw4YtjNgTKg6pXjpcQprhBQdrqg/v8pHcAS8Qs6X7r8fw==} - dependencies: - callbag: 1.5.0 - dev: false - - /callbag/1.5.0: - resolution: {integrity: sha512-PH3id0HEb/cNS+BehYlF4Z5wzjKAIUao6ab2hWtMs2bi6aW+0PXl0jymqwnFyT2cQO2h30ggUgpQlmzOpAIKNg==} - dev: false - /callsites/3.1.0: resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} engines: {node: '>=6'} From 5d96dcab9ce207c9fc7f37116b00d45b678fc87c Mon Sep 17 00:00:00 2001 From: patak-dev Date: Thu, 14 Apr 2022 16:43:29 +0200 Subject: [PATCH 87/93] release: v2.9.5 --- packages/vite/CHANGELOG.md | 7 +++++++ packages/vite/package.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/vite/CHANGELOG.md b/packages/vite/CHANGELOG.md index 8ed8c8cf8ba692..084a6363109266 100644 --- a/packages/vite/CHANGELOG.md +++ b/packages/vite/CHANGELOG.md @@ -1,3 +1,10 @@ +## 2.9.5 (2022-04-14) + +* fix: revert #7582, fix #7721 and #7736 (#7737) ([fa86d69](https://github.com/vitejs/vite/commit/fa86d69)), closes [#7721](https://github.com/vitejs/vite/issues/7721) [#7736](https://github.com/vitejs/vite/issues/7736) [#7737](https://github.com/vitejs/vite/issues/7737) +* chore: format css minify esbuild error (#7731) ([c445075](https://github.com/vitejs/vite/commit/c445075)), closes [#7731](https://github.com/vitejs/vite/issues/7731) + + + ## 2.9.4 (2022-04-13) * fix: handle url imports with semicolon (fix #7717) (#7718) ([a5c2a78](https://github.com/vitejs/vite/commit/a5c2a78)), closes [#7717](https://github.com/vitejs/vite/issues/7717) [#7718](https://github.com/vitejs/vite/issues/7718) diff --git a/packages/vite/package.json b/packages/vite/package.json index 1ab75ada9c7cd3..e575c5b4f6c907 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -1,6 +1,6 @@ { "name": "vite", - "version": "2.9.4", + "version": "2.9.5", "license": "MIT", "author": "Evan You", "description": "Native-ESM powered web dev build tool", From 434bb5c05bce8a376bde50100a1466072d5e3624 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Fri, 15 Apr 2022 03:47:53 +0900 Subject: [PATCH 88/93] docs: mention `process.env` for config env vars (#7744) --- docs/config/index.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/config/index.md b/docs/config/index.md index d7560e58736a43..346de1a78f7dc9 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -101,7 +101,9 @@ export default defineConfig(async ({ command, mode }) => { ### Environment Variables -Vite doesn't load `.env` files by default as the files to load can only be determined after evaluating the Vite config, for example, the `root` and `envDir` options affects the loading behaviour. However, you can use the exported `loadEnv` helper to load the specific `.env` file if needed. +Environmental Variables can be obtained from `process.env` as usual. + +Note that Vite doesn't load `.env` files by default as the files to load can only be determined after evaluating the Vite config, for example, the `root` and `envDir` options affects the loading behaviour. However, you can use the exported `loadEnv` helper to load the specific `.env` file if needed. ```js import { defineConfig, loadEnv } from 'vite' From 1f2ca536101d54649c6abc34e9665c2163878b56 Mon Sep 17 00:00:00 2001 From: Rom Date: Fri, 15 Apr 2022 07:45:26 +0200 Subject: [PATCH 89/93] fix: `apply` condition skipped for nested plugins (#7741) --- packages/vite/src/node/config.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index f633d1158bfa95..a30d84465e9990 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -63,7 +63,7 @@ export function defineConfig(config: UserConfigExport): UserConfigExport { return config } -export type PluginOption = Plugin | false | null | undefined +export type PluginOption = Plugin | false | null | undefined | PluginOption[] export interface UserConfig { /** @@ -109,7 +109,7 @@ export interface UserConfig { /** * Array of vite plugins to use. */ - plugins?: (PluginOption | PluginOption[])[] + plugins?: PluginOption[] /** * Configure resolver */ @@ -199,7 +199,7 @@ export interface UserConfig { /** * Vite plugins that apply to worker bundle */ - plugins?: (PluginOption | PluginOption[])[] + plugins?: PluginOption[] /** * Rollup options to build worker bundle */ @@ -322,7 +322,7 @@ export async function resolveConfig( configEnv.mode = mode // resolve plugins - const rawUserPlugins = (config.plugins || []).flat().filter((p) => { + const rawUserPlugins = (config.plugins || []).flat(Infinity).filter((p) => { if (!p) { return false } else if (!p.apply) { From b89974a127c7a986d309db675d95287a9ae75386 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Sat, 16 Apr 2022 04:20:36 +0900 Subject: [PATCH 90/93] fix(ssr): rewrite dynamic class method name (fix #7751) (#7757) --- .../node/ssr/__tests__/ssrTransform.spec.ts | 39 +++++++++++++++++++ packages/vite/src/node/ssr/ssrTransform.ts | 2 +- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts index a5f915edea97fd..14481f98a4a87a 100644 --- a/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts +++ b/packages/vite/src/node/ssr/__tests__/ssrTransform.spec.ts @@ -545,6 +545,45 @@ class A { `) }) +test('class methods', async () => { + expect( + ( + await ssrTransform( + ` +import foo from 'foo' + +const bar = 'bar' + +class A { + foo() {} + [foo]() {} + [bar]() {} + #foo() {} + bar(foo) {} +} +`, + null, + null + ) + ).code + ).toMatchInlineSnapshot(` + " + const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foo\\"); + + + const bar = 'bar' + + class A { + foo() {} + [__vite_ssr_import_0__.default]() {} + [bar]() {} + #foo() {} + bar(foo) {} + } + " + `) +}) + test('declare scope', async () => { expect( ( diff --git a/packages/vite/src/node/ssr/ssrTransform.ts b/packages/vite/src/node/ssr/ssrTransform.ts index 79ccd25f9ca8ff..238482a0ceac2f 100644 --- a/packages/vite/src/node/ssr/ssrTransform.ts +++ b/packages/vite/src/node/ssr/ssrTransform.ts @@ -429,7 +429,7 @@ function isRefIdentifier(id: Identifier, parent: _Node, parentStack: _Node[]) { } // class method name - if (parent.type === 'MethodDefinition') { + if (parent.type === 'MethodDefinition' && !parent.computed) { return false } From 12a4e7d8bbf06d35d6fcc0135dcb76fd06a57c22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Sat, 16 Apr 2022 17:32:13 +0900 Subject: [PATCH 91/93] refactor(legacy): remove unneeded dynamic import var init code (#7759) --- packages/plugin-legacy/README.md | 1 - packages/plugin-legacy/index.js | 8 -------- 2 files changed, 9 deletions(-) diff --git a/packages/plugin-legacy/README.md b/packages/plugin-legacy/README.md index 36da971c6a17c2..3c9fe67e107f7f 100644 --- a/packages/plugin-legacy/README.md +++ b/packages/plugin-legacy/README.md @@ -163,7 +163,6 @@ The legacy plugin requires inline scripts for [Safari 10.1 `nomodule` fix](https - `sha256-MS6/3FCg4WjP9gwgaBGwLpRCY6fZBgwmhVCdrPrNf3E=` - `sha256-tQjf8gvb2ROOMapIxFvFAYBeUJ0v1HCbOcSmDNXGtDo=` -- `sha256-xYj09txJ9OsgySe5ommpqul6FiaJZRrwe3KTD7wbV6w=` - `sha256-4m6wOIrq/wFDmi9Xh3mFM2mwI4ik9n3TMgHk6xDtLxk=` - `sha256-uS7/g9fhQwNZS1f/MqYqqKv8y9hCu36IfX9XZB5L7YY=` diff --git a/packages/plugin-legacy/index.js b/packages/plugin-legacy/index.js index 41f7157ebfc533..2f1b1991c31c31 100644 --- a/packages/plugin-legacy/index.js +++ b/packages/plugin-legacy/index.js @@ -20,7 +20,6 @@ const legacyEntryId = 'vite-legacy-entry' const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))` const detectDynamicImportVarName = '__vite_is_dynamic_import_support' -const detectDynamicImportVarInitCode = `var ${detectDynamicImportVarName}=false;` const detectDynamicImportCode = `try{import("_").catch(()=>1);}catch(e){}window.${detectDynamicImportVarName}=true;` const dynamicFallbackInlineCode = `!function(){if(window.${detectDynamicImportVarName})return;console.warn("vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored");var e=document.getElementById("${legacyPolyfillId}"),n=document.createElement("script");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}();` @@ -437,12 +436,6 @@ function viteLegacyPlugin(options = {}) { // 5. inject dynamic import fallback entry if (genDynamicFallback && legacyPolyfillFilename && legacyEntryFilename) { - tags.push({ - tag: 'script', - attrs: { type: 'module' }, - children: detectDynamicImportVarInitCode, - injectTo: 'head' - }) tags.push({ tag: 'script', attrs: { type: 'module' }, @@ -714,7 +707,6 @@ viteLegacyPlugin.default = viteLegacyPlugin viteLegacyPlugin.cspHashes = [ createHash('sha256').update(safari10NoModuleFix).digest('base64'), createHash('sha256').update(systemJSInlineCode).digest('base64'), - createHash('sha256').update(detectDynamicImportVarInitCode).digest('base64'), createHash('sha256').update(detectDynamicImportCode).digest('base64'), createHash('sha256').update(dynamicFallbackInlineCode).digest('base64') ] From 9a932339aae8bfbb9f3b522706c551a21a1eea3a Mon Sep 17 00:00:00 2001 From: Hydrogen <3038094028@qq.com> Date: Sat, 16 Apr 2022 20:05:49 +0800 Subject: [PATCH 92/93] fix(create-vite): bump `vue-tsc` to `0.34.7` (#7760) --- packages/create-vite/template-vue-ts/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/create-vite/template-vue-ts/package.json b/packages/create-vite/template-vue-ts/package.json index 2ad29ac0b91725..a3af0acf1ef7ab 100644 --- a/packages/create-vite/template-vue-ts/package.json +++ b/packages/create-vite/template-vue-ts/package.json @@ -14,6 +14,6 @@ "@vitejs/plugin-vue": "^2.3.1", "typescript": "^4.5.4", "vite": "^2.9.2", - "vue-tsc": "^0.29.8" + "vue-tsc": "^0.34.7" } } From 694c1ce765b80458197e039ce720bb9ce1076667 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Mon, 18 Apr 2022 00:28:25 +0900 Subject: [PATCH 93/93] test: fix use terser for preload test (#7771) --- packages/playground/preload/vite.config.js | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/playground/preload/vite.config.js b/packages/playground/preload/vite.config.js index 96fb82f51ed349..90684f41829953 100644 --- a/packages/playground/preload/vite.config.js +++ b/packages/playground/preload/vite.config.js @@ -3,6 +3,7 @@ const vuePlugin = require('@vitejs/plugin-vue') module.exports = { plugins: [vuePlugin()], build: { + minify: 'terser', terserOptions: { format: { beautify: true