Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Plugin for prerendering Vite applications in any framework

License

NotificationsYou must be signed in to change notification settings

preactjs/vite-prerender-plugin

Repository files navigation

Effortless prerendering in every framework


This is largely an extracted implementation of@preact/preset-vite's prererender functionality (license), which in turn is a reimplementation ofWMR's prerendering (license).

Getting Started

$ npm install vite-prerender-plugin
// vite.config.jsimport{defineConfig}from'vite';import{vitePrerenderPlugin}from'vite-prerender-plugin';exportdefaultdefineConfig({plugins:[vitePrerenderPlugin()],});

To prerender your app, you'll need to do three things:

  1. Set yourrenderTarget via the plugin option. This should, in all likelihood, match the query selector for where you render your app client-side, i.e.,render(<App />, document.querySelector('#app')) ->'#app'

  2. Specify your prerender script, which can be done by a) adding aprerender attribute to one of the scripts listed in your entry HTML (<script prerender src="./my-prerender-script.js">) or b) use theprerenderScript plugin option to specify the location of your script with an absolute path

  3. Export a function namedprerender() from your prerender script (see below for an example)

The plugin simply calls the prerender function you provide so it's up to you to determine how your app should be prerendered, likely you'll want to use therender-to-string implementation of your framework. This prerender function can be sync or async, so feel free to initialize your app data withfetch() calls, read local data withfs.readFile(), etc. All that's required is that your return an object containing anhtml property which is the string of HTML you want injected into your HTML document.

With that, you're all ready to build!

For full examples, please see theexamples directory, and if you don't see your framework listed, let me know! I can take a look to see at adding it.

Options

OptionTypeDefaultDescription
renderTargetstring"body"Query selector for where to insert prerender result in your HTML template
prerenderScriptstringundefinedAbsolute path to script containing exportedprerender() function. If not provided, the plugin will try to find the prerender script in the scripts listed in your HTML entrypoint
additionalPrerenderRoutesstringundefinedWhile the prerendering process can automatically find new links in your app to prerender, sometimes you will have pages that are not linked to but you still want them prerendered (such as a/404 page). Use this option to add them to the prerender queue
previewMiddlewareFallbackstring/index.htmlFallback path to be used when an HTML document cannot be found via the preview middleware, e.g.,/404 or/not-found will be returned when the user requests/some-path-that-does-not-exist

Advanced Prerender Options

Additionally, yourprerender() function can return more than just HTML -- it can return additional links to prerender as well as information that should be set in the<head> of the HTML document, such as title, language, or meta tags. For example:

exportasyncfunctionprerender(data){consthtml='<h1>hello world</h1>';return{        html,// Optionally add additional links that should be// prerendered (if they haven't already been)links:newSet(['/foo','/bar']),// Optional data to serialize into a script tag for use on the client://   <script type="application/json">{"url":"/"}</script>data:{url:data.url},// Optionally configure and add elements to the `<head>` of// the prerendered HTML documenthead:{// Sets the "lang" attribute: `<html lang="en">`lang:'en',// Sets the title for the current page: `<title>My cool page</title>`title:'My cool page',// Sets any additional elements you want injected into the `<head>`://   <link rel="stylesheet" href="foo.css">//   <meta property="og:title" content="Social media title">elements:newSet([{type:'link',props:{rel:'stylesheet',href:'foo.css'}},{type:'meta',props:{property:'og:title',content:'Social media title'}},]),},};}

For those not usingpreact-iso (be it not using Preact at all or simply using other tools), this library exposes aparseLinks 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 anhref attribute set and thetarget attribute, if set, must be_self.

exportasyncfunctionprerender(){consthtml=`        <div>            <a href="/foo">Foo</a>            <a href="/bar">Bar</a>            <a href="/baz">Baz</a>        </div>    `;const{ parseLinks}=awaitimport('vite-prerender-plugin/parse');constlinks=parseLinks(html);// ['/foo']return{        html,links:newSet(links),};}

Note: Anything you want to be server-only, likeparseLinks 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

WMR - MIT

Preact Vite Preset - MIT


[8]ページ先頭

©2009-2025 Movatter.jp