feat: added cache for css

This commit is contained in:
Leyla Becker 2026-02-11 16:08:51 -06:00
parent a7676d06b6
commit 642ee3b45a
3 changed files with 93 additions and 3 deletions

View file

@ -4,8 +4,26 @@ const markdownItFootnote = require("markdown-it-footnote");
const markdownItMermaid = require('markdown-it-mermaid').default
const syntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight");
const fs = require("fs");
const crypto = require("crypto");
const path = require("path");
const { DateTime } = require("luxon");
const cssHashCache = {};
const getCssHash = (cssFile) => {
if (cssHashCache[cssFile]) return cssHashCache[cssFile];
const cssPath = path.join(__dirname, "css", cssFile);
try {
const content = fs.readFileSync(cssPath, "utf-8");
const hash = crypto.createHash("md5").update(content).digest("hex").slice(0, 8);
cssHashCache[cssFile] = hash;
return hash;
} catch (e) {
console.warn(`Could not hash CSS file: ${cssFile}`);
return null;
}
};
const extractTags = (content, mdInstance) => {
if (!content) return [];
@ -220,7 +238,36 @@ module.exports = (eleventyConfig) => {
return tagMap;
});
eleventyConfig.addPassthroughCopy("css");
// Cache busting filter: returns hashed CSS filename
eleventyConfig.addFilter("cssHash", (cssFile) => {
const hash = getCssHash(cssFile);
const ext = path.extname(cssFile);
const base = path.basename(cssFile, ext);
return `/css/${base}.${hash}${ext}`;
});
eleventyConfig.on("eleventy.before", async () => {
const cssDir = path.join(__dirname, "css");
const outputCssDir = path.join(__dirname, "_site", "css");
if (!fs.existsSync(outputCssDir)) {
fs.mkdirSync(outputCssDir, { recursive: true });
}
const cssFiles = fs.readdirSync(cssDir).filter(f => f.endsWith(".css"));
for (const cssFile of cssFiles) {
const hash = getCssHash(cssFile);
const ext = path.extname(cssFile);
const base = path.basename(cssFile, ext);
const hashedName = `${base}${hash == null ? '' : `.${hash}`}${ext}`;
fs.copyFileSync(
path.join(cssDir, cssFile),
path.join(outputCssDir, hashedName)
);
}
});
eleventyConfig.addPassthroughCopy("robots.txt");
eleventyConfig.ignores.add("README.md");