Skip to content

Implement cache buster for css and js asset files #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions .eleventy.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
const { resolve } = require("path");
const { statSync, existsSync } = require("fs");

module.exports = (eleventyConfig) => {
eleventyConfig.addWatchTarget("./src/assets");

Expand All @@ -19,6 +22,34 @@ module.exports = (eleventyConfig) => {
"node_modules/swiper/swiper-bundle.min.css": "assets/swiper-bundle.min.css",
});

eleventyConfig.addTransform("cache-buster", function (content, outputPath) {
const assetsInputDir = resolve(eleventyConfig.dir.input, "assets");
const assetsOutputDir = resolve(eleventyConfig.dir.output, "assets");
if (outputPath.endsWith(".html")) {
return content.replace(
/="\/assets\/([^"]+\.(css|js))"/g,
function (_, matcher) {
const filepath = matcher.split("?")[0];
let timestamp

if (existsSync(resolve(assetsInputDir, filepath))) {
// These are our source files, so we use their modification time
timestamp = statSync(resolve(assetsInputDir, filepath)).mtime.getTime();
} else if (existsSync(resolve(assetsOutputDir, filepath))) {
// In cases where we are getting the output files from other places (like node_modules)
// we use the output directory's modification time.
timestamp = statSync(resolve(assetsOutputDir, filepath)).mtime.getTime();
} else {
throw new Error(`File not found: ${filepath}`);
}

return `="/assets/${filepath}?v=${timestamp}"`;
}
);
}
return content;
});

return {
dir: {
input: "src",
Expand Down