preactjs / preset-vite

Preset for using Preact with the vite bundler
https://npm.im/@preact/preset-vite
MIT License
260 stars 26 forks source link

Feature Request: `additionalPrerenderRoutes` accept async getter function #99

Closed rawrmonstar closed 9 months ago

rawrmonstar commented 9 months ago

Hello! This is just a feature request, not a bug report or anything.

I was wondering if you all think having additionalPrerenderRoutes accept an async getter function would be something that could potentially be added.

This would be a useful feature to me because in my use case I need to fetch a list of static page routes from a CMS where those static pages are defined. It would be great if I could prerender them but they are not known until the list is fetched during build time. An alternative solution would be to generate a json file of the list via a script and import that in the vite.config.js but that seems more fragile and cumbersome.

To be clear I am describing a feature where you could do something like this:


// vite.config.js

import { defineConfig } from 'vite';
import preact from '@preact/preset-vite';

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        preact({
            prerender: {
                enabled: true,
                renderTarget: '#app',
                additionalPrerenderRoutes: async () => {
                    const response = await fetch('https://my-cms-url/static-pages');
                    const routes = await response.json();

                    return [...routes, 'hardcoded routes here I guess'];
                },
            },
        }),
    ],
});
``
rawrmonstar commented 9 months ago

I just realized this can be done already because Vite supports an async config: https://vitejs.dev/config/#async-config

Ignore meeeeeee

rschristian commented 9 months ago

That's probably the way to go, but as you're writing ESM, can alternatively just make use of top-level await:

// vite.config.js

import { defineConfig } from 'vite';
import preact from '@preact/preset-vite';

let routes = []
if (process.env.NODE_ENV === 'production') {
    const urls = await fs.readFile('./routes.json', 'utf-8')
    routes = JSON.parse(urls);
}

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        preact({
            prerender: {
                enabled: true,
                renderTarget: '#app',
                additionalPrerenderRoutes:  [...routes, 'hardcoded routes here I guess'],
            },
        }),
    ],
});