Skip to content

Commit bc0f21c

Browse files
authored
feat(bundled-dev): support import.meta.hot.acceptExports (#23463)
1 parent fa71469 commit bc0f21c

12 files changed

Lines changed: 211 additions & 38 deletions

File tree

‎packages/vite/src/client/bundledDevClient.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import {
1111
transport,
1212
} from './client'
1313

14+
declare const __HMR_PARTIAL_ACCEPT__: boolean
15+
1416
// keep the same public exports as `client.ts`, which this entry replaces when inlined
1517
export {
1618
createHotContext,
@@ -55,6 +57,7 @@ if (typeof DevRuntime !== 'undefined') {
5557
runtime,
5658
{
5759
base,
60+
partialAccept: __HMR_PARTIAL_ACCEPT__,
5861
beforeApply: clearOverlayOrReloadOnFirstUpdate,
5962
},
6063
)

‎packages/vite/src/client/bundledDevHmrClient.ts‎

Lines changed: 47 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type { NormalizedModuleRunnerTransport } from '../shared/moduleRunnerTran
99
/** the subset of `__rolldown_runtime__` the HMR client uses */
1010
export interface RolldownRuntimeLike {
1111
getImporters(id: string): string[]
12+
getImportedBindings(importer: string, id: string): string[] | undefined
1213
isExecuted(id: string): boolean
1314
hasFactory(id: string): boolean
1415
removeModuleCache(id: string): void
@@ -33,6 +34,7 @@ type HmrUpdate =
3334

3435
export interface BundledDevHMRClientOptions {
3536
base: string
37+
partialAccept: boolean
3638
/** returning `'reload'` aborts the apply — the hook reloads the page itself */
3739
beforeApply: () => 'reload' | 'continue'
3840
}
@@ -56,17 +58,43 @@ export class BundledDevHMRClient extends HMRClient {
5658
}
5759

5860
isSelfAccepted(id: string): boolean {
59-
return (
60-
this.hotModulesMap.get(id)?.callbacks.some((c) => c.deps.includes(id)) ??
61-
false
62-
)
61+
return this.acceptsDep(id, id)
6362
}
6463

6564
acceptsDep(parent: string, id: string): boolean {
6665
return (
6766
this.hotModulesMap
6867
.get(parent)
69-
?.callbacks.some((c) => c.deps.includes(id)) ?? false
68+
?.callbacks.some((c) => !c.exports && c.deps.includes(id)) ?? false
69+
)
70+
}
71+
72+
private getAcceptedExports(id: string): Set<string> | undefined {
73+
let accepted: Set<string> | undefined
74+
for (const c of this.hotModulesMap.get(id)?.callbacks ?? []) {
75+
if (!c.exports) continue
76+
accepted ??= new Set()
77+
for (const name of c.exports) accepted.add(name)
78+
}
79+
return accepted
80+
}
81+
82+
private acceptsAllExports(id: string, accepted: Set<string>): boolean {
83+
const exports = this.runtime.loadExports(id)
84+
if (typeof exports !== 'object' || exports == null) return false
85+
return Object.keys(exports).every((name) => accepted.has(name))
86+
}
87+
88+
private importsOnlyAccepted(
89+
parent: string,
90+
id: string,
91+
accepted: Set<string>,
92+
): boolean {
93+
if (!this.options.partialAccept) return false
94+
return (
95+
this.runtime
96+
.getImportedBindings(parent, id)
97+
?.every((name) => accepted.has(name)) ?? false
7098
)
7199
}
72100

@@ -113,18 +141,23 @@ export class BundledDevHMRClient extends HMRClient {
113141
reason: `update propagated back to ${firstInvalidatedBy}, which already called \`import.meta.hot.invalidate()\``,
114142
}
115143
}
116-
if (this.isSelfAccepted(id)) {
144+
const acceptedExports = this.getAcceptedExports(id)
145+
const selfAccepted =
146+
this.isSelfAccepted(id) ||
147+
(acceptedExports !== undefined &&
148+
this.acceptsAllExports(id, acceptedExports))
149+
if (selfAccepted || acceptedExports) {
117150
boundaries.push({
118151
boundary: id,
119152
acceptedVia: id,
120153
isWithinCircularImport: this.isNodeWithinCircularImports(id, stack),
121154
})
122-
return
155+
if (selfAccepted) return
123156
}
124157
const parents = this.runtime
125158
.getImporters(id)
126159
.filter((p) => this.runtime.isExecuted(p))
127-
if (!parents.length) {
160+
if (!acceptedExports && !parents.length) {
128161
return {
129162
type: 'full-reload',
130163
reason: `no hmr boundary found for module \`${id}\``,
@@ -143,6 +176,12 @@ export class BundledDevHMRClient extends HMRClient {
143176
})
144177
continue
145178
}
179+
if (
180+
acceptedExports &&
181+
this.importsOnlyAccepted(parent, id, acceptedExports)
182+
) {
183+
continue
184+
}
146185
if (!stack.includes(parent)) {
147186
const fullReload = this.bubble(
148187
parent,

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,9 @@ async function createClientConfigValueReplacer(
126126
const hmrTimeoutReplacement = escapeReplacement(timeout)
127127
const hmrEnableOverlayReplacement = escapeReplacement(overlay)
128128
const hmrConfigNameReplacement = escapeReplacement(hmrConfigName)
129+
const hmrPartialAcceptReplacement = escapeReplacement(
130+
config.experimental.hmrPartialAccept,
131+
)
129132
const wsTokenReplacement = escapeReplacement(config.webSocketToken)
130133
const serverForwardConsoleReplacement = escapeReplacement(
131134
config.server.forwardConsole as any,
@@ -144,6 +147,7 @@ async function createClientConfigValueReplacer(
144147
.replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement)
145148
.replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement)
146149
.replace(`__HMR_CONFIG_NAME__`, hmrConfigNameReplacement)
150+
.replace(`__HMR_PARTIAL_ACCEPT__`, hmrPartialAcceptReplacement)
147151
.replace(`__WS_TOKEN__`, wsTokenReplacement)
148152
.replace(`__SERVER_FORWARD_CONSOLE__`, serverForwardConsoleReplacement)
149153
}

‎packages/vite/src/shared/hmr.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ interface HotCallback {
1414
// the dependencies must be fetchable paths
1515
deps: string[]
1616
fn: (modules: Array<ModuleNamespace | undefined>) => void
17+
exports?: readonly string[]
1718
}
1819

1920
export interface HMRLogger {
@@ -75,13 +76,15 @@ export class HMRContext implements ViteHotContext {
7576
}
7677
}
7778

78-
// export names (first arg) are irrelevant on the client side, they're
79-
// extracted in the server for propagation
8079
acceptExports(
81-
_: string | readonly string[],
80+
exportNames: string | readonly string[],
8281
callback?: (data: any) => void,
8382
): void {
84-
this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod))
83+
this.acceptDeps(
84+
[this.ownerPath],
85+
([mod]) => callback?.(mod),
86+
typeof exportNames === 'string' ? [exportNames] : exportNames,
87+
)
8588
}
8689

8790
dispose(cb: (data: any) => void): void {
@@ -154,6 +157,7 @@ export class HMRContext implements ViteHotContext {
154157
private acceptDeps(
155158
deps: string[],
156159
callback: HotCallback['fn'] = () => {},
160+
exports?: readonly string[],
157161
): void {
158162
const mod: HotModule = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
159163
id: this.ownerPath,
@@ -162,6 +166,7 @@ export class HMRContext implements ViteHotContext {
162166
mod.callbacks.push({
163167
deps,
164168
fn: callback,
169+
exports,
165170
})
166171
this.hmrClient.hotModulesMap.set(this.ownerPath, mod)
167172
}

‎playground/hmr/__tests__/hmr.spec.ts‎

Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import {
88
editFile,
99
getBg,
1010
getColor,
11+
gotoLatestBuild,
12+
hotUpdatedLog,
1113
isBuild,
1214
isBundledDev,
1315
page,
@@ -513,26 +515,25 @@ if (!isBuild) {
513515
)
514516
})
515517

516-
// bundled dev: partial accept (`import.meta.hot.acceptExports`) is not
517-
// supported (rolldown#10061)
518-
describe.skipIf(isBundledDev)('acceptExports', () => {
518+
describe('acceptExports', () => {
519519
const HOT_UPDATED = /hot updated/
520520
const CONNECTED = /connected/
521521

522522
const baseDir = 'accept-exports'
523+
const openPage = (testDir: string) =>
524+
gotoLatestBuild(`${viteTestUrl}/${testDir}/`)
523525

524526
describe('when all used exports are accepted', () => {
525527
const testDir = baseDir + '/main-accepted'
526528

527529
const fileName = 'target.ts'
528530
const file = `${testDir}/${fileName}`
529-
const url = '/' + file
530531

531532
let dep = 'dep0'
532533

533534
beforeAll(async () => {
534535
await untilBrowserLogAfter(
535-
() => page.goto(`${viteTestUrl}/${testDir}/`),
536+
() => openPage(testDir),
536537
[CONNECTED, />>>>>>/],
537538
(logs) => {
538539
expect(logs).toContain(`<<<<<< A0 B0 D0 ; ${dep}`)
@@ -543,7 +544,6 @@ if (!isBuild) {
543544

544545
it('the callback is called with the new version the module', async () => {
545546
const callbackFile = `${testDir}/callback.ts`
546-
const callbackUrl = '/' + callbackFile
547547

548548
await untilBrowserLogAfter(
549549
() => {
@@ -557,7 +557,7 @@ if (!isBuild) {
557557
(logs) => {
558558
expect(logs).toEqual([
559559
'reloaded >>> Y',
560-
`[vite] hot updated: ${callbackUrl}`,
560+
hotUpdatedLog(callbackFile),
561561
])
562562
},
563563
)
@@ -572,7 +572,7 @@ if (!isBuild) {
572572
(logs) => {
573573
expect(logs).toEqual([
574574
'reloaded (2) >>> Z',
575-
`[vite] hot updated: ${callbackUrl}`,
575+
hotUpdatedLog(callbackFile),
576576
])
577577
},
578578
)
@@ -593,7 +593,7 @@ if (!isBuild) {
593593
(logs) => {
594594
expect(logs).toEqual([
595595
`<<<<<< A0 B0 D0 ; ${dep}`,
596-
`[vite] hot updated: ${url}`,
596+
hotUpdatedLog(file),
597597
])
598598
},
599599
)
@@ -608,7 +608,7 @@ if (!isBuild) {
608608
(logs) => {
609609
expect(logs).toEqual([
610610
`<<<<<< A1 B1 D1 ; ${dep}`,
611-
`[vite] hot updated: ${url}`,
611+
hotUpdatedLog(file),
612612
])
613613
},
614614
)
@@ -632,7 +632,7 @@ if (!isBuild) {
632632
(logs) => {
633633
expect(logs).toEqual([
634634
`<<<<<< A2 B2 D2 ; ${dep}`,
635-
`[vite] hot updated: ${url}`,
635+
hotUpdatedLog(file),
636636
])
637637
},
638638
)
@@ -668,7 +668,7 @@ if (!isBuild) {
668668

669669
beforeAll(async () => {
670670
await untilBrowserLogAfter(
671-
() => page.goto(`${viteTestUrl}/${testDir}/`),
671+
() => openPage(testDir),
672672
[CONNECTED, />>>>>>/],
673673
(logs) => {
674674
expect(logs).toContain(`<<< named: ${a} ; ${dep}`)
@@ -731,7 +731,7 @@ if (!isBuild) {
731731
const file = 'side-effects.ts'
732732

733733
await untilBrowserLogAfter(
734-
() => page.goto(`${viteTestUrl}/${testDir}/`),
734+
() => openPage(testDir),
735735
[CONNECTED, />>>/],
736736
(logs) => {
737737
expect(logs).toContain('>>> side FX')
@@ -748,7 +748,7 @@ if (!isBuild) {
748748
(logs) => {
749749
expect(logs).toEqual([
750750
'>>> side FX !!',
751-
`[vite] hot updated: /${testDir}/${file}`,
751+
hotUpdatedLog(`${testDir}/${file}`),
752752
])
753753
},
754754
)
@@ -760,10 +760,9 @@ if (!isBuild) {
760760
test('accepts itself if no exports are imported', async () => {
761761
const fileName = 'unused.ts'
762762
const file = `${testDir}/${fileName}`
763-
const url = '/' + file
764763

765764
await untilBrowserLogAfter(
766-
() => page.goto(`${viteTestUrl}/${testDir}/`),
765+
() => openPage(testDir),
767766
[CONNECTED, '-- unused --'],
768767
(logs) => {
769768
expect(logs).toContain('-- unused --')
@@ -779,7 +778,7 @@ if (!isBuild) {
779778
},
780779
HOT_UPDATED,
781780
(logs) => {
782-
expect(logs).toEqual(['-> unused <-', `[vite] hot updated: ${url}`])
781+
expect(logs).toEqual(['-> unused <-', hotUpdatedLog(file)])
783782
},
784783
)
785784
})
@@ -789,7 +788,7 @@ if (!isBuild) {
789788
const file = `${testDir}/${fileName}`
790789

791790
await untilBrowserLogAfter(
792-
() => page.goto(`${viteTestUrl}/${testDir}/`),
791+
() => openPage(testDir),
793792
[CONNECTED, '-- used --'],
794793
(logs) => {
795794
expect(logs).toContain('-- used --')
@@ -824,10 +823,9 @@ if (!isBuild) {
824823
it('accepts itself if all its exports are accepted', async () => {
825824
const fileName = 'deps-all-accepted.ts'
826825
const file = `${testDir}/${fileName}`
827-
const url = '/' + file
828826

829827
await untilBrowserLogAfter(
830-
() => page.goto(`${viteTestUrl}/${testDir}/`),
828+
() => openPage(testDir),
831829
[CONNECTED, '>>> ready <<<'],
832830
(logs) => {
833831
expect(logs).toContain('loaded:all:a0b0c0default0')
@@ -843,7 +841,7 @@ if (!isBuild) {
843841
(logs) => {
844842
expect(logs).toEqual([
845843
'all >>>>>> a1, b1, c1',
846-
`[vite] hot updated: ${url}`,
844+
hotUpdatedLog(file),
847845
])
848846
},
849847
)
@@ -856,7 +854,7 @@ if (!isBuild) {
856854
(logs) => {
857855
expect(logs).toEqual([
858856
'all >>>>>> a2, b2, c2',
859-
`[vite] hot updated: ${url}`,
857+
hotUpdatedLog(file),
860858
])
861859
},
862860
)
@@ -867,7 +865,7 @@ if (!isBuild) {
867865
const file = `${testDir}/${fileName}`
868866

869867
await untilBrowserLogAfter(
870-
() => page.goto(`${viteTestUrl}/${testDir}/`),
868+
() => openPage(testDir),
871869
[CONNECTED, '>>> ready <<<'],
872870
(logs) => {
873871
expect(logs).toContain('loaded:some:a0b0c0default0')

0 commit comments

Comments
 (0)