vite-prerender-plugin

Effortless prerendering in every framework

--- This is largely an extracted implementation of [@preact/preset-vite](https://github.com/preactjs/preset-vite)'s prererender functionality ([license](https://github.com/preactjs/preset-vite/blob/main/LICENSE)), which in turn is a reimplementation of [WMR](https://github.com/preactjs/wmr)'s prerendering ([license](https://github.com/preactjs/wmr/blob/main/LICENSE)). ## Getting Started ```bash $ npm install vite-prerender-plugin ``` ```js // vite.config.js import { defineConfig } from 'vite'; import { vitePrerenderPlugin } from 'vite-prerender-plugin'; export default defineConfig({ plugins: [vitePrerenderPlugin()], }); ``` To prerender your app, you'll need to do three things: 1. Set your `renderTarget` via the plugin option. This should, in all likelihood, match the query selector for where you render your app client-side, i.e., `render(, document.querySelector('#app'))` -> `'#app'` 2. Specify your prerender script, which can be done by a) adding a `prerender` attribute to one of the scripts listed in your entry HTML (` data: { url: data.url }, // Optionally configure and add elements to the `` of // the prerendered HTML document head: { // Sets the "lang" attribute: `` lang: 'en', // Sets the title for the current page: `My cool page` title: 'My cool page', // Sets any additional elements you want injected into the ``: // // elements: new Set([ { type: 'link', props: { rel: 'stylesheet', href: 'foo.css' } }, { type: 'meta', props: { property: 'og:title', content: 'Social media title' } }, ]), }, }; } ``` For those not using `preact-iso` (be it not using Preact at all or simply using other tools), this library exposes a `parseLinks` function which you can use to crawl your site for links to prerender. The function takes an HTML string and returns an array of links found in the document. To be valid, they must have an `href` attribute set and the `target` attribute, if set, must be `_self`. ```js export async function prerender() { const html = `
Foo Bar Baz
`; const { parseLinks } = await import('vite-prerender-plugin/parse'); const links = parseLinks(html); // ['/foo'] return { html, links: new Set(links), }; } ``` > **Note**: Anything you want to be server-only, like `parseLinks` from the example above, should be dynamically imported in the prerender function. A static import will see that code included in your client bundle, inflating it for a code path that will never run. ## Licenses [MIT](https://github.com/preactjs/vite-prerender-plugin/blob/master/LICENSE) [WMR - MIT](https://github.com/preactjs/wmr/blob/main/LICENSE) [Preact Vite Preset - MIT](https://github.com/preactjs/preset-vite/blob/main/LICENSE)