Skip to content

Commit bc598a6

Browse files
authored
fix(bundled-dev): serve the rolldown runtime from the installed rolldown (#23568)
1 parent 3d02335 commit bc598a6

6 files changed

Lines changed: 117 additions & 20 deletions

File tree

‎packages/vite/rolldown.config.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ const bundledDevClientConfig = defineConfig({
4444
transform: {
4545
target: 'es2020',
4646
},
47-
external: ['@vite/env'],
47+
// the runtime is served from the installed rolldown at dev time (`getRolldownDevRuntimeFiles`)
48+
external: ['@vite/env', 'rolldown/experimental/runtime'],
4849
output: {
4950
dir: path.resolve(dirname, 'dist'),
5051
entryFileNames: 'client/bundledDevClient.mjs',
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import path from 'node:path'
2+
import { expect, test } from 'vitest'
3+
import { getRolldownDevRuntimeFiles } from '../../plugins/clientInjections'
4+
5+
// The runtime entry imports its helper file with a relative path. Catch a rolldown layout
6+
// change here, instead of as a 404 in the browser.
7+
test('serves every file the rolldown dev runtime imports', () => {
8+
const files = getRolldownDevRuntimeFiles()
9+
let checked = 0
10+
for (const [urlPath, source] of files) {
11+
for (const match of source.matchAll(/\bfrom\s*['"](\.\.?\/[^'"]+)['"]/g)) {
12+
const imported = path.posix.join(path.posix.dirname(urlPath), match[1])
13+
expect(files.has(imported), `${urlPath} imports ${match[1]}`).toBe(true)
14+
checked++
15+
}
16+
}
17+
expect(checked).toBeGreaterThan(0)
18+
})

‎packages/vite/src/node/constants.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@ export const BUNDLED_DEV_CLIENT_ENTRY: string = resolve(
131131
)
132132
/** URL filename the bundled-dev server serves the vite client under */
133133
export const BUNDLED_DEV_CLIENT_FILENAME: string = 'bundledDevClient.mjs'
134+
/** URL directory the bundled-dev server serves rolldown's dev runtime files under */
135+
export const BUNDLED_DEV_ROLLDOWN_RUNTIME_DIR: string = '@rolldown'
134136
export const ENV_ENTRY: string = resolve(
135137
VITE_PACKAGE_DIR,
136138
'dist/client/env.mjs',

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

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
import fs from 'node:fs'
22
import path from 'node:path'
3+
import { fileURLToPath } from 'node:url'
34
import { cleanUrl } from '../../shared/utils'
45
import type { ResolvedConfig } from '../config'
5-
import { CLIENT_ENTRY, ENV_ENTRY, BUNDLED_DEV_CLIENT_ENTRY } from '../constants'
6+
import {
7+
BUNDLED_DEV_CLIENT_ENTRY,
8+
BUNDLED_DEV_ROLLDOWN_RUNTIME_DIR,
9+
CLIENT_ENTRY,
10+
ENV_ENTRY,
11+
} from '../constants'
612
import { perEnvironmentState } from '../environment'
713
import type { Plugin } from '../plugin'
814
import { isObject, normalizePath, resolveHostname } from '../utils'
@@ -138,14 +144,55 @@ async function createClientConfigValueReplacer(
138144
.replace(`__SERVER_FORWARD_CONSOLE__`, serverForwardConsoleReplacement)
139145
}
140146

147+
const ROLLDOWN_DEV_RUNTIME_ENTRY = 'rolldown/experimental/runtime'
148+
141149
export async function getHmrImplementation(
142150
config: ResolvedConfig,
143151
): Promise<string> {
144152
const content = fs.readFileSync(normalizedBundledDevClientEntry, 'utf-8')
145153
const replacer = await createClientConfigValueReplacer(config)
146154
return (
147155
replacer(content)
148-
// the rolldown runtime cannot import a module
156+
// `/@vite/env` is not served in bundled dev
149157
.replace(/import\s*['"]@vite\/env['"]/, '')
158+
// absolute under `base`: a relative specifier would resolve against a sub-page's URL
159+
.replace(
160+
new RegExp(`(from\\s*['"])${ROLLDOWN_DEV_RUNTIME_ENTRY}(['"])`),
161+
(_, before, after) =>
162+
`${before}${path.posix.join(
163+
config.base,
164+
BUNDLED_DEV_ROLLDOWN_RUNTIME_DIR,
165+
path.basename(rolldownDevRuntimeEntryPath()),
166+
)}${after}`,
167+
)
150168
)
151169
}
170+
171+
function rolldownDevRuntimeEntryPath(): string {
172+
return fileURLToPath(import.meta.resolve(ROLLDOWN_DEV_RUNTIME_ENTRY))
173+
}
174+
175+
/**
176+
* The dev runtime must match the rolldown that generates the bundle, so it is read from the
177+
* installed package at serve time instead of being bundled into the client. The entry imports
178+
* its helper file with a relative path, so both are served under the same directory.
179+
*/
180+
export function getRolldownDevRuntimeFiles(): Map<string, string> {
181+
const entry = rolldownDevRuntimeEntryPath()
182+
const dir = path.dirname(entry)
183+
const files = new Map<string, string>()
184+
for (const name of fs.readdirSync(dir)) {
185+
if (name.startsWith('experimental-runtime') && name.endsWith('.mjs')) {
186+
files.set(
187+
`${BUNDLED_DEV_ROLLDOWN_RUNTIME_DIR}/${name}`,
188+
fs.readFileSync(path.join(dir, name), 'utf-8'),
189+
)
190+
}
191+
}
192+
if (
193+
!files.has(`${BUNDLED_DEV_ROLLDOWN_RUNTIME_DIR}/${path.basename(entry)}`)
194+
) {
195+
throw new Error(`rolldown dev runtime entry ${entry} was not found`)
196+
}
197+
return files
198+
}

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

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ import {
99
} from 'rolldown/experimental'
1010
import { ChunkMetadataMap, resolveRolldownOptions } from '../build'
1111
import { BUNDLED_DEV_CLIENT_FILENAME } from '../constants'
12-
import { getHmrImplementation } from '../plugins/clientInjections'
12+
import {
13+
getHmrImplementation,
14+
getRolldownDevRuntimeFiles,
15+
} from '../plugins/clientInjections'
1316
import { createDebugger, formatAndTruncateFileList } from '../utils'
1417
import { convertToDevWatchOptions } from '../watch'
1518
import type { DevEnvironment } from './environment'
@@ -60,7 +63,8 @@ export class MemoryFiles {
6063

6164
export class BundledDev {
6265
private _devEngine!: DevEngine
63-
private viteRuntime?: string
66+
/** the vite client and the rolldown runtime; set before the first build so `hasBuildOutput` can count them */
67+
private staticFiles = new Map<string, MemoryFile>()
6468
private initialBuildCompleted = false
6569
private _closed = false
6670
private clients = new Clients()
@@ -107,17 +111,14 @@ export class BundledDev {
107111
private pendingPayloadFilenames = new Set<string>()
108112

109113
get hasBuildOutput(): boolean {
110-
return (
111-
this.memoryFiles.size > 1 ||
112-
(this.memoryFiles.size === 1 &&
113-
!this.memoryFiles.has(BUNDLED_DEV_CLIENT_FILENAME))
114-
)
114+
return this.memoryFiles.size > this.staticFiles.size
115115
}
116116

117117
async listen(): Promise<void> {
118118
this._closed = false
119119
debug?.('INITIAL: setup bundle options')
120120
const rolldownOptions = await this.getRolldownOptions()
121+
await this.storeStaticFiles()
121122
// NOTE: only single outputOptions is supported here
122123
if (
123124
Array.isArray(rolldownOptions.output) &&
@@ -262,10 +263,6 @@ export class BundledDev {
262263
debug?.('INITIAL: run error', e)
263264
},
264265
)
265-
this.viteRuntime = await getHmrImplementation(
266-
this.environment.getTopLevelConfig(),
267-
)
268-
this.storeOutputFiles([])
269266
this.waitForInitialBuildFinish().then(() => {
270267
if (this._closed) return
271268
debug?.('INITIAL: build done')
@@ -373,14 +370,27 @@ export class BundledDev {
373370
this.initialBuildCompleted = false
374371
}
375372

373+
private async storeStaticFiles(): Promise<void> {
374+
const sources = new Map<string, string>([
375+
[
376+
BUNDLED_DEV_CLIENT_FILENAME,
377+
await getHmrImplementation(this.environment.getTopLevelConfig()),
378+
],
379+
...getRolldownDevRuntimeFiles(),
380+
])
381+
this.staticFiles.clear()
382+
for (const [fileName, source] of sources) {
383+
const file = {
384+
source,
385+
etag: getEtag(Buffer.from(source), { weak: true }),
386+
}
387+
this.staticFiles.set(fileName, file)
388+
this.memoryFiles.set(fileName, file)
389+
}
390+
}
391+
376392
private storeOutputFiles(output: RolldownOutput['output'][number][]): void {
377393
// NOTE: don't clear memoryFiles here as incremental build reuses the files
378-
if (this.viteRuntime) {
379-
this.memoryFiles.set(BUNDLED_DEV_CLIENT_FILENAME, {
380-
source: this.viteRuntime,
381-
etag: getEtag(Buffer.from(this.viteRuntime), { weak: true }),
382-
})
383-
}
384394
for (const outputFile of output) {
385395
this.memoryFiles.set(outputFile.fileName, () => {
386396
const source =

‎playground/hmr-full-bundle-mode/__tests__/hmr-full-bundle-mode.spec.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,25 @@ if (isBuild) {
3636
await expect.poll(() => page.textContent('.worker-url')).toBe('worker-url')
3737
})
3838

39+
// The runtime must be the installed rolldown's, served by the dev server
40+
test('loads the rolldown runtime from the server', async () => {
41+
const runtimeUrl = new URL(
42+
'/@rolldown/experimental-runtime.mjs',
43+
page.url(),
44+
)
45+
const client = await page.request.get(
46+
new URL('/bundledDevClient.mjs', page.url()).href,
47+
)
48+
expect(await client.text()).toContain(`from "${runtimeUrl.pathname}"`)
49+
const runtime = await page.request.get(runtimeUrl.href)
50+
expect(runtime.status()).toBe(200)
51+
expect(await runtime.text()).toContain('class DevRuntime')
52+
const loaded: string[] = await page.evaluate(() =>
53+
performance.getEntriesByType('resource').map((entry) => entry.name),
54+
)
55+
expect(loaded).toContain(runtimeUrl.href)
56+
})
57+
3958
// BUNDLED -> GENERATE_HMR_PATCH -> BUNDLING -> BUNDLE_ERROR -> BUNDLING -> BUNDLED
4059
test('handle bundle error', async () => {
4160
editFile('main.js', (code) =>

0 commit comments

Comments
 (0)