Skip to content

Commit 5afc5a8

Browse files
h-a-n-asapphi-red
andauthored
fix(bundled-dev): serve /@vite/client and stub @vite/env (#23664)
Co-authored-by: sapphi-red <[email protected]>
1 parent 794516d commit 5afc5a8

5 files changed

Lines changed: 67 additions & 13 deletions

File tree

‎packages/vite/src/node/plugins/clientInjections.ts‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
11
import fs from 'node:fs'
22
import path from 'node:path'
33
import { fileURLToPath } from 'node:url'
4+
import { exactRegex } from 'rolldown/filter'
45
import { cleanUrl } from '../../shared/utils'
56
import type { ResolvedConfig } from '../config'
67
import {
78
BUNDLED_DEV_CLIENT_ENTRY,
9+
BUNDLED_DEV_CLIENT_FILENAME,
810
BUNDLED_DEV_ROLLDOWN_RUNTIME_DIR,
911
CLIENT_ENTRY,
12+
CLIENT_PUBLIC_PATH,
1013
ENV_ENTRY,
14+
ENV_PUBLIC_PATH,
1115
} from '../constants'
1216
import { perEnvironmentState } from '../environment'
1317
import type { Plugin } from '../plugin'
14-
import { isObject, normalizePath, resolveHostname } from '../utils'
18+
import { escapeRegex, isObject, normalizePath, resolveHostname } from '../utils'
1519
import { replaceDefine, serializeDefine } from './define'
1620

1721
// ids in transform are normalized to unix style
@@ -196,3 +200,46 @@ export function getRolldownDevRuntimeFiles(): Map<string, string> {
196200
}
197201
return files
198202
}
203+
204+
export function getBundledDevClientAliases(
205+
config: ResolvedConfig,
206+
): Map<string, string> {
207+
const clientUrl = path.posix.join(config.base, BUNDLED_DEV_CLIENT_FILENAME)
208+
return new Map([
209+
[CLIENT_PUBLIC_PATH.slice(1), `export * from ${JSON.stringify(clientUrl)}`],
210+
// defines are replaced at build time in bundled dev
211+
[ENV_PUBLIC_PATH.slice(1), ''],
212+
])
213+
}
214+
215+
export function bundledDevClientImportsPlugin(config: ResolvedConfig): Plugin {
216+
const clientUrl = path.posix.join(config.base, BUNDLED_DEV_CLIENT_FILENAME)
217+
return {
218+
name: 'vite:bundled-dev-client-imports',
219+
applyToEnvironment(environment) {
220+
return (
221+
config.command === 'serve' &&
222+
environment.config.isBundled &&
223+
environment.config.consumer === 'client'
224+
)
225+
},
226+
resolveId: {
227+
filter: { id: exactRegex(clientUrl) },
228+
handler(id) {
229+
return { id, external: true }
230+
},
231+
},
232+
load: {
233+
filter: {
234+
id: new RegExp(
235+
`^(?:${escapeRegex(normalizedClientEntry)}|${escapeRegex(normalizedEnvEntry)})(?:\\?.*)?$`,
236+
),
237+
},
238+
handler(id) {
239+
return cleanUrl(id) === normalizedClientEntry
240+
? `export * from ${JSON.stringify(clientUrl)}`
241+
: ''
242+
},
243+
},
244+
}
245+
}

‎packages/vite/src/node/plugins/index.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@ import {
1515
} from '../plugin'
1616
import { assetPlugin } from './asset'
1717
import { assetImportMetaUrlPlugin } from './assetImportMetaUrl'
18-
import { clientInjectionsPlugin } from './clientInjections'
18+
import {
19+
bundledDevClientImportsPlugin,
20+
clientInjectionsPlugin,
21+
} from './clientInjections'
1922
import { cssAnalysisPlugin, cssPlugin, cssPostPlugin } from './css'
2023
import { definePlugin } from './define'
2124
import { dynamicImportVarsPlugin } from './dynamicImportVars'
@@ -87,6 +90,8 @@ export async function resolvePlugins(
8790
modulePreload !== false && modulePreload.polyfill
8891
? modulePreloadPolyfillPlugin()
8992
: null,
93+
// before the resolver, which cannot resolve the client's public URL
94+
bundledDevClientImportsPlugin(config),
9095
...oxcResolvePlugin(
9196
{
9297
root: config.root,

‎packages/vite/src/node/server/bundledDev.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import { ChunkMetadataMap, resolveRolldownOptions } from '../build'
1111
import { BUNDLED_DEV_CLIENT_FILENAME } from '../constants'
1212
import {
13+
getBundledDevClientAliases,
1314
getHmrImplementation,
1415
getRolldownDevRuntimeFiles,
1516
} from '../plugins/clientInjections'
@@ -26,6 +27,7 @@ type HmrOutput = BindingClientHmrUpdate['update']
2627
type MemoryFile = {
2728
source: string | Uint8Array
2829
etag?: string
30+
contentType?: string
2931
}
3032

3133
export class MemoryFiles {
@@ -387,11 +389,15 @@ export class BundledDev {
387389
],
388390
...getRolldownDevRuntimeFiles(),
389391
])
392+
const aliases = getBundledDevClientAliases(
393+
this.environment.getTopLevelConfig(),
394+
)
390395
this.staticFiles.clear()
391-
for (const [fileName, source] of sources) {
392-
const file = {
396+
for (const [fileName, source] of [...sources, ...aliases]) {
397+
const file: MemoryFile = {
393398
source,
394399
etag: getEtag(Buffer.from(source), { weak: true }),
400+
...(aliases.has(fileName) ? { contentType: 'text/javascript' } : {}),
395401
}
396402
this.staticFiles.set(fileName, file)
397403
this.memoryFiles.set(fileName, file)

‎packages/vite/src/node/server/middlewares/memoryFiles.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export function memoryFilesMiddleware(
3939
res.setHeader('Etag', file.etag)
4040
}
4141

42-
const mime = mrmime.lookup(filePath)
42+
const mime = file.contentType ?? mrmime.lookup(filePath)
4343
if (mime) {
4444
res.setHeader('Content-Type', mime)
4545
}

‎playground/define/__tests__/define.spec.ts‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { expect, test } from 'vitest'
2-
import { isBundledDev, page } from '~utils'
2+
import { page } from '~utils'
33
import viteConfig from '../vite.config'
44

55
const defines = viteConfig.define
@@ -116,10 +116,6 @@ test('optional values are detected by pattern properly', async () => {
116116
)
117117
})
118118

119-
// bundled dev serves `?query` env imports without injecting __DEFINES__
120-
test.skipIf(isBundledDev)(
121-
'env import with query parameters works correctly',
122-
async () => {
123-
expect(await page.textContent('.env-with-query')).toBe('success')
124-
},
125-
)
119+
test('env import with query parameters works correctly', async () => {
120+
expect(await page.textContent('.env-with-query')).toBe('success')
121+
})

0 commit comments

Comments
 (0)