Skip to content

Commit 40ac2ca

Browse files
authored
chore: treeshakeable store subs (#10506)
* make store subscriptions treeshakeable on the server * drive-by fix * changeset --------- Co-authored-by: Rich Harris <[email protected]>
1 parent df10204 commit 40ac2ca

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

.changeset/brown-months-fry.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+
chore: treeshake unused store subscriptions in SSR mode

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

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,7 @@ function serialize_get_binding(node, state) {
322322
const store_id = b.id(node.name.slice(1));
323323
return b.call(
324324
'$.store_get',
325-
b.id('$$store_subs'),
325+
b.assignment('??=', b.id('$$store_subs'), b.object([])),
326326
b.literal(node.name),
327327
serialize_get_binding(store_id, state)
328328
);
@@ -460,7 +460,7 @@ function serialize_set_binding(node, context, fallback) {
460460
} else if (is_store) {
461461
return b.call(
462462
'$.mutate_store',
463-
b.id('$$store_subs'),
463+
b.assignment('??=', b.id('$$store_subs'), b.object([])),
464464
b.literal(left.name),
465465
b.id(left_name),
466466
b.assignment(node.operator, /** @type {import('estree').Pattern} */ (visit(node.left)), value)
@@ -506,7 +506,11 @@ const global_visitors = {
506506
if (node.prefix) fn += '_pre';
507507

508508
/** @type {import('estree').Expression[]} */
509-
const args = [b.id('$$store_subs'), b.literal(argument.name), b.id(argument.name.slice(1))];
509+
const args = [
510+
b.assignment('??=', b.id('$$store_subs'), b.object([])),
511+
b.literal(argument.name),
512+
b.id(argument.name.slice(1))
513+
];
510514
if (node.operator === '--') {
511515
args.push(b.literal(-1));
512516
}
@@ -2094,8 +2098,10 @@ export function server_component(analysis, options) {
20942098
(binding) => binding.kind === 'store_sub'
20952099
)
20962100
) {
2097-
instance.body.unshift(b.const('$$store_subs', b.object([])));
2098-
template.body.push(b.stmt(b.call('$.unsubscribe_stores', b.id('$$store_subs'))));
2101+
instance.body.unshift(b.var('$$store_subs'));
2102+
template.body.push(
2103+
b.if(b.id('$$store_subs'), b.stmt(b.call('$.unsubscribe_stores', b.id('$$store_subs'))))
2104+
);
20992105
}
21002106
// Propagate values of bound props upwards if they're undefined in the parent and have a value.
21012107
// Don't do this as part of the props retrieval because people could eagerly mutate the prop in the instance script.

0 commit comments

Comments
 (0)