More Tooling for Static Analysis of Pages
See original GitHub issueMotivation
I’m building a blog, and I want to be able to show a listing page that links to all pages within a posts directory.
Problem
Since posts are just pages, I can theoretically generate a list of page-metadata statically at build-time–I’ve tested this with import.meta.glob
, and it works mostly fine, but I have to manually construct links from the filenames, which is brittle since it’s bypassing any custom routing functionality I may create in the future:
async function getPosts(): Promise<PostMetadata[]> {
const files = import.meta.globEager('/pages/posts/**/*.page.*([a-zA-Z0-9])');
return map(files, (file, path) => {
const { title, publishedAt } = file;
return {
publishedAt,
title,
url: path.replace('index.page.tsx', '').replace('pages/', ''),
};
});
}
Obviously I could manually create this list of URLs, but I’ve found even this hacky solution to be extremely nice from a developer-experience perspective, and would like to see some tooling to support this further.
Proposed solution
Expose an API for accessing routing details for all pre-rendered pages. It seems there may potentially be some overlap with https://github.com/brillout/vite-plugin-ssr/issues/49 here. I’m actually not sure if this is potentially an intractable problem, since this would require knowledge of all pages that will be prerendered (and what their routes would look like) before prerender hooks are called.
Issue Analytics
- State:
- Created 2 years ago
- Comments:8 (4 by maintainers)
Top GitHub Comments
I agree there should be an API for that.
In the meantime, have you seen
pageContext._pageRoutes
? You still have to manually determine the URLs but it will at least provide you with a consistent list of page IDs and their routes.But a non-internal and higher-level API should be made available to users. E.g.
In general, eagerly loading pages is an anti-pattern for performance & scalability; it goes against Vite’s lazy-transpiling approach.
An alternative is to use https://github.com/antfu/vite-plugin-glob with a custom transformer (see https://github.com/antfu/vite-plugin-glob#custom-queries). The transformer would extract the meta data in a performant way. That way we can get meta data for all pages and stay performant & scalable.