diff --git a/.changeset/big-shirts-travel.md b/.changeset/big-shirts-travel.md new file mode 100644 index 000000000000..2adfa3e4e6e4 --- /dev/null +++ b/.changeset/big-shirts-travel.md @@ -0,0 +1,5 @@ +--- +'@astrojs/svelte': patch +--- + +When using Svelte 5, slots can now be rendered as snippets diff --git a/packages/integrations/svelte/client-v5.js b/packages/integrations/svelte/client-v5.js index b3d2e1964eb8..eaa06974c242 100644 --- a/packages/integrations/svelte/client-v5.js +++ b/packages/integrations/svelte/client-v5.js @@ -1,4 +1,8 @@ import { mount } from 'svelte'; +import { add_snippet_symbol } from 'svelte/internal'; + +// Allow a slot to be rendered as a snippet (dev validation only) +const tagSlotAsSnippet = import.meta.env.DEV ? add_snippet_symbol : (s) => s; export default (element) => { return async (Component, props, slotted) => { @@ -32,7 +36,7 @@ function createSlotDefinition(key, children) { /** * @param {Comment} $$anchor A comment node for slots in Svelte 5 */ - return ($$anchor, _$$slotProps) => { + const fn = ($$anchor, _$$slotProps) => { const parent = $$anchor.parentNode; const el = document.createElement('div'); el.innerHTML = `${children}`; parent.insertBefore(el.children[0], $$anchor); }; + return tagSlotAsSnippet(fn); } diff --git a/packages/integrations/svelte/server-v5.js b/packages/integrations/svelte/server-v5.js index 105b843fb1bf..e1d246ff4e26 100644 --- a/packages/integrations/svelte/server-v5.js +++ b/packages/integrations/svelte/server-v5.js @@ -1,4 +1,8 @@ import { render } from 'svelte/server'; +import { add_snippet_symbol } from 'svelte/internal'; + +// Allow a slot to be rendered as a snippet (dev validation only) +const tagSlotAsSnippet = import.meta.env.DEV ? add_snippet_symbol : (s) => s; function check(Component) { // Svelte 5 generated components always accept these two props @@ -18,10 +22,10 @@ async function renderToStaticMarkup(Component, props, slotted, metadata) { let $$slots = undefined; for (const [key, value] of Object.entries(slotted)) { if (key === 'default') { - children = () => `<${tagName}>${value}`; + children = tagSlotAsSnippet(() => `<${tagName}>${value}`); } else { $$slots ??= {}; - $$slots[key] = () => `<${tagName} name="${key}">${value}`; + $$slots[key] = tagSlotAsSnippet(() => `<${tagName} name="${key}">${value}`); } }