diff --git a/.changeset/new-fireants-bake.md b/.changeset/new-fireants-bake.md new file mode 100644 index 0000000000..81bd596e43 --- /dev/null +++ b/.changeset/new-fireants-bake.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: move store setup/cleanup outside of async component body diff --git a/packages/svelte/src/compiler/phases/3-transform/client/transform-client.js b/packages/svelte/src/compiler/phases/3-transform/client/transform-client.js index 7f25e6c0d2..124438a9da 100644 --- a/packages/svelte/src/compiler/phases/3-transform/client/transform-client.js +++ b/packages/svelte/src/compiler/phases/3-transform/client/transform-client.js @@ -209,7 +209,8 @@ export function client_component(analysis, options) { /** @type {ESTree.Statement[]} */ const store_setup = []; - + /** @type {ESTree.Statement} */ + let store_init = b.empty; /** @type {ESTree.VariableDeclaration[]} */ const legacy_reactive_declarations = []; @@ -227,8 +228,9 @@ export function client_component(analysis, options) { if (binding.kind === 'store_sub') { if (store_setup.length === 0) { needs_store_cleanup = true; - store_setup.push( - b.const(b.array_pattern([b.id('$$stores'), b.id('$$cleanup')]), b.call('$.setup_stores')) + store_init = b.const( + b.array_pattern([b.id('$$stores'), b.id('$$cleanup')]), + b.call('$.setup_stores') ); } @@ -385,9 +387,16 @@ export function client_component(analysis, options) { analysis.slot_names.size > 0; if (analysis.instance.has_await) { + const params = [b.id('$$anchor')]; + if (should_inject_props) { + params.push(b.id('$$props')); + } + if (store_setup.length > 0) { + params.push(b.id('$$stores')); + } const body = b.function_declaration( b.id('$$body'), - should_inject_props ? [b.id('$$anchor'), b.id('$$props')] : [b.id('$$anchor')], + params, b.block([ b.var('$$unsuspend', b.call('$.suspend')), ...component_block.body, @@ -403,10 +412,12 @@ export function client_component(analysis, options) { component_block = b.block([ b.var('fragment', b.call('$.comment')), b.var('node', b.call('$.first_child', b.id('fragment'))), - b.stmt(b.call(body.id, b.id('node'), should_inject_props && b.id('$$props'))), + store_init, + b.stmt(b.call(body.id, b.id('node'), ...params.slice(1))), b.stmt(b.call('$.append', b.id('$$anchor'), b.id('fragment'))) ]); } else { + component_block.body.unshift(store_init); component_block.body.push(.../** @type {ESTree.Statement[]} */ (template.body)); }