@wroud/vite-plugin-ssg
Version:
A Vite plugin for static site generation (SSG) with React. Renders React applications to static HTML for faster load times and improved SEO.
61 lines • 2.59 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { Writable } from "stream";
import { renderToPipeableStream } from "react-dom/server";
import { AppInstance } from "../app/AppInstance.js";
import { renderViteTags } from "./ssg-common.js";
import { AppContext } from "./components/AppContext.js";
import { SSGContext } from "./components/SSGContext.js";
export async function create(indexOrApp, context, mainScriptUrl) {
if (!(indexOrApp instanceof AppInstance)) {
indexOrApp = new AppInstance(indexOrApp);
}
const appStartData = await indexOrApp.start(context);
context.base = appStartData.base;
return {
appStartData,
context,
async render(htmlTags, timeout = 10000) {
let htmlContent = "";
await new Promise(async (resolve, reject) => {
try {
const writable = new Writable({
write(chunk, encoding, callback) {
htmlContent += chunk.toString();
callback();
},
final(callback) {
resolve();
callback();
},
});
const renderTags = renderViteTags.bind(undefined, htmlTags, context);
const Index = indexOrApp.index;
const { pipe, abort } = renderToPipeableStream(_jsx(AppContext, { value: appStartData, children: _jsx(SSGContext, { value: { context, renderTags, mainScriptUrl }, children: _jsx(Index, { renderTags: renderTags, context: context, mainScriptUrl: mainScriptUrl }) }) }), {
nonce: context.cspNonce,
onAllReady() {
clearTimeout(timeoutId);
pipe(writable);
},
onError(error) {
reject(error);
},
});
const timeoutId = setTimeout(() => {
abort(new Error("SSG render timeout"));
}, timeout);
}
catch (error) {
reject(error);
}
});
return htmlContent;
},
async getPathsToPrerender() {
return await indexOrApp.getRoutesPrerender(appStartData);
},
async dispose() {
await indexOrApp.stop();
},
};
}
//# sourceMappingURL=server.js.map