Skip to content

Instantly share code, notes, and snippets.

@fedek6
Created April 7, 2022 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fedek6/b75025f115383e54d87227d9cb3c297f to your computer and use it in GitHub Desktop.
Save fedek6/b75025f115383e54d87227d9cb3c297f to your computer and use it in GitHub Desktop.
Better cache busting for Gatsby (using date hash)
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);
}
};
{
"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