Skip to content

Commit 436cc99

Browse files
authored
fix: always pass original component to HMR wrapper (#12454)
When Vite calls `hot.accept`, it passes the wrapped component, which means we're passing the HMR wrapper along as the new component. Avoid that by maintaining a reference to the original component.
1 parent 1ce4cd5 commit 436cc99

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

.changeset/itchy-lemons-punch.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: always pass original component to HMR wrapper

packages/svelte/src/compiler/phases/3-transform/client/transform-client.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -418,7 +418,7 @@ export function client_component(source, analysis, options) {
418418

419419
if (options.hmr) {
420420
const accept_fn_body = [
421-
b.stmt(b.call('$.set', b.id('s'), b.member(b.id('module'), b.id('default'))))
421+
b.stmt(b.call('$.set', b.id('s'), b.member(b.id('module.default'), b.id('original'))))
422422
];
423423

424424
if (analysis.css.hash) {
@@ -440,8 +440,14 @@ export function client_component(source, analysis, options) {
440440
const hmr = b.block([
441441
b.const(b.id('s'), b.call('$.source', b.id(analysis.name))),
442442
b.const(b.id('filename'), b.member(b.id(analysis.name), b.id('filename'))),
443+
b.const(b.id('$$original'), b.id(analysis.name)),
443444
b.stmt(b.assignment('=', b.id(analysis.name), b.call('$.hmr', b.id('s')))),
444445
b.stmt(b.assignment('=', b.member(b.id(analysis.name), b.id('filename')), b.id('filename'))),
446+
// Assign the original component to the wrapper so we can use it on hot reload patching,
447+
// else we would call the HMR function two times
448+
b.stmt(
449+
b.assignment('=', b.member(b.id(analysis.name), b.id('original')), b.id('$$original'))
450+
),
445451
b.stmt(b.call('import.meta.hot.accept', b.arrow([b.id('module')], b.block(accept_fn_body))))
446452
]);
447453

packages/svelte/tests/snapshot/samples/hmr/_expected/client/index.svelte.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,14 @@ function Hmr($$anchor) {
1212
if (import.meta.hot) {
1313
const s = $.source(Hmr);
1414
const filename = Hmr.filename;
15+
const $$original = Hmr;
1516

1617
Hmr = $.hmr(s);
1718
Hmr.filename = filename;
19+
Hmr.original = $$original;
1820

1921
import.meta.hot.accept((module) => {
20-
$.set(s, module.default);
22+
$.set(s, module.default.original);
2123
});
2224
}
2325

0 commit comments

Comments
 (0)