fix(prerender): Optimize blog route prerendering strategy

- Refactor prerender plugin to use content:file:afterParse hook
- Dynamically collect blog post routes during file parsing
- Remove complex locale-based post fetching logic
- Add conditional prerendering to prevent unnecessary processing
- Improve logging for prerender route generation
- Simplify route collection and prerendering process
Improves performance and reliability of static site generation for blog content.
This commit is contained in:
mahdiarghyani
2025-11-11 17:10:21 +03:30
parent 5f28eaa179
commit d04e9ea58c
+15 -30
View File
@@ -1,37 +1,22 @@
export default defineNitroPlugin((nitroApp) => { export default defineNitroPlugin(async (nitroApp) => {
nitroApp.hooks.hook('prerender:routes' as any, async (ctx: any) => { if (!import.meta.prerender) {
try { return
// Import serverQueryContent dynamically }
const { serverQueryContent } = await import('#content/server' as any)
// Fetch all blog posts from both English and Persian locales const routes: string[] = []
const locales = ['en', 'fa']
const allPosts: any[] = []
for (const locale of locales) { nitroApp.hooks.hook('content:file:afterParse', (file) => {
const posts = await serverQueryContent(nitroApp as any, `${locale}/blog`) // Collect blog post routes for prerendering
.where({ draft: { $ne: true } }) if (file._path && !file.draft) {
.find() if (file._path.startsWith('/en/blog/') || file._path.startsWith('/fa/blog/')) {
routes.push(file._path)
allPosts.push(...posts)
} }
}
})
if (allPosts.length === 0) { nitroApp.hooks.hook('prerender:generate', async () => {
console.log('No blog posts found for prerendering') for (const route of routes) {
return console.log(`Prerendering blog route: ${route}`)
}
// Add routes for each published post
for (const post of allPosts) {
if (post._path) {
ctx.routes.add(post._path)
console.log(`Added route for prerendering: ${post._path}`)
}
}
console.log(`Total blog routes added for prerendering: ${allPosts.length}`)
} catch (error) {
console.error('Error generating prerender routes:', error)
} }
}) })
}) })