I want to make a simple static blog site, and when I export my pages, everything is good and fast.
But in dev mode, my post generation is slow and I want to cache it, so that it is done only once. This is done in a post.ts file and my cache is const posts: Post[] = [] .
What I expect is that after typing yarn dev, the post.ts file is loaded once and I can fill and reuse my cached post array, but strangely this ts module is loaded many times.
import fs from 'fs'
import path from 'path'
// ...
ā
console.log('????? reloading page')
const posts: Post[] = [] // cached posts, hope to generate once
let postsGenerated = false
ā
export async function getSortedPostsData(): Promise<Post[]> {
// Get file names under /posts
const pendings: Promise<any>[] = []
if (postsGenerated) {
console.log('+++++ Using cache ')
return sortPostsByDate(posts)
} else {
console.log('==== Calculating all')
postsGenerated = true
}
let i = 0
traverseDir('content/blog', (path) => {
if (path.includes('.md')) { ... })
}
await Promise.all(pendings)
return sortPostsByDate(posts)
}
The result is that sometimes cache is used, sometimes not. Even when reloading the same page, cache is not always called. Why ? And how to improve that ?
