From e16a01b9c509bf99754408d6ffb2af57f364d33d Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Fri, 27 Nov 2026 13:53:55 +0800 Subject: [PATCH] fix(svelte): hydrate server-rendered islands --- docs/guide/pages-routing/islands.md | 2 + packages/md/src/emit-svelte.ts | 2 +- packages/svelte/src/plugin-islands.ts | 13 ++- .../test/integration/island-hydration.test.ts | 93 +++++++++++++++++++ test/island-css-build.ts | 4 +- 5 files changed, 110 insertions(+), 4 deletions(-) create mode 100644 packages/svelte/test/integration/island-hydration.test.ts diff --git a/docs/guide/pages-routing/islands.md b/docs/guide/pages-routing/islands.md index 390cd10b4..256620941 100644 --- a/docs/guide/pages-routing/islands.md +++ b/docs/guide/pages-routing/islands.md @@ -172,6 +172,8 @@ Import attributes require `"module": "ESNext"` in your `tsconfig.json`: ## Hydration Strategies +Put Svelte `` content in a page or layout. Svelte matches head blocks by component, so islands that hydrate independently can claim another instance's head tags. If the tags do not match, Svelte can remount the island and reset its DOM state. + The `island` attribute value controls _when_ the component hydrates: | Strategy | Hydrates when... | Use case | diff --git a/packages/md/src/emit-svelte.ts b/packages/md/src/emit-svelte.ts index fdec4db75..f15e63b34 100644 --- a/packages/md/src/emit-svelte.ts +++ b/packages/md/src/emit-svelte.ts @@ -53,7 +53,7 @@ setFrontmatter(__frontmatter); source += `const ${propsName} = ${propsLiteral}; `; body.push( - `
<${alias} {...${propsName}} />
`, + `
{#each [1] as _}<${alias} {...${propsName}} />{/each}
`, ); } diff --git a/packages/svelte/src/plugin-islands.ts b/packages/svelte/src/plugin-islands.ts index a65803b18..efdaa178f 100644 --- a/packages/svelte/src/plugin-islands.ts +++ b/packages/svelte/src/plugin-islands.ts @@ -78,6 +78,17 @@ export function islandsPlugin( configResolved(config) { resolvedConfig = config; isDev = config.command === 'serve'; + const compiler = config.plugins.find(({ name }) => name === 'vite-plugin-svelte:config'); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Vite erases the plugin API type. + const api = compiler?.api as { options?: SvelteOptions } | undefined; + if (isDev && api?.options) { + const previous = api.options.dynamicCompileOptions; + api.options.dynamicCompileOptions = async (input) => { + const base = await previous?.(input); + const wrapper = /^\/@void-(island-wrap|md-svelte)\//.test(input.filename); + return wrapper && input.code.includes('data-island=') ? { ...base, hmr: false } : base; + }; + } }, configureServer(server) { @@ -296,7 +307,7 @@ function generateWrapperComponent(id: string): string { let props = $props();
- + {#each [1] as _}{/each}
`; } diff --git a/packages/svelte/test/integration/island-hydration.test.ts b/packages/svelte/test/integration/island-hydration.test.ts new file mode 100644 index 000000000..30fa1db31 --- /dev/null +++ b/packages/svelte/test/integration/island-hydration.test.ts @@ -0,0 +1,93 @@ +import { join } from 'node:path'; +import { expect, it } from 'vite-plus/test'; +import { + collectBrowserDiagnostics, + waitForIslandsHydrated, +} from '../../../../test/browser-helpers.ts'; +import { buildIslandApp } from '../../../../test/island-css-build.ts'; +import { launchPagesBrowser } from '../../../../test/pages-browser.ts'; + +const media = 'media:(min-width: 1200px)'; +const files = (root: string) => ({ + 'src/Probe.svelte': ` + +`, + 'src/Empty.svelte': ``, + 'pages/layout.island.svelte': ` +
{@render children()}
`, + 'pages/index.md': ` + +# Markdown page + + +`, +}); + +it('hydrates the original DOM in Svelte layout and Markdown islands', async () => { + const build = buildIslandApp({ + packageDir: join(import.meta.dirname, '../..'), + pluginName: 'voidSvelte', + files, + }); + try { + const assets = build.output('client'); + const browser = await launchPagesBrowser(); + try { + const page = await browser.newPage({ viewport: { width: 800, height: 600 } }); + page.setDefaultTimeout(10_000); + const diagnostics = collectBrowserDiagnostics(page); + const origin = 'http://svelte-islands.test'; + await page.route(origin + '/**', (route) => { + const file = new URL(route.request().url()).pathname.slice(1) || 'index.html'; + return assets.has(file) + ? route.fulfill({ path: join(build.root, 'dist/client', file) }) + : route.fulfill({ status: 404 }); + }); + + await page.goto(origin); + expect(await page.locator('[data-island]').count()).toBe(3); + expect(await page.locator('[data-hydrated="true"]').count()).toBe(0); + const fields = await Promise.all( + ['Layout', 'Markdown'].map(async (label) => { + const input = page.getByRole('textbox', { name: label }); + const original = await input.elementHandle(); + return { label, input, original, typed: 'typed into ' + label }; + }), + ); + for (const { input, typed } of fields) { + await input.fill(typed); + } + + await page.setViewportSize({ width: 1300, height: 600 }); + await waitForIslandsHydrated(page, 3, 10_000); + await page.locator('html[data-empty-island-mounted="true"]').waitFor(); + for (const { label, input, original, typed } of fields) { + expect + .soft(await input.evaluate((node, ssrNode) => node === ssrNode, original), label) + .toBe(true); + expect.soft(await input.inputValue(), label).toBe(typed); + await page.getByRole('button', { name: label + ' clicks: 0' }).click(); + await page.getByRole('button', { name: label + ' clicks: 1' }).waitFor(); + } + + expect(diagnostics()).not.toMatch(/console\.(warning|error)|pageerror:/); + } finally { + await browser.close(); + } + } finally { + build.cleanup(); + } +}, 120_000); diff --git a/test/island-css-build.ts b/test/island-css-build.ts index 1f382f757..90cd6a661 100644 --- a/test/island-css-build.ts +++ b/test/island-css-build.ts @@ -13,7 +13,7 @@ type IslandCssApp = { /** The adapter's plugin export in `dist/plugin.mjs`, e.g. `voidReact`. */ pluginName: string; /** App files by path. `index` and `about` must ship no JavaScript. */ - files: Record; + files: Record | ((root: string) => Record); /** Rules (as minified CSS) every page must link, found once in the client build. */ expectedCss: Array; /** Extra assertions for each page. */ @@ -55,7 +55,7 @@ export default { plugins: [voidPlugin(), ${app.pluginName}(), voidMarkdown()] }; export default defineConfig({ output: 'static', worker: { compatibility_date: '2026-02-24' } }); `, 'pages/about.md': '---\ntitle: About\n---\n\n# About\n', - ...app.files, + ...(typeof app.files === 'function' ? app.files(root) : app.files), }; for (const [file, content] of Object.entries(files)) { mkdirSync(dirname(join(root, file)), { recursive: true });