Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/guide/pages-routing/islands.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@ Import attributes require `"module": "ESNext"` in your `tsconfig.json`:

## Hydration Strategies

Put Svelte `<svelte:head>` 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 |
Expand Down
2 changes: 1 addition & 1 deletion packages/md/src/emit-svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ setFrontmatter(__frontmatter);
source += `const ${propsName} = ${propsLiteral};
`;
body.push(
`<div data-island="${chunk.islandImport.islandId}" data-props={JSON.stringify(${propsName})} data-hydrate="${chunk.islandImport.strategy}"><${alias} {...${propsName}} /></div>`,
`<div data-island="${chunk.islandImport.islandId}" data-props={JSON.stringify(${propsName})} data-hydrate="${chunk.islandImport.strategy}">{#each [1] as _}<${alias} {...${propsName}} />{/each}</div>`,
);
}

Expand Down
13 changes: 12 additions & 1 deletion packages/svelte/src/plugin-islands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -296,7 +307,7 @@ function generateWrapperComponent(id: string): string {
let props = $props();
</script>
<div data-island="${islandId}" data-props={serializePageData(props)} data-hydrate="${hydrate}">
<Cmp {...props} />
{#each [1] as _}<Cmp {...props} />{/each}
</div>
`;
}
Expand Down
93 changes: 93 additions & 0 deletions packages/svelte/test/integration/island-hydration.test.ts
Original file line number Diff line number Diff line change
@@ -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': `<script>
let { label } = $props();
let value = $state('initial');
let clicks = $state(0);
</script>
<label>{label}<input bind:value /></label>
<button type="button" onclick={() => clicks++}>{label} clicks: {clicks}</button>`,
'src/Empty.svelte': `<script>
import { onMount } from 'svelte';
onMount(() => { document.documentElement.dataset.emptyIslandMounted = 'true'; });
</script>`,
'pages/layout.island.svelte': `<script>
import Probe from '../src/Probe.svelte' with { island: '${media}' };
import Empty from '../src/Empty.svelte' with { island: '${media}' };
let { children } = $props();
</script>
<main><Probe label="Layout" /><Empty />{@render children()}</main>`,
'pages/index.md': `<script>
import Probe from ${JSON.stringify(join(root, 'src/Probe.svelte').replaceAll('\\', '/'))} with { island: '${media}' };
</script>

# Markdown page

<Probe label="Markdown" />
`,
});

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);
4 changes: 2 additions & 2 deletions test/island-css-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>;
files: Record<string, string> | ((root: string) => Record<string, string>);
/** Rules (as minified CSS) every page must link, found once in the client build. */
expectedCss: Array<string>;
/** Extra assertions for each page. */
Expand Down Expand Up @@ -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 });
Expand Down