Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 38 additions & 12 deletions packages/vite/src/client/bundledDevHmrClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import type { NormalizedModuleRunnerTransport } from '../shared/moduleRunnerTran

/** the subset of `__rolldown_runtime__` the HMR client uses */
export interface RolldownRuntimeLike {
staticImports: Map<string, { edges: string[] }>
dynamicImports: Map<string, { edges: string[] }>
getImporters(id: string): string[]
getImportedBindings(importer: string, id: string): string[] | undefined
isExecuted(id: string): boolean
Expand All @@ -24,10 +26,9 @@ interface PropagationBoundary {
}

type HmrUpdate =
| { type: 'noop' }
| { type: 'full-reload'; reason: string }
| {
type: 'boundaries'
type: 'update'
boundaries: PropagationBoundary[]
updateSet: string[]
}
Expand All @@ -43,6 +44,7 @@ export class BundledDevHMRClient extends HMRClient {
private applyQueue = Promise.resolve()
private lastSeq = 0
private reloadPending = false
private orphans = new Set<string>()

constructor(
logger: HMRLogger,
Expand Down Expand Up @@ -119,9 +121,20 @@ export class BundledDevHMRClient extends HMRClient {
)
if (fullReload) return fullReload
}
return boundaries.length
? { type: 'boundaries', boundaries, updateSet: [...updateSet] }
: { type: 'noop' }
return { type: 'update', boundaries, updateSet: [...updateSet] }
}

private getImports(id: string): string[] {
return [
...(this.runtime.staticImports.get(id)?.edges ?? []),
...(this.runtime.dynamicImports.get(id)?.edges ?? []),
]
}

private hasExecutedImporter(id: string): boolean {
return this.runtime
.getImporters(id)
.some((importer) => this.runtime.isExecuted(importer))
}

private bubble(
Expand All @@ -135,6 +148,10 @@ export class BundledDevHMRClient extends HMRClient {
if (traversedModules.has(id)) return
traversedModules.add(id)
updateSet.add(id)
// A module that ran in this page gets orphaned when all its importers
// remove their import of it. An orphan has no importer left, so stop here
// and don't bubble up.
if (this.orphans.has(id) && !this.hasExecutedImporter(id)) return
if (firstInvalidatedBy !== undefined && id === firstInvalidatedBy) {
return {
type: 'full-reload',
Expand Down Expand Up @@ -310,25 +327,34 @@ export class BundledDevHMRClient extends HMRClient {
this.lastSeq = seq

const update = this.computeHmrUpdate(changedIds)
if (update.type === 'noop') return
if (update.type === 'full-reload') {
this.requestFullReload(update.reason)
return
}
// none of the changed modules has run in this page
if (!update.updateSet.length) return

const notify = update.boundaries.length > 0
const listenerPayload = this.toUpdatePayload(update.boundaries, undefined)
await this.notifyListeners('vite:beforeUpdate', listenerPayload)
if (notify) await this.notifyListeners('vite:beforeUpdate', listenerPayload)
if (this.options.beforeApply() === 'reload') return

// the patch replaces the import edges of the changed modules
const importsBeforePatch = changedIds.flatMap((id) => this.getImports(id))
try {
await import(/* @vite-ignore */ this.options.base + url)
} catch {
this.requestFullReload(`failed to import hmr patch ${url}`)
return
}
for (const id of importsBeforePatch) {
if (this.runtime.isExecuted(id) && !this.hasExecutedImporter(id)) {
this.orphans.add(id)
}
}

await this.applyUpdate(update)
await this.notifyListeners('vite:afterUpdate', listenerPayload)
if (notify) await this.notifyListeners('vite:afterUpdate', listenerPayload)
}

private async applyInvalidate(id: string): Promise<void> {
Expand All @@ -346,24 +372,24 @@ export class BundledDevHMRClient extends HMRClient {

// no rebuild happened, so there is no patch to fetch
const update = this.computeHmrUpdate(importers, { firstInvalidatedBy })
if (update.type === 'noop') return
if (update.type === 'full-reload') {
this.requestFullReload(update.reason)
return
}

const notify = update.boundaries.length > 0
const listenerPayload = this.toUpdatePayload(
update.boundaries,
firstInvalidatedBy,
)
await this.notifyListeners('vite:beforeUpdate', listenerPayload)
if (notify) await this.notifyListeners('vite:beforeUpdate', listenerPayload)
if (this.options.beforeApply() === 'reload') return
await this.applyUpdate(update, firstInvalidatedBy)
await this.notifyListeners('vite:afterUpdate', listenerPayload)
if (notify) await this.notifyListeners('vite:afterUpdate', listenerPayload)
}

private async applyUpdate(
update: Extract<HmrUpdate, { type: 'boundaries' }>,
update: Extract<HmrUpdate, { type: 'update' }>,
firstInvalidatedBy?: string,
): Promise<void> {
for (const id of update.updateSet) {
Expand Down
106 changes: 100 additions & 6 deletions playground/hmr/__tests__/hmr.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1062,13 +1062,13 @@ if (!isBuild) {

await expect
.poll(() => page.textContent('.intermediate-file-delete-display'))
.toMatch('count is 1')
.toBe('count is 1')

// add state
await page.click('.intermediate-file-delete-increment')
await expect
.poll(() => page.textContent('.intermediate-file-delete-display'))
.toMatch('count is 2')
.toBe('count is 2')

// update import, hmr works
editFile('intermediate-file-delete/index.js', (code) =>
Expand All @@ -1079,29 +1079,29 @@ if (!isBuild) {
)
await expect
.poll(() => page.textContent('.intermediate-file-delete-display'))
.toMatch('count is 2!')
.toBe('count is 2!')

// remove unused file. Plain dev reloads the page, because the file is now
// an entry point in its module graph. Bundled dev keeps the page as is: the
// file is no longer in the bundle, so nothing changes.
Comment on lines 1084 to 1086

@h-a-n-a h-a-n-a Oct 20, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wrote this previously but it turned out to be a mistake. Previously, bundled-dev didn't keep the page as is and the reason it was kept is because of the one update bug I mentioned in the comment section above so it sometime passes the test case (i.e. keeping the page as-is).

removeFile('intermediate-file-delete/re-export.js')
await expect
.poll(() => page.textContent('.intermediate-file-delete-display'))
.toMatch(isBundledDev ? 'count is 2!' : 'count is 1!')
.toBe(isBundledDev ? 'count is 2!' : 'count is 1!')

// re-add state
await page.click('.intermediate-file-delete-increment')
await expect
.poll(() => page.textContent('.intermediate-file-delete-display'))
.toMatch(isBundledDev ? 'count is 3!' : 'count is 2!')
.toBe(isBundledDev ? 'count is 3!' : 'count is 2!')

// hmr works after file deletion
editFile('intermediate-file-delete/display.js', (code) =>
code.replace('count is ${count}!', 'count is ${count}'),
)
await expect
.poll(() => page.textContent('.intermediate-file-delete-display'))
.toMatch(isBundledDev ? 'count is 3' : 'count is 2')
.toBe(isBundledDev ? 'count is 3' : 'count is 2')
})

test(
Expand Down Expand Up @@ -1212,6 +1212,100 @@ if (!isBuild) {
},
)

test('importing an unused file again should not use old code', async () => {
await page.goto(viteTestUrl)

const display = () => page.textContent('.orphan-reimport-display')

await expect.poll(display).toBe('count is 1')

await page.click('.orphan-reimport-increment')
await expect.poll(display).toBe('count is 2')

// re-export.js is no longer imported
await untilBrowserLogAfter(
() =>
editFile('orphan-reimport/index.js', (code) =>
code.replace("from './re-export.js'", "from './display.js'"),
),
hotUpdatedLog('orphan-reimport/index.js'),
)

// update a dependency of re-export.js. Plain dev reloads the page, because
// re-export.js has no importers, so it is an entry point in its module graph.
// Bundled dev applies the update and stops at re-export.js.
editFile('orphan-reimport/display.js', (code) =>
code.replace('count is ${count}', 'count is ${count}!'),
)
await expect
.poll(display)
.toBe(isBundledDev ? 'count is 2!' : 'count is 1!')

// import re-export.js again
await untilBrowserLogAfter(
() =>
editFile('orphan-reimport/index.js', (code) =>
code.replace("from './display.js'", "from './re-export.js'"),
),
hotUpdatedLog('orphan-reimport/index.js'),
)
await expect
.poll(display)
.toBe(isBundledDev ? 'count is 2!' : 'count is 1!')
})

test('updating a file that only an unused file imports should not keep old code', async () => {
await page.goto(viteTestUrl)

const display = () => page.textContent('.orphan-no-boundary-display')

await expect.poll(display).toBe('count is 1')

await page.click('.orphan-no-boundary-increment')
await expect.poll(display).toBe('count is 2')

// re-export.js and display.js are no longer imported
await untilBrowserLogAfter(
() =>
editFile('orphan-no-boundary/index.js', (code) =>
code.replace("from './re-export.js'", "from './local.js'"),
),
hotUpdatedLog('orphan-no-boundary/index.js'),
)
await expect.poll(display).toBe('local 2')

// update display.js. Plain dev reloads the page, because re-export.js has
// no importers, so it is an entry point in its module graph. Bundled dev
// finds no hmr boundary, so nothing runs again and no update is logged.
// Wait for the dispose log instead, so that this edit is handled on its own
// and not in the same update as the next edit.
const editDisplay = () =>
editFile('orphan-no-boundary/display.js', (code) =>
code.replace('count is ${count}', 'count is ${count}!'),
)
if (isBundledDev) {
await untilBrowserLogAfter(
editDisplay,
'[orphan-no-boundary] re-export.js disposed',
)
} else {
editDisplay()
}
await expect.poll(display).toBe(isBundledDev ? 'local 2' : 'local 1')

// import re-export.js again
await untilBrowserLogAfter(
() =>
editFile('orphan-no-boundary/index.js', (code) =>
code.replace("from './local.js'", "from './re-export.js'"),
),
hotUpdatedLog('orphan-no-boundary/index.js'),
)
await expect
.poll(display)
.toBe(isBundledDev ? 'count is 2!' : 'count is 1!')
})

test('import.meta.hot?.accept', async () => {
await gotoLatestBuild(viteTestUrl)

Expand Down
2 changes: 2 additions & 0 deletions playground/hmr/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import './invalidation-circular-deps'
import './file-delete-restore'
import './optional-chaining/parent'
import './intermediate-file-delete'
import './orphan-reimport'
import './orphan-no-boundary'
import './circular'
import './prune'
import logoNoInline from './logo-no-inline.svg'
Expand Down
4 changes: 4 additions & 0 deletions playground/hmr/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@
<div class="optional-chaining"></div>
<button class="intermediate-file-delete-increment">1</button>
<div class="intermediate-file-delete-display"></div>
<button class="orphan-reimport-increment">1</button>
<div class="orphan-reimport-display"></div>
<button class="orphan-no-boundary-increment">1</button>
<div class="orphan-no-boundary-display"></div>
<img id="logo" />
<img id="logo-no-inline" />
<div class="circular"></div>
Expand Down
1 change: 1 addition & 0 deletions playground/hmr/orphan-no-boundary/display.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const displayCount = (count) => `count is ${count}`
21 changes: 21 additions & 0 deletions playground/hmr/orphan-no-boundary/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { displayCount } from './re-export.js'

const button = document.querySelector('.orphan-no-boundary-increment')

const render = () => {
document.querySelector('.orphan-no-boundary-display').textContent =
displayCount(Number(button.textContent))
}

render()

const increment = () => {
button.textContent = `${Number(button.textContent) + 1}`
render()
}
button.addEventListener('click', increment)

if (import.meta.hot) {
import.meta.hot.accept()
import.meta.hot.dispose(() => button.removeEventListener('click', increment))
}
1 change: 1 addition & 0 deletions playground/hmr/orphan-no-boundary/local.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const displayCount = (count) => `local ${count}`
7 changes: 7 additions & 0 deletions playground/hmr/orphan-no-boundary/re-export.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export * from './display.js'

if (import.meta.hot) {
import.meta.hot.dispose(() =>
console.log('[orphan-no-boundary] re-export.js disposed'),
)
}
1 change: 1 addition & 0 deletions playground/hmr/orphan-reimport/display.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const displayCount = (count) => `count is ${count}`
22 changes: 22 additions & 0 deletions playground/hmr/orphan-reimport/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { displayCount } from './re-export.js'

const button = document.querySelector('.orphan-reimport-increment')

const render = () => {
document.querySelector('.orphan-reimport-display').textContent = displayCount(
Number(button.textContent),
)
}

render()

const increment = () => {
button.textContent = `${Number(button.textContent) + 1}`
render()
}
button.addEventListener('click', increment)

if (import.meta.hot) {
import.meta.hot.accept()
import.meta.hot.dispose(() => button.removeEventListener('click', increment))
}
1 change: 1 addition & 0 deletions playground/hmr/orphan-reimport/re-export.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './display.js'
Loading