我有一个 gatsby 生成的网站,我已经在其中替换了主页的内容。
不幸的是,以前的版本正在提供/page-data/index/page-data.json
使用不正确的缓存控制 header ,导致 /page-data/index/page-data.json
缓存在客户端浏览器上(除非强制刷新,否则会显示陈旧数据)。我还发现 page-data.json 文件没有经过哈希处理(请参阅 https://github.com/gatsbyjs/gatsby/issues/15080 )。
我已经更新了缓存控制 header ,以便从现在开始的版本不会被缓存,但这对现在拥有缓存版本的客户端没有帮助。
我该怎么做才能强制客户端请求此文件的最新版本?
最佳答案
我终于到了那里...这是我的 gatsby-node.js
const hash = md5(`${new Date().getTime()}`)
const addPageDataVersion = async file => {
const stats = await util.promisify(fs.stat)(file)
if (stats.isFile()) {
console.log(`Adding version to page-data.json in ${file}..`)
let content = await util.promisify(fs.readFile)(file, 'utf8')
const result = content.replace(
/page-data.json(\?v=[a-f0-9]{32})?/g,
`page-data.json?v=${hash}`
)
await util.promisify(fs.writeFile)(file, result, 'utf8')
}
}
exports.onPostBootstrap = async () => {
const loader = path.join(__dirname, 'node_modules/gatsby/cache-dir/loader.js')
await addPageDataVersion(loader)
}
exports.onPostBuild = async () => {
const publicPath = path.join(__dirname, 'public')
const htmlAndJSFiles = glob.sync(`${publicPath}/**/*.{html,js}`)
for (let file of htmlAndJSFiles) {
await addPageDataVersion(file)
}
}
关于node.js - Gatsby 中的缓存破坏 page-data.json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58223669/