Skip to content

Commit 0236cf8

Browse files
authored
fix: better support for top-level snippet declarations (#9898)
1 parent a8e5cc8 commit 0236cf8

File tree

4 files changed

+28
-1
lines changed

4 files changed

+28
-1
lines changed

.changeset/ten-peaches-sleep.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: better support for top-level snippet declarations

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2477,7 +2477,14 @@ export const template_visitors = {
24772477
body = /** @type {import('estree').BlockStatement} */ (context.visit(node.body));
24782478
}
24792479

2480-
context.state.init.push(b.const(node.expression, b.arrow(args, body)));
2480+
const path = context.path;
2481+
// If we're top-level, then we can create a function for the snippet so that it can be referenced
2482+
// in the props declaration (default value pattern).
2483+
if (path.length === 1 && path[0].type === 'Fragment') {
2484+
context.state.init.push(b.function_declaration(node.expression, args, body));
2485+
} else {
2486+
context.state.init.push(b.const(node.expression, b.arrow(args, body)));
2487+
}
24812488
if (context.state.options.dev) {
24822489
context.state.init.push(b.stmt(b.call('$.add_snippet_symbol', node.expression)));
24832490
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { test } from '../../test';
2+
3+
export default test({
4+
compileOptions: {
5+
dev: true // Render in dev mode to check that the validation error is not thrown
6+
},
7+
html: `<p>hello world</p>`
8+
});
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<script>
2+
const {children = snippet} = $props();
3+
</script>
4+
{@render children()}
5+
{#snippet snippet()}
6+
<p>hello world</p>
7+
{/snippet}

0 commit comments

Comments
 (0)