Skip to main content

A Docusaurus Plugin to Optimize Images at Build Time

· 21 min read ·
Docux
Curious explorer, a bit of a mad experimenter, and a bit of a contributor.

Developer Development License: MIT AI 90%

Docux trimming photographs beside a set of scales labelled Photo Weighing

My blog was quietly shipping 13.7 MB of images. A few PNGs weighed over a megabyte, and several WebP files were surprisingly heavy — over-sized dimensions and default encoder quality. Heavy images hurt load time, Core Web Vitals, and ultimately SEO. So I built a small local Docusaurus plugin that optimizes every image at build time, and it cut the deployed images almost in half (-49% on the corpus I had then) — without touching a single source file. It has since learned to emit srcset variants too, which took another two thirds off what my homepage sends to a phone.

This article walks through the plugin: how it hooks into the build, how a content-hash cache makes it incremental (already-optimized images become a reusable artifact), how the width variants work, and the real numbers it produced.

Design goals

Non-destructive (never modify sources), incremental (process new images only), and reference-safe (formats are preserved, so no URL ever breaks).

Why a build-time plugin (and not the source images)?​

There are several ways to optimize images. I picked the one that fits a Docusaurus site best:

  • At build time, on the build/ output. Docusaurus copies static/ and processes co-located images into build/. Optimizing there means every image is covered — including the hashed assets from MDX — while my source files stay pristine.
  • Non-destructive. Re-compressing sources in place is risky: quality degrades a little on every pass, and a mistake is permanent. Working on the generated output keeps the originals safe.
  • Reference-safe. Each image keeps its format and filename (WebP → WebP, PNG → PNG), so no link, image: front matter, or <img> src ever changes.

The one downside — the build output is regenerated every time, so a naive version would re-encode everything on every build. That's what the cache solves.

The tool: sharp​

sharp is the de-facto Node library for fast image processing (resize, re-encode, format conversion). It ships prebuilt binaries, so it just works locally and in CI.

> user@machine: ~/yourproject

npm install sharp

The plugin​

The plugin lives in plugins/, like my other local plugins.

▼📁plugins
▼📁docusaurus-plugin-image-optimizer
index.cjs

It hooks into Docusaurus's postBuild lifecycle, which runs only during docusaurus build (never during docusaurus start). Here is the whole thing:

/**
* Docusaurus plugin: image-optimizer
*
* Compresses the raster images of the production build (`build/`) with sharp
* and writes the `srcset` width variants the site actually references, without
* ever touching a source file. Runs in `postBuild`, so never under
* `docusaurus start` — no variant exists in development, and any `srcset` must
* be guarded accordingly.
*
* Options: quality (80), maxWidth (1920), widths ([400, 800, 1200, 1600]),
* extensions (.png/.jpg/.jpeg/.webp), cacheDir, concurrency (8),
* pruneUnreferenced (true), pruneCache (true).
*
* `IMAGE_OPTIMIZER_FORCE=1 npm run build` ignores the cache for one run.
* Bump CACHE_VERSION whenever the encoding changes: nothing else invalidates
* entries when the code changes, and it travels with the commit, so CI too.
*
* Written up in full at
* https://docuxlab.com/blog/image-optimizer-docusaurus-plugin/
*/

const fsp = require("fs/promises");
const path = require("path");
const crypto = require("crypto");

const DEFAULT_OPTIONS = {
quality: 80,
maxWidth: 1920,
widths: [400, 800, 1200, 1600],
extensions: [".png", ".jpg", ".jpeg", ".webp"],
cacheDir: null,
concurrency: 8,
pruneUnreferenced: true,
pruneCache: true,
};

const CACHE_VERSION = "v2";
const FORCE_ENV = "IMAGE_OPTIMIZER_FORCE";
const REFERENCING_EXTENSIONS = [".html", ".js", ".css"];
const VARIANT_REFERENCE = /[\w./@-]+-\d+w\.(?:webp|png|jpe?g)/gi;

function variantPath(file, width) {
const ext = path.extname(file);
return `${file.slice(0, -ext.length)}-${width}w${ext}`;
}

function isVariant(file) {
return /-\d+w\.[a-z]+$/i.test(file);
}

function formatBytes(bytes) {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
}

async function readIfExists(file) {
try {
return await fsp.readFile(file);
} catch {
return null;
}
}

/** Write via a temp file + rename, so an interrupted build never truncates one. */
async function writeAtomic(file, bytes) {
const tmp = `${file}.tmp${process.pid}-${crypto.randomBytes(4).toString("hex")}`;
try {
await fsp.writeFile(tmp, bytes);
await fsp.rename(tmp, file);
} catch (err) {
await fsp.unlink(tmp).catch(() => {});
throw err;
}
}

/**
* Files to process, plus those skipped for looking like our own output.
*
* `build/` is fresh at this point, so no variant exists yet: whatever the name
* check rejects is a source file, which is why the caller reports it.
*/
async function collectImages(dir, extensions) {
const found = [];
const excluded = [];
async function walk(current) {
for (const entry of await fsp.readdir(current, { withFileTypes: true })) {
const full = path.join(current, entry.name);
if (entry.isDirectory()) {
await walk(full);
} else if (extensions.includes(path.extname(entry.name).toLowerCase())) {
if (isVariant(entry.name)) excluded.push(full);
else found.push(full);
}
}
}
await walk(dir);
return { found, excluded };
}

async function optimizeBuffer(sharp, buffer, ext, { quality, maxWidth }) {
const meta = await sharp(buffer).metadata();
const animated = (meta.pages || 1) > 1;
let pipeline = animated ? sharp(buffer, { animated: true }) : sharp(buffer);

if (maxWidth && meta.width && meta.width > maxWidth && !animated) {
pipeline = pipeline.resize({ width: maxWidth, withoutEnlargement: true });
}

switch (ext) {
case ".webp":
pipeline = pipeline.webp({ quality });
break;
case ".png":
pipeline = pipeline.png({ compressionLevel: 9, palette: true, quality });
break;
case ".jpg":
case ".jpeg":
pipeline = pipeline.jpeg({ quality, mozjpeg: true });
break;
default:
return null;
}
return pipeline.toBuffer();
}

/**
* A `srcset` candidate, or `null` for an animated image or a source already
* narrower than the rung — which is why a consumer must only reference rungs
* narrower than the image.
*/
async function resizeBuffer(sharp, buffer, ext, width, { quality }) {
const pipeline = sharp(buffer);
const meta = await pipeline.metadata();
if ((meta.pages || 1) > 1) return null;
if (!meta.width || meta.width <= width) return null;

let out = pipeline.resize({ width, withoutEnlargement: true });

switch (ext) {
case ".webp":
out = out.webp({ quality });
break;
case ".png":
out = out.png({ compressionLevel: 9, palette: true, quality });
break;
case ".jpg":
case ".jpeg":
out = out.jpeg({ quality, mozjpeg: true });
break;
default:
return null;
}
return out.toBuffer();
}

async function mapLimit(items, limit, worker) {
let cursor = 0;
const runners = Array.from(
{ length: Math.min(limit, items.length) },
async () => {
while (cursor < items.length) {
const current = cursor++;
await worker(items[current]);
}
}
);
await Promise.all(runners);
}

/** Every variant URL the built site names. Only knowable once the HTML exists. */
async function collectReferences(dir) {
const refs = new Set();
async function walk(current) {
for (const entry of await fsp.readdir(current, { withFileTypes: true })) {
const full = path.join(current, entry.name);
if (entry.isDirectory()) {
await walk(full);
} else if (
REFERENCING_EXTENSIONS.includes(path.extname(entry.name).toLowerCase())
) {
const text = await fsp.readFile(full, "utf8");
for (const match of text.match(VARIANT_REFERENCE) || [])
refs.add(match);
}
}
}
await walk(dir);
return refs;
}

/**
* Matches on the path relative to the build root, so a `baseUrl` prefix is
* tolerated while a bare filename — one quoted in a code block — is not.
*/
function isReferenced(outDir, file, refs) {
const rel = path.relative(outDir, file).split(path.sep).join("/");
const suffix = `/${rel}`;
for (const ref of refs) {
if (ref === rel || ref.endsWith(suffix)) return true;
}
return false;
}

/**
* Group by bytes, so a distinct image is encoded once and written to every path
* that carries it. Docusaurus re-emits post images under a hashed name beside
* the original, so a large share of the build is duplicates.
*/
async function groupByContent(files) {
const groups = new Map();
for (const file of files) {
const buffer = await fsp.readFile(file);
const hash = crypto.createHash("sha256").update(buffer).digest("hex");
const existing = groups.get(hash);
if (existing) existing.paths.push(file);
else {
groups.set(hash, {
hash,
buffer,
ext: path.extname(file).toLowerCase(),
paths: [file],
});
}
}
return [...groups.values()];
}

/**
* Drop cache entries this run did not use: a full build touches everything that
* still matters. Losing one costs a re-encode, never correctness.
*/
async function pruneCacheDir(cacheDir, used) {
const result = { removed: 0, bytes: 0 };
for (const entry of await fsp.readdir(cacheDir, { withFileTypes: true })) {
if (!entry.isFile()) continue;
const full = path.join(cacheDir, entry.name);
if (used.has(full)) continue;
try {
const { size } = await fsp.stat(full);
await fsp.unlink(full);
result.removed++;
result.bytes += size;
} catch {
// Already gone.
}
}
return result;
}

module.exports = function pluginImageOptimizer(context, options = {}) {
const opts = { ...DEFAULT_OPTIONS, ...options };
const cacheDir =
opts.cacheDir ||
path.join(
context.siteDir,
"node_modules/.cache/docusaurus-plugin-image-optimizer"
);
const paramsSignature = `q${opts.quality}-w${opts.maxWidth}-${CACHE_VERSION}`;

return {
name: "docusaurus-plugin-image-optimizer",

/**
* Publish each static image's real width, so a component can ask instead of
* hard-coding rungs. `contentLoaded` runs before the HTML is generated.
*
* The map stays empty outside a production build — variants are written in
* `postBuild`, which `docusaurus start` never reaches — which keeps that
* guard here rather than in every component.
*/
async contentLoaded({ actions }) {
const payload = { widths: opts.widths, images: {} };
if (process.env.NODE_ENV !== "production" || !opts.widths.length) {
actions.setGlobalData(payload);
return;
}

let sharp;
try {
sharp = require("sharp");
} catch {
actions.setGlobalData(payload);
return;
}

const staticDir = path.join(context.siteDir, "static");
let files;
try {
files = (await collectImages(staticDir, opts.extensions)).found;
} catch {
actions.setGlobalData(payload);
return;
}

await mapLimit(files, opts.concurrency, async (file) => {
try {
const { width } = await sharp(file).metadata();
if (!width) return;
const rel = path.relative(staticDir, file).split(path.sep).join("/");
payload.images[`${context.baseUrl}${rel}`] = width;
} catch {
// Unreadable: simply absent from the map, so no `srcset` is emitted.
}
});

actions.setGlobalData(payload);
},

async postBuild({ outDir }) {
let sharp;
try {
sharp = require("sharp");
} catch {
console.warn(
"[image-optimizer] `sharp` is not installed — skipping image optimization."
);
return;
}

const force = Boolean(process.env[FORCE_ENV]);
if (force) {
console.log(`[image-optimizer] ${FORCE_ENV} set — ignoring the cache.`);
}

await fsp.mkdir(cacheDir, { recursive: true });
const { found: images, excluded } = await collectImages(
outDir,
opts.extensions
);

for (const file of excluded) {
console.warn(
`[image-optimizer] Left alone, its name matches a generated variant: ${path.relative(outDir, file)}`
);
}

// Asked before anything is encoded: the HTML already exists here.
const refs = opts.pruneUnreferenced
? await collectReferences(outDir)
: null;

const groups = await groupByContent(images);

const stats = {
optimized: 0,
fromCache: 0,
noGain: 0,
failed: 0,
before: 0,
after: 0,
variantsEncoded: 0,
variantsFromCache: 0,
variantsWritten: 0,
variantBytes: 0,
cacheRemoved: 0,
cacheBytes: 0,
};

const usedCacheFiles = new Set();

await mapLimit(groups, opts.concurrency, async (group) => {
const { hash, buffer: original, ext, paths } = group;
try {
stats.before += original.length * paths.length;

const cacheFile = path.join(
cacheDir,
`${hash}-${paramsSignature}${ext}`
);

let best = force ? null : await readIfExists(cacheFile);
if (best) {
stats.fromCache++;
} else {
const optimized = await optimizeBuffer(sharp, original, ext, opts);
best =
optimized && optimized.length < original.length
? optimized
: original;
await writeAtomic(cacheFile, best);
if (best.length < original.length) stats.optimized++;
else stats.noGain++;
}
usedCacheFiles.add(cacheFile);

const keep = best.length < original.length;
if (keep) {
for (const file of paths) await writeAtomic(file, best);
}
stats.after += (keep ? best.length : original.length) * paths.length;

// Derived from `best`: the ladder inherits its resize and quality.
for (const width of opts.widths) {
// Decided per path: a copy under `img/` can go unreferenced
// while its twin under `assets/images/` is wanted.
const targets = paths
.map((file) => variantPath(file, width))
.filter((target) => !refs || isReferenced(outDir, target, refs));

// `continue`, not `break`: a wider rung may still be referenced.
if (!targets.length) continue;

const variantCache = path.join(
cacheDir,
`${hash}-${paramsSignature}-${width}w${ext}`
);

let bytes = force ? null : await readIfExists(variantCache);
if (bytes) {
stats.variantsFromCache++;
} else {
bytes = await resizeBuffer(sharp, best, ext, width, opts);
if (!bytes) break;
await writeAtomic(variantCache, bytes);
stats.variantsEncoded++;
}
usedCacheFiles.add(variantCache);

for (const target of targets) {
await writeAtomic(target, bytes);
stats.variantsWritten++;
stats.variantBytes += bytes.length;
}
}
} catch (err) {
stats.failed += paths.length;
console.warn(
`[image-optimizer] Skipped ${path.basename(paths[0])}: ${err.message}`
);
}
});

if (opts.pruneCache && !stats.failed) {
const swept = await pruneCacheDir(cacheDir, usedCacheFiles);
stats.cacheRemoved = swept.removed;
stats.cacheBytes = swept.bytes;
}

const saved = stats.before - stats.after;
const percent = stats.before
? ((saved / stats.before) * 100).toFixed(1)
: "0.0";

console.log("\n=== Image optimizer ===");
console.log(
`Images: ${images.length} files, ${groups.length} distinct (optimized: ${stats.optimized}, from cache: ${stats.fromCache}, no gain: ${stats.noGain}, failed: ${stats.failed})`
);
console.log(
`Total: ${formatBytes(stats.before)} → ${formatBytes(stats.after)} (saved ${formatBytes(saved)}, -${percent}%)`
);
if (opts.widths.length) {
const rungs = images.length * opts.widths.length;
console.log(
`Variants: ${stats.variantsWritten} of ${rungs} rungs (encoded: ${stats.variantsEncoded}, from cache: ${stats.variantsFromCache}, ${formatBytes(stats.variantBytes)} added)`
);
}
if (stats.cacheRemoved) {
console.log(
`Cache: ${stats.cacheRemoved} stale entries removed (${formatBytes(stats.cacheBytes)} freed)`
);
}
console.log("=======================\n");
},
};
};

The transform​

For each image, sharp:

  1. Downscales it to maxWidth (default 1920px), never enlarging.
  2. Re-encodes it at quality (default 80), keeping the original format.
  3. Keeps the original if the "optimized" version isn't actually smaller — so we never inflate a file.
  4. Writes narrower copies of it for srcset — see Width variants below.

The cache = the incremental part​

This is the key idea. Each image is keyed by sha256(bytes) + settings, and the chosen result is stored in a persistent folder:

node_modules/.cache/docusaurus-plugin-image-optimizer/

On the next build, an image whose hash is already in the cache is restored from it instead of being re-encoded. So:

  • First build: every image is processed.
  • Later builds: only new or changed images are processed; everything else is a cache hit.

A nice side effect: two byte-identical images (say, the same picture referenced from static/ and from a blog post) share a hash, so the encoding work is done once even within a single build. Note that this deduplicates the work, not the bytes — both copies are still written to build/, each with its own ladder of variants.

One escape hatch, because a cache you cannot bypass is a cache you end up distrusting:

> user@machine: ~/yourproject

IMAGE_OPTIMIZER_FORCE=1 npm run build

That ignores the cache for a single run and re-encodes everything, without deleting anything — the results are written back, so the next build is incremental again. It is also how you check the cache has not been replaying stale bytes: a forced run should print the same totals as a cached one. On this build it does, down to the byte.

The cache also has to forget. Nothing in the key changes when the encoding code does, so there is a constant, CACHE_VERSION, to bump when it does — every key changes, and everything is re-encoded. It travels with the commit, which matters: deleting your local cache does nothing to the one CI restores on the next run.

Bumping it used to leave the old entries on disk forever, and so did deleting an image from the site. A full build touches every entry that still matters, so whatever it did not touch is dead — the plugin now sweeps those at the end:

Cache: 297 stale entries removed (16.91 MB freed)

That line is from a v1 → v2 bump. Without the sweep the folder would have gone from 18 MB to about 36, carrying both sets; with it, it stayed at 18 with no v1 entry left. Losing an entry that turns out to be needed costs one re-encode and never correctness, which is why it can be left on.

The cache is the "artifact"

Because the cache lives under node_modules/.cache, it's git-ignored. In CI we persist it with actions/cache (below), which is exactly what makes the already-optimized images a build artifact reused across runs.

Width variants​

Compressing an image achieves nothing if the browser downloads it at 1760px to display it in a card a few hundred pixels wide. That was happening on my homepage: a row of article thumbnails, each loading a full-size cover. The cards are fluid, so there is no single number to quote — the layout declares 380px as their widest realistic size, which is what the sizes attribute below is built on.

So the plugin also writes narrower copies next to every image:

photo-optimizer.webp ← the original, optimized
photo-optimizer-400w.webp
photo-optimizer-800w.webp
photo-optimizer-1200w.webp
photo-optimizer-1600w.webp

The ladder is the widths option, defaulting to [400, 800, 1200, 1600]. An empty array turns the feature off. Variants are derived from the already-optimized bytes rather than the source, so they inherit the same resize and quality decisions.

Deterministic naming, and why everything rests on it​

This is the piece that makes the rest possible, and it comes down to a quirk of timing.

postBuild runs after the HTML is generated. At the moment a React component writes its srcset, no variant exists yet — they are written moments later, in the same build. Because the name is predictable, photo.webp always yielding photo-400w.webp, a component can point at files that do not exist when it names them.

Without that, the alternative was rewriting the generated HTML from the outside: opening all 124 pages, finding every <img>, injecting a srcset. A far more fragile operation, on files I don't control.

Only when genuinely narrower — and the mistake that produced the rule​

My first version wrote a variant for every declared width. When the source was narrower than the target, it re-encoded it anyway under the candidate's name, so that no srcset entry could ever 404.

The intent was sound. The result was not:

644 variants written
297 of them were mere copies of their source (46%)
24 MB added to the build

So I reversed the rule: a variant is only written when it is genuinely narrower than the source. The obligation then moves to the consumer, and it fits in one line:

Only reference a candidate narrower than the image itself.

Both of my consumers can honour it, in two different ways. The img mapper in MDXComponents.js knows each image's real width, because Docusaurus hands it over, and lists only the narrower rungs. My homepage cannot — it has no such metadata — so it names its rungs by hand: 400w and 800w for the article cards, whose covers are all at least 1760px wide, and 800w and 1600w for the hero portrait, which is 1621px. Hand-naming works here only because I checked those widths; it is the weaker of the two arrangements.

After the reversal, the same corpus produced 346 variants for 18 MB instead of 644 for 24. The two counts come from two separate builds, so read them as orders of magnitude rather than a subtraction that has to reconcile.

The srcset must exist in production only

This is the trap, and it cost me a broken development environment.

The plugin runs in postBuild, so never under docusaurus start. In development the variants do not exist — and the dev server does not answer 404 on those URLs. It serves its fallback page:

/img/docux4-400w.webp → Content-Type: text/html 3,354 bytes
/img/docux4.webp → Content-Type: image/webp 145,156 bytes

The browser receives an HTML page where it expected an image, and displays nothing at all. No build error, no warning: the images simply vanish.

The guard is one constant:

const HAS_VARIANTS = process.env.NODE_ENV === "production";

Docusaurus sets that variable itself: bin/docusaurus.mjs defaults every command to development, and build forces production.

What makes it galling is that the constraint sits on the second line of the plugin's own header — never during docusaurus start. I quoted it while designing the srcset, without drawing the consequence.

sizes cannot come from the plugin​

A srcset lists the files available; it is sizes that tells the browser how wide the image will be once displayed. That depends on the layout, which the plugin knows nothing about. So the attribute is written where the layout is known — in the component.

Mine uses three:

homepage card (max-width: 600px) 100vw, 380px
article body (max-width: 996px) 100vw, 976px
hero portrait (max-width: 996px) 560px, 747px

One case deserves attention. My hero illustration sits in a 280px circle, but with object-fit: cover on a 1621 × 608 image, it is the height that fills: the image is scaled by 280/608 and rendered about 747px wide. Declaring it at 280px would have served a blurry crop on the most visible element of the page.

What it gives​

What a phone downloads, at 390px wide and device pixel ratio 2:

PageBeforeAfter
Homepage672 KB234 KB-65%
A component article560 KB459 KB-18%
An article full of screenshots1321 KB1137 KB-14%

The homepage gains most, because that is where the gap between displayed size and downloaded size was widest. Articles gain less: their screenshots are already close to the width they are shown at.

The cost sits on the other side: writing a full ladder for every image added 18 MB to the build, taking it from 24 MB to 42 MB. That is deployment weight, not visitor weight — GitHub Pages stores them, nobody downloads them all.

But "nobody downloads them all" is not the same as "each one is useful", and I only checked the difference while writing this section. The answer was bad enough to send me back to the plugin:

WhereVariants writtenReferenced by a page
assets/images/ (article bodies)144142
img/ (static, homepage)2028

The first row is the arrangement working as designed: those images pass through the img mapper, which reads each real width and asks for exactly the rungs that exist. The second row is the hand-named one — 194 files, 9.6 MB, sitting in the deployed build with nothing that would ever request them. A widths ladder pays for itself where a component picks rungs from real widths, and writes dead weight where nothing consumes it.

Asking the site before making anything​

The fix leans on the naming rule's premise, read the other way round.

Deterministic naming works because the HTML is written before postBuild runs — that is what lets a component name a file that does not exist yet. But the same fact means the finished HTML is sitting there, readable, before the plugin encodes a single byte. So instead of producing a full ladder and cleaning up afterwards, the plugin collects every variant URL the built site names, then skips any rung nobody asked for. Nothing is written, so nothing has to be deleted.

Variants: 238 of 644 rungs (encoded: 146, from cache: 0, 14.62 MB added)

644 is four rungs for each of the 161 images; 238 is what the site actually references. The other 406 are never encoded and never written. There is no list to keep in sync — it is derived from the site itself, so it stays correct the day a component changes its rungs.

I then checked all 238 against the HTML rather than trusting the count: every referenced variant resolves, and nothing the site asks for is missing.

I built this backwards first

The first version of this did produce all 346, write them to disk, then delete 195 of them — a tidy-up pass at the end of the build. It gave the right output by the wrong route: on a cold cache it spent 199 encodes to keep 151.

Reversing it took moving one function call above the loop. The information had been available all along; I had simply written the cleanup before asking whether the work needed doing.

One limit worth stating plainly: the scan reads HTML, JS and CSS. A rung referenced only from JSON, or through a URL assembled at runtime, would be skipped — that is what pruneUnreferenced: false is for.

Telling components what exists​

Everything above assumes a component knows which rungs to ask for. Mine did not, and that turned out to be where most of the weight still was.

The img mapper in MDXComponents.js is fine: Docusaurus hands it each image's real width, so it lists exactly the narrower rungs. But that only covers images inside an article's body. Every listing on the site — tag pages, series pages, related posts — goes through a card component that receives a URL from front matter and nothing else. No width, no srcset, so the full-size cover downloads into a card a few hundred pixels wide.

Measured on the built HTML, it was worse than I expected:

PageWeight of images without srcset
/blog/tags/docusaurus/1900 KB
/blog/tags/react/1381 KB
/series/1358 KB

Median across the site: 211 KB per page. Card images accounted for 92% of it, from a single component.

The tempting fix, and why it is the wrong one​

The obvious move is to write the rungs into the component:

srcSet = "/img/cover-400w.webp 400w, /img/cover-800w.webp 800w";

That works, and it is what my homepage did for weeks. It is also a dependency in its worst form: silent, and wrong the day a cover is replaced by a narrower image. The component asserts that files exist; nothing checks the claim, and nothing fails at build time if it is false. Multiply that across every component that shows a cover and you have a rule nobody can keep.

It matters more than usual here, because these components get copied. Someone taking the card component into their own site would inherit a srcset pointing at files their build never produces.

Asking instead of asserting​

postBuild is too late to help a component — the HTML is already written. But Docusaurus has an earlier hook, contentLoaded, which runs before anything renders. So the plugin measures the source images there and publishes what it found:

actions.setGlobalData({
widths: opts.widths,
images: { "/img/cover.webp": 1760 },
});

A component reads it back through usePluginData, and the contract inverts: it asks whether anything is known about this image, instead of asserting that a file exists.

The property that makes this safe is in Docusaurus's own implementation — usePluginData returns undefined for a plugin that is not installed, and only throws if you pass failfast: true. So a helper built on it degrades to nothing:

const { srcSet, sizes } = useImageSrcSet(
image,
"(max-width: 996px) 100vw, 300px"
);
// plugin present → candidates that are known to exist
// plugin absent → {} → a plain <img> that works

Three things fall out of that. The rung list stops being duplicated in every component. The NODE_ENV guard moves into the plugin, which is the only place that knows whether it wrote anything — the map is simply empty outside a production build. And the widths come from measurement rather than from a comment claiming someone checked.

I verified the dev case rather than trusting it, because this is exactly where a hand-written srcset broke my local environment once: delete .docusaurus/globalData.json, run docusaurus start, and the file comes back with 0 entries against 104 after a build.

One more thing the layout knows​

A card 380px wide will never choose a 1600w candidate — the widest it can ask for is its own width times the device pixel ratio. Listing wider rungs costs build weight for a file no browser will pick.

That ceiling is derivable from the sizes attribute the component already writes, so it is not another number to tune. Every px length counts, media-query bounds included: (max-width: 600px) 100vw means the image can span a 600px viewport, so 1200 is genuinely reachable on a dense screen. It over-estimates when a bound is wider than the slot it governs, which is the safe direction — a candidate too many, never one too few.

That last point corrected my own hand-tuning: the homepage cards had been pinned to [400, 800], which under-served a 600px phone at device pixel ratio 2.

What it gave​

BeforeAfter
Images with srcset5070
Images without3917
Median page, images without srcset211 KB25 KB
Heaviest tag page1900 KB25 KB

The 25 KB that remain are the navbar logo, which the browser caches for the whole visit.

The cost is on the deployment side: 238 rungs instead of 151, and 14.6 MB of variants instead of 8.4. That is the honest trade — correct coverage of dense screens, paid in storage nobody downloads.

Registering the plugin​

In docusaurus.config.js:

import pluginImageOptimizer from "./plugins/docusaurus-plugin-image-optimizer/index.cjs";

const config = {
plugins: [
[pluginImageOptimizer, { quality: 80, maxWidth: 1920 }],
// ...other plugins
],
};

The results​

After one npm run build, the plugin prints a report:

=== Image optimizer ===
Images: 161 files, 101 distinct (optimized: 101, from cache: 0, no gain: 0, failed: 0)
Total: 24.69 MB → 12.22 MB (saved 12.47 MB, -50.5%)
Variants: 238 of 644 rungs (encoded: 146, from cache: 0, 14.62 MB added)
=======================

161 files, 101 distinct: Docusaurus re-emits every image a post references under a hashed name in assets/images/, beside the original in img/, so 60 of them are byte-identical twins. The plugin groups by content before encoding anything, so each distinct image is encoded once and the result written to every path that carries it. That also keeps from cache honest — it means restored from an earlier build, never met twice in this one, which is why it reads 0 here.

A few representative files, comparing what sits in static/img/ to what the plugin produced in build/:

ImageBeforeAfterSaved
frontmattercms/post2/frontmatterparameters.png1691 KB531 KB-69%
api.png1546 KB415 KB-73%
frontmattercms/post4/snippetcolone.png902 KB153 KB-83%
icon/css.webp904 KB513 KB-43%

Across the whole set: 104 files with a gain, 14.6 MB → 7.4 MB.

That 104 is not the 161 the report prints, and the gap is worth explaining. The report counts what the plugin walks — the whole build/ folder, which holds 104 images under img/ and 57 more under assets/images/, where Docusaurus re-emits every image a post references under a hashed name. The table above counts source files in static/img/ instead, each compared to its counterpart in the build. Same plugin, two different populations, and the second one double-counts anything a post cites.

The contrast between the three PNGs and the WebP is not an accident. A palette re-encode bites hard on a screenshot and much less on an already-compressed WebP.

A second build is basically instant for images — everything comes from the cache:

Images: 161 files, 101 distinct (optimized: 0, from cache: 101, no gain: 0, failed: 0)
Variants: 238 of 644 rungs (encoded: 0, from cache: 146, 14.62 MB added)

Caching in CI​

My GitHub Actions workflow builds on every push. To reuse the optimized images across runs — so CI only re-encodes what actually changed — I cache the plugin folder before the build step:

- name: Cache optimized images
uses: actions/cache@v4
with:
path: node_modules/.cache/docusaurus-plugin-image-optimizer
key: image-optimizer-${{ hashFiles('static/**', 'src/**/*.png', 'src/**/*.webp', 'plugins/docusaurus-plugin-image-optimizer/index.cjs') }}
restore-keys: |
image-optimizer-

The key is what the cache actually depends on: the source images and the encoding code. When neither changed it hits exactly, and actions/cache skips saving — confirmed in a real run, Cache hit for: image-optimizer-b95ce43c… with no upload afterwards. When one did change, the restore-keys prefix still seeds from the previous cache, so only the new work is done.

It started as key: image-optimizer-${{ github.run_id }}, which is unique per run and therefore never hits — so every push re-uploaded 18 MB whether anything had changed or not.

Forcing a rebuild without a commit

Two levers, and they are not interchangeable. CACHE_VERSION is a constant in the plugin: bump it when the encoding code changes, because that invalidation has to travel with the commit and reach CI too.

For a one-off check that the cache is not replaying stale bytes, a commit would be noise. So workflow_dispatch carries a checkbox that sets IMAGE_OPTIMIZER_FORCE=1 for that run only:

on:
workflow_dispatch:
inputs:
force_images:
description: "Re-encode every image, ignoring the cache"
type: boolean
default: false

Ticked, the run prints IMAGE_OPTIMIZER_FORCE set — ignoring the cache and reports optimized: 101, from cache: 0. Unticked, the next run reports optimized: 0, from cache: 101 — with identical totals, which is the point of the exercise.

Tuning and trade-offs​

  • quality / maxWidth / widths are the options you will actually reach for. Lower quality or a smaller max width means smaller files; a shorter widths ladder means fewer variants on disk. extensions, cacheDir, concurrency (8 workers by default — that is where the speed comes from), pruneUnreferenced and pruneCache round out the eight.
  • widths must be given in ascending order. The loop stops at the first rung that is not narrower than the source, so [1600, 400] would quietly produce nothing.
  • A source named like a variant is left alone. The plugin recognises its own output by the -400w suffix, so a source image genuinely called banner-1920w.jpg would be skipped. It now says so in the build log rather than passing over it in silence — none of mine trip it, but the warning is there because nothing else would tell you.
  • Every write goes through a temp file and a rename. A build interrupted mid-write would otherwise leave a truncated image in build/, or a half-written cache entry that the next build would happily restore.
  • PNG uses a palette (lossy) re-encode for much smaller files. It's great for screenshots and illustrations; if you have PNGs where exact pixels matter, raise the quality or exclude them via extensions.
  • Animated WebP is left un-resized and gets no variants at all, to stay safe. GIF never reaches that check: it is not in the default extensions list, so the plugin does not touch it in the first place.
  • The plugin only runs in build, so your dev server stays fast — at the price of the trap described above: no variant exists in development, so any srcset must be guarded.

Most of what is above was rewritten at least twice, usually because a measurement contradicted something I had been confident about. What survived every pass is the shape: a lifecycle hook, a hash, and a rule about who is allowed to name a file that does not exist yet.


This article is part of the Docusaurus Plugins series:

No related posts.

Back to top