vite-plugin-prerender-spa
v0.1.2
Published
Vite plugin to pre-render SPA routes into static HTML at build time while emitting accurate asset preloads for lazy imports the rendered routes actually trigger
Maintainers
Readme
vite-plugin-prerender-spa
A Vite plugin for pre-rendering single-page applications at build time.
Inspired by Vite's SSR guide, but make it simple and powerful.
How it works
After the standard client build completes, the plugin:
- Builds an SSR bundle from your
entry-serverusing Vite's--ssrmode internally. - Renders each route by calling your
render(url)function exported byentry-server, collecting the output HTML along with the dynamic imported chunks and assets during rendering. - Generates preload links for the chunks a route loaded, their css and then their fonts, eliminating the sequential RTT waterfall of lazy-loaded routes. Images and other assets are not preloaded yet.
- Injects the rendered HTML into the client build's
index.htmland writes each route to a static.htmlfile.
Install
npm install --save-dev vite-plugin-prerender-spaUsage
1. Create your entry-server
This file must export a render function that returns the app HTML for a given route:
// src/entry-server.tsx
import { prerenderToNodeStream } from "react-dom/static";
import { StaticRouter } from "react-router-dom";
const Home = lazy(() => import("./pages/home"));
const About = lazy(() => import("./pages/about"));
export async function render(url: string): Promise<string> {
const { prelude } = await prerenderToNodeStream(
<StaticRouter location={url}>
<Suspense fallback={<Loader />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
</StaticRouter>,
);
const chunks: Buffer[] = [];
return new Promise((resolve, reject) => {
prelude.on("data", (chunk: Buffer) => chunks.push(chunk));
prelude.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
prelude.on("error", reject);
});
}2. Configure the plugin
// vite.config.ts
import prerender from "vite-plugin-prerender-spa";
export default defineConfig({
plugins: [
prerender({
routes: ["/", "/about"],
}),
],
});3. Build
vite buildThe static HTML files will be output alongside the standard client build.
Options
| Option | Type | Default | Description |
| ------------- | ---------- | -------------------- | ------------------------------------------------------------- |
| routes | string[] | — | Routes to pre-render, e.g. ["/"] |
| renderer | string | "src/entry-server" | Path to the SSR entry module that exports a render function |
| containerId | string | "root" | The #id of the app mount container in index.html |
