Skip to content
Merged
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
54 changes: 40 additions & 14 deletions src/plugins/prerender-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ export function prerenderPlugin({ prerenderScript, renderTarget, additionalPrere
let viteConfig = {};
let userEnabledSourceMaps;
let ssrBuild = false;
let prerenderEntryHtml;

/** @type {import('./types.d.ts').PrerenderedRoute[]} */
let routes = [];
Expand All @@ -90,12 +91,9 @@ export function prerenderPlugin({ prerenderScript, renderTarget, additionalPrere
const tmpDirId = 'headless-prerender';

/**
* From the non-external scripts in entry HTML document, find the one (if any)
* that provides a `prerender` export
*
* @param {import('vite').Rollup.InputOption} input
*/
const getPrerenderScriptFromHTML = async (input) => {
const getPrerenderEntryHtml = (input) => {
Comment thread
JoviDeCroock marked this conversation as resolved.
// prettier-ignore
const entryHtml =
typeof input === "string"
Expand All @@ -106,7 +104,17 @@ export function prerenderPlugin({ prerenderScript, renderTarget, additionalPrere

if (!entryHtml) throw new Error('Unable to detect entry HTML');

const htmlDoc = htmlParse(await fs.readFile(entryHtml, 'utf-8'));
return path.resolve(viteConfig.root, entryHtml);
};

/**
* From the non-external scripts in the entry HTML document, find the one (if any)
* that provides a `prerender` export
*/
const getPrerenderScriptFromHtml = async () => {
if (!prerenderEntryHtml) throw new Error('Unable to detect entry HTML');

const htmlDoc = htmlParse(await fs.readFile(prerenderEntryHtml, 'utf-8'));

const entryScriptTag = htmlDoc
.getElementsByTagName('script')
Expand All @@ -118,7 +126,9 @@ export function prerenderPlugin({ prerenderScript, renderTarget, additionalPrere
if (!entrySrc || /^https:/.test(entrySrc))
throw new Error('Prerender entry script must have a `src` attribute and be local');

return path.join(viteConfig.root, entrySrc);
return entrySrc.startsWith('/')
? path.join(viteConfig.root, entrySrc)
: path.resolve(path.dirname(prerenderEntryHtml), entrySrc);
};

return {
Expand All @@ -134,7 +144,7 @@ export function prerenderPlugin({ prerenderScript, renderTarget, additionalPrere
// Only required for Vite 5 and older. In 6+, this is handled by the
// Environment API (`applyToEnvironment`)
if (config.build?.ssr) {
ssrBuild = true
ssrBuild = true;
return;
}

Expand Down Expand Up @@ -194,8 +204,9 @@ export function prerenderPlugin({ prerenderScript, renderTarget, additionalPrere
},
async options(opts) {
if (ssrBuild || !opts.input) return;
prerenderEntryHtml = getPrerenderEntryHtml(opts.input);
if (!prerenderScript) {
prerenderScript = await getPrerenderScriptFromHTML(opts.input);
prerenderScript = await getPrerenderScriptFromHtml();
}

// prettier-ignore
Expand Down Expand Up @@ -288,9 +299,25 @@ export function prerenderPlugin({ prerenderScript, renderTarget, additionalPrere
};

// Grab the generated HTML file, we'll use it as a template for all pages:
const tpl = /** @type {string} */ (
/** @type {OutputAsset} */ (bundle['index.html']).source
);
const entryHtmlAsset =
(prerenderEntryHtml &&
Object.values(bundle).find(
(output) =>
output.type === 'asset' &&
output.fileName.endsWith('.html') &&
(output.originalFileName === prerenderEntryHtml ||
output.originalFileNames?.includes(prerenderEntryHtml)),
)) ||
/** @type {OutputAsset | undefined} */ (bundle['index.html']) ||
Object.values(bundle).find(
(output) => output.type === 'asset' && output.fileName.endsWith('.html'),
);

if (!entryHtmlAsset) {
this.error('Unable to detect generated entry HTML asset');
}

const tpl = /** @type {string} */ (entryHtmlAsset.source);

// Create a tmp dir to allow importing & consuming the built modules,
// before Rollup writes them to the disk
Expand Down Expand Up @@ -506,8 +533,7 @@ export function prerenderPlugin({ prerenderScript, renderTarget, additionalPrere

// Add generated HTML to compilation:
route.url == '/'
? (/** @type {OutputAsset} */ (bundle['index.html']).source =
htmlDoc.toString())
? (entryHtmlAsset.source = htmlDoc.toString())
: this.emitFile({
type: 'asset',
fileName: assetName,
Expand Down Expand Up @@ -535,6 +561,6 @@ export function prerenderPlugin({ prerenderScript, renderTarget, additionalPrere
}
}
}
}
},
};
}
9 changes: 9 additions & 0 deletions tests/fixtures/nested-entry/src/dashboard/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<script prerender type="module" src="./main.js"></script>
</body>
</html>
3 changes: 3 additions & 0 deletions tests/fixtures/nested-entry/src/dashboard/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export async function prerender() {
return `<h1>Nested Entry Test Result</h1>`;
}
17 changes: 17 additions & 0 deletions tests/fixtures/nested-entry/vite.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { defineConfig } from 'vite';
import path from 'node:path';
import url from 'node:url';
import { vitePrerenderPlugin } from 'vite-prerender-plugin';

const __dirname = path.dirname(url.fileURLToPath(import.meta.url));

export default defineConfig({
build: {
rollupOptions: {
input: {
dashboard: path.resolve(__dirname, 'src/dashboard/index.html'),
},
},
},
plugins: [vitePrerenderPlugin()],
});
8 changes: 8 additions & 0 deletions tests/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ test('Should merge preload and entry chunks', async () => {
assert.equal((await fs.readdir(outDirAssets)).length, 1);
});

test('Should support nested HTML entrypoints', async () => {
await loadFixture('nested-entry', env);
await viteBuild(env.tmp.path);

const prerenderedHtml = await getOutputFile(env.tmp.path, 'src/dashboard/index.html');
assert.match(prerenderedHtml, '<h1>Nested Entry Test Result</h1>');
});

test('Should bail on merging preload & entry chunks if user configures `manualChunks`', async () => {
await loadFixture('simple', env);
await writeConfig(env.tmp.path, `
Expand Down
Loading