Created
April 7, 2022 09:01
-
-
Save fedek6/b75025f115383e54d87227d9cb3c297f to your computer and use it in GitHub Desktop.
Better cache busting for Gatsby (using date hash)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const path = require("path"); | |
const md5 = require("md5"); | |
const util = require("util"); | |
const glob = require("glob"); | |
/** | |
* Cache busting | |
*/ | |
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}..`); | |
const 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 (const file of htmlAndJSFiles) { | |
// eslint-disable-next-line no-await-in-loop | |
await addPageDataVersion(file); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"dependencies": { | |
"glob": "^7.2.0", | |
"md5": "^2.3.0", | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment