fix: better support for top-level snippet declarations (#9898)

pull/9900/head
Dominic Gannaway 2 years ago committed by GitHub
parent a8e5cc83cd
commit 0236cf87e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: better support for top-level snippet declarations

@ -2477,7 +2477,14 @@ export const template_visitors = {
body = /** @type {import('estree').BlockStatement} */ (context.visit(node.body)); body = /** @type {import('estree').BlockStatement} */ (context.visit(node.body));
} }
context.state.init.push(b.const(node.expression, b.arrow(args, body))); const path = context.path;
// If we're top-level, then we can create a function for the snippet so that it can be referenced
// in the props declaration (default value pattern).
if (path.length === 1 && path[0].type === 'Fragment') {
context.state.init.push(b.function_declaration(node.expression, args, body));
} else {
context.state.init.push(b.const(node.expression, b.arrow(args, body)));
}
if (context.state.options.dev) { if (context.state.options.dev) {
context.state.init.push(b.stmt(b.call('$.add_snippet_symbol', node.expression))); context.state.init.push(b.stmt(b.call('$.add_snippet_symbol', node.expression)));
} }

@ -0,0 +1,8 @@
import { test } from '../../test';
export default test({
compileOptions: {
dev: true // Render in dev mode to check that the validation error is not thrown
},
html: `<p>hello world</p>`
});

@ -0,0 +1,7 @@
<script>
const {children = snippet} = $props();
</script>
{@render children()}
{#snippet snippet()}
<p>hello world</p>
{/snippet}
Loading…
Cancel
Save