diff --git a/packages/react/src/plugin-islands.ts b/packages/react/src/plugin-islands.ts index ef182c7ff..fe00202ac 100644 --- a/packages/react/src/plugin-islands.ts +++ b/packages/react/src/plugin-islands.ts @@ -64,6 +64,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); @@ -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)}"\` : ""; @@ -258,10 +263,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${PREAMBLE_SCRIPT}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""} +\${headHtml}\${PREAMBLE_SCRIPT}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}
\${html}
- \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} + \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} \`; } diff --git a/packages/solid/src/plugin-islands.ts b/packages/solid/src/plugin-islands.ts index 16c9e8ced..7e689a0f8 100644 --- a/packages/solid/src/plugin-islands.ts +++ b/packages/solid/src/plugin-islands.ts @@ -85,6 +85,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); @@ -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)}"\` : ""; @@ -304,10 +309,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}\${__pagesNeedingClientJS.has(pageObj.component) ? generateHydrationScript() : ""} +\${headHtml}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}\${__needsJS ? generateHydrationScript() : ""}
\${html}
- \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} + \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} \`; } diff --git a/packages/svelte/src/plugin-islands.ts b/packages/svelte/src/plugin-islands.ts index 4f650c596..c31848c19 100644 --- a/packages/svelte/src/plugin-islands.ts +++ b/packages/svelte/src/plugin-islands.ts @@ -79,6 +79,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); @@ -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)}"\` : ""; @@ -354,10 +359,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${head}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""} +\${headHtml}\${head}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}
\${html}
- \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} + \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} \`; } diff --git a/packages/void/src/pages/islands-plugin.ts b/packages/void/src/pages/islands-plugin.ts index f351e3a2a..19988baf4 100644 --- a/packages/void/src/pages/islands-plugin.ts +++ b/packages/void/src/pages/islands-plugin.ts @@ -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. */ @@ -94,6 +99,7 @@ export function createIslandManifest( extensions: ReadonlyArray, ): IslandManifest { const entries = new Map(); + let server: ViteDevServer | null = null; function register( specifier: string, @@ -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 }; } @@ -129,6 +144,9 @@ export function createIslandManifest( } } }, + configureServer(devServer) { + server = devServer; + }, }; } @@ -391,7 +409,13 @@ export type IslandClientEntryOptions = { export function generateIslandClientEntry(options: IslandClientEntryOptions): string { const uniqueIslands = new Map(); - 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); } @@ -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'); } diff --git a/packages/vue/src/plugin-islands.ts b/packages/vue/src/plugin-islands.ts index 3b7092cb5..74cd2eabd 100644 --- a/packages/vue/src/plugin-islands.ts +++ b/packages/vue/src/plugin-islands.ts @@ -72,6 +72,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); @@ -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)}"\` : ""; @@ -297,10 +302,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""} +\${headHtml}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}
\${html}
- \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} + \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} \`; } diff --git a/packages/vue/test/integration/island-dev-client-entry.test.ts b/packages/vue/test/integration/island-dev-client-entry.test.ts new file mode 100644 index 000000000..fda7cc7f2 --- /dev/null +++ b/packages/vue/test/integration/island-dev-client-entry.test.ts @@ -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 = ` + +`; + +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'), + ` + +`, + ); + + 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'), + ` + +`, + ); + // 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'), + ` + +`, + ); + + 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'), + ` + +`, + ); + 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, '\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 }, + assetTags: { css: string; preloads: string; body: string }, + ): Promise; + }; + return renderer.renderIslandPage( + { component: 'index', props: {} }, + { css: '', preloads: '', body: '' }, + ); + }; + try { + // Listening runs the pages scan. + await server.listen(); + expect(await render()).not.toContain('/islands.js'); + + writeFileSync( + page, + ` + +`, + ); + // 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 }); + } +});