fix: allow accessing snippet in script tag

pull/15789/head
paoloricciuti 1 year ago
parent 707682eaa9
commit c43bfebcd7

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: allow accessing snippet in script tag

@ -1,4 +1,4 @@
/** @import { ArrowFunctionExpression, BlockStatement, CallExpression } from 'estree' */
/** @import { ArrowFunctionExpression, BlockStatement, CallExpression, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import { dev } from '../../../../state.js';
@ -15,21 +15,24 @@ export function SnippetBlock(node, context) {
body.body.unshift(b.stmt(b.call('$.validate_snippet_args', b.id('$$payload'))));
}
/** @type {ArrowFunctionExpression | CallExpression} */
let fn = b.arrow([b.id('$$payload'), ...node.parameters], body);
let fn = b.function_declaration(
node.expression,
[b.id('$$payload'), ...node.parameters],
/** @type {BlockStatement} */ (context.visit(node.body))
);
const push_to = node.metadata.can_hoist ? context.state.hoisted : context.state.init;
if (dev) {
fn = b.call('$.prevent_snippet_stringification', fn);
push_to.push(b.stmt(b.call('$.prevent_snippet_stringification', fn.id)));
}
const declaration = b.declaration('const', [b.declarator(node.expression, fn)]);
// @ts-expect-error - TODO remove this hack once $$render_inner for legacy bindings is gone
fn.___snippet = true;
if (node.metadata.can_hoist) {
context.state.hoisted.push(declaration);
push_to.push(fn);
} else {
context.state.init.push(declaration);
push_to.push(fn);
}
}

@ -0,0 +1,7 @@
import { test } from '../../test';
export default test({
compileOptions: {
dev: true
}
});

@ -0,0 +1,3 @@
export function fn(snippet) {
return snippet;
}

@ -0,0 +1,10 @@
<script>
import { fn } from "./fn.js";
let variable = $state("var");
fn(test);
</script>
{#snippet test()}
{variable}
{/snippet}

@ -0,0 +1 @@
Subproject commit 97817a95d6fa2d3f72c03f04a1e0882a7650cd16
Loading…
Cancel
Save