Files
SlpSoftware/scripts/prerender.mjs
T

36 lines
1.3 KiB
JavaScript

// Post-build step (NFR-9): renders the static landing text into dist/index.html so crawlers see
// it without JavaScript. The client (createRoot in src/main.tsx) replaces it on load.
import { build } from 'vite';
import { readFile, writeFile, rm } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
import path from 'node:path';
const root = process.cwd();
const ssrDir = path.join(root, 'node_modules', '.prerender');
const htmlPath = path.join(root, 'dist', 'index.html');
await build({
logLevel: 'warn',
build: {
ssr: path.join(root, 'src/prerender/entry-server.tsx'),
outDir: ssrDir,
emptyOutDir: true,
rollupOptions: { output: { entryFileNames: 'entry-server.mjs', format: 'esm' } },
},
});
const { render } = await import(pathToFileURL(path.join(ssrDir, 'entry-server.mjs')).href);
const markup = render();
const html = await readFile(htmlPath, 'utf8');
const placeholder = '<div id="root"></div>';
if (!html.includes(placeholder)) {
throw new Error(`prerender: ${placeholder} not found in dist/index.html`);
}
await writeFile(
htmlPath,
html.replace(placeholder, () => `<div id="root">${markup}</div>`),
);
await rm(ssrDir, { recursive: true, force: true });
console.log(`prerender: ${markup.length} bytes of static HTML injected into dist/index.html`);