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
11 changes: 8 additions & 3 deletions packages/react/src/plugin-islands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export function islandsPlugin(
},

configureServer(server) {
islandManifest.configureServer(server);
watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => {
pageScan = scan;
});
Expand Down Expand Up @@ -246,9 +247,13 @@ export async function renderIslandPage(pageObj, assetTags) {
);

const html = renderToString(element);
// The rendered islands also count: in dev, the page may have gained its
// first island after this module computed __pagesNeedingClientJS.
const __hasIslands = html.includes("data-island=");
const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component);
// Islands hydrate as separate roots. Send the page frontmatter so their
// useFrontmatter() returns the same value in the browser.
const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=")
const __frontmatterScript = __hasIslands
? islandFrontmatterScript(__pageModule.frontmatter)
: "";
const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : "";
Expand All @@ -258,10 +263,10 @@ export async function renderIslandPage(pageObj, assetTags) {

return \`<!doctype html>
<html\${htmlAttrs}>
<head>\${headHtml}\${PREAMBLE_SCRIPT}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}</head>
<head>\${headHtml}\${PREAMBLE_SCRIPT}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}</head>
<body\${bodyAttrs}>
<div id="app"\${__mdScriptAttr}>\${html}</div>
\${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""}
\${__frontmatterScript}\${__needsJS ? assetTags.body : ""}
</body>
</html>\`;
}
Expand Down
11 changes: 8 additions & 3 deletions packages/solid/src/plugin-islands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export function islandsPlugin(
},

configureServer(server) {
islandManifest.configureServer(server);
watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => {
pageScan = scan;
});
Expand Down Expand Up @@ -292,9 +293,13 @@ export async function renderIslandPage(pageObj, assetTags) {

const html = await renderToStringAsync(() => createComponent(ServerApp, {}));

// The rendered islands also count: in dev, the page may have gained its
// first island after this module computed __pagesNeedingClientJS.
const __hasIslands = html.includes("data-island=");
const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component);
// Islands hydrate as separate roots. Send the page frontmatter so their
// useFrontmatter() returns the same value in the browser.
const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=")
const __frontmatterScript = __hasIslands
? islandFrontmatterScript(__pageModule.frontmatter)
: "";
const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : "";
Expand All @@ -304,10 +309,10 @@ export async function renderIslandPage(pageObj, assetTags) {

return \`<!doctype html>
<html\${htmlAttrs}>
<head>\${headHtml}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}\${__pagesNeedingClientJS.has(pageObj.component) ? generateHydrationScript() : ""}</head>
<head>\${headHtml}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}\${__needsJS ? generateHydrationScript() : ""}</head>
<body\${bodyAttrs}>
<div id="app"\${__mdScriptAttr}>\${html}</div>
\${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""}
\${__frontmatterScript}\${__needsJS ? assetTags.body : ""}
</body>
</html>\`;
}
Expand Down
11 changes: 8 additions & 3 deletions packages/svelte/src/plugin-islands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export function islandsPlugin(
},

configureServer(server) {
islandManifest.configureServer(server);
watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => {
pageScan = scan;
});
Expand Down Expand Up @@ -342,9 +343,13 @@ export async function renderIslandPage(pageObj, assetTags) {
},
});

// The rendered islands also count: in dev, the page may have gained its
// first island after this module computed __pagesNeedingClientJS.
const __hasIslands = html.includes("data-island=");
const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component);
// Islands hydrate as separate roots. Send the page frontmatter so their
// useFrontmatter() returns the same value in the browser.
const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=")
const __frontmatterScript = __hasIslands
? islandFrontmatterScript(__pageModule.frontmatter)
: "";
const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : "";
Expand All @@ -354,10 +359,10 @@ export async function renderIslandPage(pageObj, assetTags) {

return \`<!doctype html>
<html\${htmlAttrs}>
<head>\${headHtml}\${head}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}</head>
<head>\${headHtml}\${head}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}</head>
<body\${bodyAttrs}>
<div id="app"\${__mdScriptAttr}>\${html}</div>
\${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""}
\${__frontmatterScript}\${__needsJS ? assetTags.body : ""}
</body>
</html>\`;
}
Expand Down
29 changes: 26 additions & 3 deletions packages/void/src/pages/islands-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ export type IslandManifest = {
* build may load the islands client entry before their transforms run.
*/
registerPages(pageScan: PageScanResult, pagesDir: string): void;
/**
* Invalidate the dev islands client entry when a page transform records a
* new island, so the next page load hydrates it without a server restart.
*/
configureServer(server: ViteDevServer): void;
};

/** `extensions` are tried, in order, for an island import without one. */
Expand All @@ -94,6 +99,7 @@ export function createIslandManifest(
extensions: ReadonlyArray<string>,
): IslandManifest {
const entries = new Map<string, IslandEntry>();
let server: ViteDevServer | null = null;

function register(
specifier: string,
Expand All @@ -105,7 +111,16 @@ export function createIslandManifest(
return { absPath, islandId: specifier };
}
const islandId = normalizePath(relative(root, absPath)).replace(/\.[^.]+$/, '');
const isNew = entries.get(islandId)?.componentPath !== absPath;
entries.set(islandId, { componentPath: absPath, islandId, hydrate });
if (isNew && server) {
for (const env of Object.values(server.environments)) {
const mod = env.moduleGraph.getModuleById('\0' + ISLANDS_CLIENT_ENTRY_ID);
if (mod) {
env.moduleGraph.invalidateModule(mod);
}
}
}
return { absPath, islandId };
}

Expand All @@ -129,6 +144,9 @@ export function createIslandManifest(
}
}
},
configureServer(devServer) {
server = devServer;
},
};
}

Expand Down Expand Up @@ -391,7 +409,13 @@ export type IslandClientEntryOptions = {

export function generateIslandClientEntry(options: IslandClientEntryOptions): string {
const uniqueIslands = new Map<string, string>();
for (const entry of options.manifest.entries.values()) {
for (const [key, entry] of options.manifest.entries) {
// A dev edit can delete an island the manifest recorded. Importing its
// path would fail the whole entry and stop every other island hydrating.
if (!existsSync(entry.componentPath)) {
options.manifest.entries.delete(key);
continue;
}
uniqueIslands.set(entry.islandId, entry.componentPath);
}

Expand All @@ -418,8 +442,7 @@ export function generateIslandClientEntry(options: IslandClientEntryOptions): st

// Without islands, no built page gets this script (see
// computePagesNeedingClientJS), so the entry only gives the styles a chunk to
// link. Dev keeps the runtime: it does not reload this module when a page
// gains an island.
// link. Dev keeps the runtime so a page that gains its first island hydrates.
if (!options.needsRuntime && !options.isDev) {
return lines.join('\n');
}
Expand Down
11 changes: 8 additions & 3 deletions packages/vue/src/plugin-islands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export function islandsPlugin(
},

configureServer(server) {
islandManifest.configureServer(server);
watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => {
pageScan = scan;
});
Expand Down Expand Up @@ -285,9 +286,13 @@ export async function renderIslandPage(pageObj, assetTags) {
if (Object.keys(boundaryManifest.plans).length) app.config.errorHandler = error => { renderFailure ??= { error }; };
const html = await renderToString(app);
if (renderFailure) throw renderFailure.error;
// The rendered islands also count: in dev, the page may have gained its
// first island after this module computed __pagesNeedingClientJS.
const __hasIslands = html.includes("data-island=");
const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component);
// Islands hydrate as separate roots. Send the page frontmatter so their
// useFrontmatter() returns the same value in the browser.
const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=")
const __frontmatterScript = __hasIslands
? islandFrontmatterScript(__pageModule.frontmatter)
: "";
const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : "";
Expand All @@ -297,10 +302,10 @@ export async function renderIslandPage(pageObj, assetTags) {

return \`<!doctype html>
<html\${htmlAttrs}>
<head>\${headHtml}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}</head>
<head>\${headHtml}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}</head>
<body\${bodyAttrs}>
<div id="app"\${__mdScriptAttr}>\${html}</div>
\${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""}
\${__frontmatterScript}\${__needsJS ? assetTags.body : ""}
</body>
</html>\`;
}
Expand Down
170 changes: 170 additions & 0 deletions packages/vue/test/integration/island-dev-client-entry.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import vue from '@vitejs/plugin-vue';
import { createServer } from 'vite';
import { expect, it } from 'vite-plus/test';
import { islandsPlugin } from '../../src/plugin-islands.ts';

const COUNTER = `<script setup>
import { ref } from "vue";
const count = ref(0);
</script>
<template><button @click="count++">Count {{ count }}</button></template>
`;

it('adds an island imported after the dev server loaded the islands client entry', async () => {
const root = mkdtempSync(join(import.meta.dirname, '__tmp_island_dev_client_entry_'));
const pages = join(root, 'pages');
mkdirSync(pages);
mkdirSync(join(root, 'components'));
writeFileSync(join(root, 'components/Counter.vue'), COUNTER);
writeFileSync(
join(pages, 'index.island.vue'),
`<script setup>
import Counter from "../components/Counter.vue" with { island: "load" };
</script>
<template><Counter /></template>
`,
);

const server = await createServer({
root,
configFile: false,
cacheDir: join(root, '.vite'),
logLevel: 'silent',
plugins: [vue(), ...islandsPlugin(pages)],
server: { ws: false, watch: null },
});
try {
const { client, ssr } = server.environments;
const before = await client.transformRequest('virtual:void-islands-client');
expect(before?.code).toContain('components/Counter');
expect(before?.code).not.toContain('components/Second');

cpSync(join(root, 'components/Counter.vue'), join(root, 'components/Second.vue'));
writeFileSync(
join(pages, 'index.island.vue'),
`<script setup>
import Counter from "../components/Counter.vue" with { island: "load" };
import Second from "../components/Second.vue" with { island: "load" };
</script>
<template><Counter /><Second /></template>
`,
);
// Rendering the edited page registers the new island.
await ssr.transformRequest('/pages/index.island.vue');

const after = await client.transformRequest('virtual:void-islands-client');
expect(after?.code).toContain('components/Second');
} finally {
await server.close();
rmSync(root, { recursive: true, force: true });
}
});

it('keeps the islands client entry loading after an island is deleted', async () => {
const root = mkdtempSync(join(import.meta.dirname, '__tmp_island_dev_deleted_'));
const pages = join(root, 'pages');
mkdirSync(pages);
mkdirSync(join(root, 'components'));
writeFileSync(join(root, 'components/Counter.vue'), COUNTER);
writeFileSync(join(root, 'components/Removed.vue'), COUNTER);
writeFileSync(
join(pages, 'index.island.vue'),
`<script setup>
import Counter from "../components/Counter.vue" with { island: "load" };
import Removed from "../components/Removed.vue" with { island: "load" };
</script>
<template><Counter /><Removed /></template>
`,
);

const server = await createServer({
root,
configFile: false,
cacheDir: join(root, '.vite'),
logLevel: 'silent',
plugins: [vue(), ...islandsPlugin(pages)],
server: { ws: false, watch: null },
});
try {
const { client, ssr } = server.environments;
await client.transformRequest('virtual:void-islands-client');

// Remove an island's import and file, then add another island.
rmSync(join(root, 'components/Removed.vue'));
cpSync(join(root, 'components/Counter.vue'), join(root, 'components/Added.vue'));
writeFileSync(
join(pages, 'index.island.vue'),
`<script setup>
import Counter from "../components/Counter.vue" with { island: "load" };
import Added from "../components/Added.vue" with { island: "load" };
</script>
<template><Counter /><Added /></template>
`,
);
await ssr.transformRequest('/pages/index.island.vue');

const after = await client.transformRequest('virtual:void-islands-client');
expect(after?.code).toContain('components/Counter');
expect(after?.code).toContain('components/Added');
expect(after?.code).not.toContain('components/Removed');
} finally {
await server.close();
rmSync(root, { recursive: true, force: true });
}
});

it('loads the islands client on a static island page that gains its first island', async () => {
const root = mkdtempSync(join(import.meta.dirname, '__tmp_island_dev_first_island_'));
const pages = join(root, 'pages');
const page = join(pages, 'index.island.vue');
mkdirSync(pages);
mkdirSync(join(root, 'components'));
writeFileSync(join(root, 'components/Counter.vue'), COUNTER);
writeFileSync(page, '<template><p>Static</p></template>\n');

const server = await createServer({
root,
configFile: false,
cacheDir: join(root, '.vite'),
logLevel: 'silent',
plugins: [vue(), ...islandsPlugin(pages)],
server: { ws: false, watch: null, port: 0, host: '127.0.0.1' },
});
const render = async () => {
const renderer = (await server.ssrLoadModule('virtual:void-islands-renderer')) as {
renderIslandPage(
page: { component: string; props: Record<string, unknown> },
assetTags: { css: string; preloads: string; body: string },
): Promise<string>;
};
return renderer.renderIslandPage(
{ component: 'index', props: {} },
{ css: '', preloads: '', body: '<script type="module" src="/islands.js"></script>' },
);
};
try {
// Listening runs the pages scan.
await server.listen();
expect(await render()).not.toContain('/islands.js');

writeFileSync(
page,
`<script setup>
import Counter from "../components/Counter.vue" with { island: "load" };
</script>
<template><Counter /></template>
`,
);
// What the dev server's watcher does when the page is saved.
server.environments.ssr.moduleGraph.onFileChange(page);

const html = await render();
expect(html).toContain('data-island="components/Counter"');
expect(html).toContain('/islands.js');
} finally {
await server.close();
rmSync(root, { recursive: true, force: true });
}
});