npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vite-prerender-plugin

v0.5.0

Published

A Vite plugin for prerendering apps to HTML at build time

Downloads

98

Readme


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

Getting Started

$ npm install vite-prerender-plugin
// 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(<App />, 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 (<script prerender src="./my-prerender-script.js">) or b) use the prerenderScript plugin option to specify the location of your script with an absolute path

  3. Export a function named prerender() 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 the render-to-string implementation of your framework. This prerender function can be sync or async, so feel free to initialize your app data with fetch() calls, read local data with fs.readFile(), etc. All that's required is that your return an object containing an html 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 the examples directory, and if you don't see your framework listed, let me know! I can take a look to see at adding it.

Options

| Option | Type | Default | Description | | --------------------------- | -------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | renderTarget | string | "body" | Query selector for where to insert prerender result in your HTML template | | prerenderScript | string | undefined | Absolute path to script containing exported prerender() function. If not provided, the plugin will try to find the prerender script in the scripts listed in your HTML entrypoint | | additionalPrerenderRoutes | string | undefined | While 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 | | previewMiddlewareFallback | string | /index.html | Fallback 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, your prerender() 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:

export async function prerender(data) {
    const html = '<h1>hello world</h1>';

    return {
        html,

        // Optionally add additional links that should be
        // prerendered (if they haven't already been)
        links: new Set(['/foo', '/bar']),

        // Optional data to serialize into a script tag for use on the client:
        //   <script type="application/json" id="prerender-data">{"url":"/"}</script>
        data: { url: data.url },

        // Optionally configure and add elements to the `<head>` of
        // the prerendered HTML document
        head: {
            // 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: 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.

export async function prerender() {
    const html = `
        <div>
            <a href="/foo">Foo</a>
            <a href="/bar" target="_blank">Bar</a>
            <a href="/baz" target="_top">Baz</a>
        </div>
    `;

    const { parseLinks } = await import('vite-prerender-plugin/parse');
    const links = parseLinks(html); // ['/foo']

    return {
        html,
        links: new Set(links),
    };
}

Licenses

MIT

WMR - MIT

Preact Vite Preset - MIT