Skip to content
Open
Show file tree
Hide file tree
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
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ As of version 5.0.0, all notable changes to HTML Minifier (HM) are documented in

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
## [5.4.2] - 2026-11-28

### Fixed

* Fixed `removeEmptyElements` with `collapseWhitespace` dropping the space after an empty inline element it removes right after an element that doesn’t render, like a non-empty `script` (e.g., `<p>a<script>1</script><span></span> b</p>` became `<p>a<script>1</script>b</p>`)
* Fixed `collapseWhitespace` keeping whitespace next to `htmlmin:ignore` blocks that start or end with whitespace, which doubled it and changed the output when minified again (e.g., `a <!-- htmlmin:ignore --> x <!-- htmlmin:ignore --> b` became `a x b`), including at the edges of `partialMarkup` and, under `trimCustomFragments`, next to custom fragments
* Fixed `minifySVG` dropping `htmlmin:ignore` markup within `svg` elements, along with the markers (e.g., `<svg><!-- htmlmin:ignore --><g id="a"></g><!-- htmlmin:ignore --></svg>` became `<svg/>`); such `svg` elements now skip SVGO

## [5.4.1] - 2026-11-22

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ const result = await minify(html, {
});
```

To exempt individual `svg` elements, pass `canMinifySVG` a synchronous function. It receives each outermost `svg` element, including any `svg` elements nested in it, as the HTML pass wrote it (e.g., without comments under `removeComments`), and one for which it returns `false` skips SVGO. To keep an `svg` element exactly as written, [wrap it in `<!-- htmlmin:ignore -->`](#ignoring-chunks-of-markup) instead.
To exempt individual `svg` elements, pass `canMinifySVG` a synchronous function. It receives each outermost `svg` element, including any `svg` elements nested in it, as the HTML pass wrote it (e.g., without comments under `removeComments`), and one for which it returns `false` skips SVGO. To keep an `svg` element exactly as written, [wrap it in `<!-- htmlmin:ignore -->`](#ignoring-chunks-of-markup) instead. An `svg` element that holds `<!-- htmlmin:ignore -->` markup skips SVGO, as SVGO would drop it.

```js
const result = await minify(html, {
Expand Down
464 changes: 261 additions & 203 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@
"devDependencies": {
"@eslint/js": "^10.0.1",
"@swc/core": "^1.16.22",
"@types/node": "^26.6.6",
"@types/node": "^26.6.11",
"alpinejs": "^3.17.5",
"eslint": "^10.15.0",
"eslint": "^10.16.0",
"globals": "^17.14.0",
"parse5": "^8.1.1",
"typescript": "^7.0.2",
"vite": "^8.3.8"
"vite": "^8.4.0"
},
"engines": {
"node": ">=22.13"
Expand Down Expand Up @@ -99,5 +99,5 @@
},
"type": "module",
"types": "dist/types/htmlminifier.d.ts",
"version": "5.4.1"
"version": "5.4.2"
}
96 changes: 89 additions & 7 deletions src/htmlminifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
buildInlineSets,
defaultInlineSets,
endsWithWhitespace,
isAsciiWhitespace,
trimWhitespace,
collapseWhitespaceAll,
collapseNoBreakSpaces,
Expand Down Expand Up @@ -702,6 +703,7 @@ const RE_END_TAG = /^<\//;
const RE_WHITESPACE_ONLY = /^\s+$/;
const RE_TABS = /\t/g;
const RE_TRAILING_WHITESPACE = /\s$/;
const RE_LINE_BREAK = /[\n\r]/;
const RE_LINE_BREAK_BLANKS_END = /(?:\r\n?|\n)[ \t\f]*$/;
const RE_BLANKS_LINE_BREAK_START = /^[ \t\f]*(?:\r\n?|\n)/;
const RE_BLANKS_START = /^[ \t\f]+/;
Expand Down Expand Up @@ -953,6 +955,21 @@ async function createSortFns(value, options, uidIgnore, ignoredMarkupChunks) {
}
}

// The length of the ASCII whitespace `str` starts or ends with
/**
* @param {string} str
* @param {boolean} atEnd
*/
function edgeWhitespaceLength(str, atEnd) {
let length = 0;
if (atEnd) {
while (length < str.length && isAsciiWhitespace(str.charCodeAt(str.length - 1 - length))) length++;
} else {
while (length < str.length && isAsciiWhitespace(str.charCodeAt(length))) length++;
}
return length;
}

// Match `/^<\/([\w:-]+)>$/` by hand—the regex engine’s per-call setup costs more
// than the scan on these short buffer entries
/**
Expand Down Expand Up @@ -1092,6 +1109,10 @@ async function minifyHTML(value, options, partialMarkup) {
let textVerbatim = false;
/** @type {string[]} */
const ignoredMarkupChunks = [];
// Placeholders of `htmlmin:ignore` blocks where whitespace collapses, each followed
// by where in `buffer` it went
/** @type {Array<string | number>} */
const ignoredMarkupCollapsing = [];
/** @type {Array<[string, string, string]>} */
const ignoredCustomMarkupChunks = [];
// Custom fragments whose surrounding whitespace is never trimmed: in tags, where it
Expand Down Expand Up @@ -1641,6 +1662,43 @@ async function minifyHTML(value, options, partialMarkup) {
}
}

// Whitespace next to an `htmlmin:ignore` block that starts or ends with whitespace renders
// the same without it; a line break under `preserveLineBreaks` stays unless the block has one
function trimIgnoreEdges() {
const indexStart = '<!--'.length + (uidIgnore ?? '').length;
for (let i = 0; i < ignoredMarkupCollapsing.length; i += 2) {
const placeholder = /** @type {string} */ (ignoredMarkupCollapsing[i]);
const indexPushed = /** @type {number} */ (ignoredMarkupCollapsing[i + 1]);
// Entries removed before a placeholder move it down
const index = buffer[indexPushed] === placeholder ? indexPushed : buffer.lastIndexOf(placeholder, indexPushed);
if (index === -1) continue;
const content = ignoredMarkupChunks[+placeholder.slice(indexStart, -3)] ?? '';
trimIgnoreEdge(content, findNeighbors(index)[0], false);
trimIgnoreEdge(content, findNeighbors(index + 1)[1], true);
}
}

// `atEnd` is the side of the block, `neighbor` the entry on that side
function trimIgnoreEdge(/** @type {string} */ content, /** @type {number} */ neighbor, /** @type {boolean} */ atEnd) {
let text = buffer[neighbor];
if (!text) return;
// Text passing SVGO as a placeholder is trimmed where it’s kept
const token = uidSVGRawText && text.startsWith('/*!' + uidSVGRawText) && text.endsWith('*/')
? +text.slice(3 + uidSVGRawText.length, -2)
: -1;
if (token !== -1) text = svgRawTexts[token];
if (!text) return;
const inner = edgeWhitespaceLength(content, atEnd);
const outer = inner && edgeWhitespaceLength(text, !atEnd);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (!outer) return;
if (options.preserveLineBreaks &&
RE_LINE_BREAK.test(atEnd ? text.slice(0, outer) : text.slice(-outer)) &&
!RE_LINE_BREAK.test(atEnd ? content.slice(-inner) : content.slice(0, inner))) return;
const trimmed = atEnd ? text.slice(outer) : text.slice(0, -outer);
if (token !== -1) svgRawTexts[token] = trimmed;
else bufferSet(neighbor, trimmed);
}

function lastStartTagIndex() {
let index = buffer.length - 1;
while (index > 0 && !RE_START_TAG.test(buffer[index] ?? '')) {
Expand Down Expand Up @@ -2348,6 +2406,9 @@ async function minifyHTML(value, options, partialMarkup) {
}
}
}
if (!stackNoTrimWhitespace.length && !stackNoCollapseWhitespace.length) {
ignoredMarkupCollapsing.push(comment, buffer.length);
}
}
}

Expand Down Expand Up @@ -3131,19 +3192,40 @@ async function minifyHTML(value, options, partialMarkup) {
await mergeElements(mergeRecords);
}

// Before SVGO joins entries, which `trimIgnoreEdges` would have to search past
if (ignoredMarkupCollapsing.length) {
trimIgnoreEdges();
}

// Post-processing: Optimize SVG blocks with SVGO
// Run all SVGO calls in parallel, then splice results in reverse to preserve indices
const minifySVG = options.minifySVG;
if (minifySVG && svgBlocks.length) {
const optimized = await Promise.all(
svgBlocks.map(({ start, end }) =>
minifySVG(buffer.slice(start, end).join(''))
)
);
const optimized = await Promise.all(svgBlocks.map(({ start, end }) => {
const source = buffer.slice(start, end).join('');
// `htmlmin:ignore` placeholders are comments, which SVGO drops with what they stand for.
// (Keeping them, or lifting the markup out and dropping it back in, wouldn’t be safe,
// either: SVGO may move or remove what surrounds them, and it can’t see what they hold,
// like references to IDs and definitions it then removes or renames.)
// Raw text in HTML content holds them as text, passing SVGO as a placeholder.
if (uidIgnore && (source.includes(uidIgnore) || svgRawTexts.some((text, index) =>
text.includes(uidIgnore) && source.includes('/*!' + uidSVGRawText + index + '*/')))) {
options.log('Skipping SVGO for an `svg` element holding `htmlmin:ignore` markup, which SVGO would drop');
// Attribute values were escaped for SVGO, placeholders in them included
const escaped = '&lt;!--' + uidIgnore;
for (let i = start; i < end; i++) {
const entry = buffer[i] ?? '';
if (entry.includes(escaped)) bufferSet(i, entry.replaceAll(escaped, '<!--' + uidIgnore));
}
return null;
}
return minifySVG(source);
}));
for (let i = svgBlocks.length - 1; i >= 0; i--) {
const block = svgBlocks[i];
if (block) {
buffer.splice(block.start, block.end - block.start, optimized[i] ?? '');
const result = optimized[i];
if (block && result != null) {
buffer.splice(block.start, block.end - block.start, result);
bufferTags?.splice(block.start, block.end - block.start, false);
}
}
Expand Down
19 changes: 10 additions & 9 deletions src/lib/whitespace.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,18 @@ const trimWhitespace = str => {
if (!str) return str;
let start = 0;
let end = str.length;
while (start < end && isAsciiWs(str.charCodeAt(start))) start++;
while (end > start && isAsciiWs(str.charCodeAt(end - 1))) end--;
while (start < end && isAsciiWhitespace(str.charCodeAt(start))) start++;
while (end > start && isAsciiWhitespace(str.charCodeAt(end - 1))) end--;
return start === 0 && end === str.length ? str : str.slice(start, end);
};

/** @param {number} code */
function isAsciiWs(code) {
function isAsciiWhitespace(code) {
return code === 32 || code === 10 || code === 13 || code === 9 || code === 12;
}

/** @param {number} code */
function isWsOrNbsp(code) {
function isWhitespaceOrNbsp(code) {
return code === 32 || code === 10 || code === 13 || code === 9 || code === 12 || code === 160;
}

Expand All @@ -64,7 +64,7 @@ function isAllWhitespace(str) {
// Whether the last character is whitespace, no-break space included
/** @param {string} str */
function endsWithWhitespace(str) {
return str.length > 0 && isWsOrNbsp(str.charCodeAt(str.length - 1));
return str.length > 0 && isWhitespaceOrNbsp(str.charCodeAt(str.length - 1));
}

// Module scope so the hot path doesn’t allocate a closure per call
Expand Down Expand Up @@ -189,7 +189,7 @@ function collapseWhitespaceKnown(str, options, trimLeft, trimRight, collapseAll,
let hasLineBreak = false;
for (; leadEnd < str.length; leadEnd++) {
const code = str.charCodeAt(leadEnd);
if (!isAsciiWs(code)) break;
if (!isAsciiWhitespace(code)) break;
// Settling the line break in the same pass keeps the run from being walked twice
if (code === 10 || code === 13) hasLineBreak = true;
}
Expand All @@ -203,7 +203,7 @@ function collapseWhitespaceKnown(str, options, trimLeft, trimRight, collapseAll,
let hasLineBreak = false;
for (; trailStart > 0; trailStart--) {
const code = str.charCodeAt(trailStart - 1);
if (!isAsciiWs(code)) break;
if (!isAsciiWhitespace(code)) break;
if (code === 10 || code === 13) hasLineBreak = true;
}
if (hasLineBreak) {
Expand All @@ -217,7 +217,7 @@ function collapseWhitespaceKnown(str, options, trimLeft, trimRight, collapseAll,
// Find the leading whitespace boundary with a loop, so the common case neither
// allocates a replacer closure nor runs the regex machinery
let start = 0;
while (start < str.length && isWsOrNbsp(str.charCodeAt(start))) {
while (start < str.length && isWhitespaceOrNbsp(str.charCodeAt(start))) {
start++;
}
if (start > 0) {
Expand All @@ -241,7 +241,7 @@ function collapseWhitespaceKnown(str, options, trimLeft, trimRight, collapseAll,
// Find trailing whitespace boundary manually (avoids polynomial backtracking
// with `/[ \n\r\t\f\xA0]+$/` on strings with long internal whitespace runs)
let end = str.length;
while (end > 0 && isWsOrNbsp(str.charCodeAt(end - 1))) {
while (end > 0 && isWhitespaceOrNbsp(str.charCodeAt(end - 1))) {
end--;
}
if (end < str.length) {
Expand Down Expand Up @@ -418,6 +418,7 @@ export {
buildInlineSets,
defaultInlineSets,
endsWithWhitespace,
isAsciiWhitespace,
trimWhitespace,
collapseWhitespaceAll,
collapseNoBreakSpaces,
Expand Down
50 changes: 50 additions & 0 deletions test/html.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6456,6 +6456,56 @@ describe('HTML', () => {
assert.strictEqual(await minify(`<p>a\n<script></script>${ignore}<span>b</span>${ignore}\n</p>`, { collapseWhitespace: true }), '<p>a <script></script><span>b</span></p>');
});

test('Drops whitespace next to `htmlmin:ignore` blocks that start or end with whitespace', async () => {
const ignore = '<!-- htmlmin:ignore -->';
const collapse = { collapseWhitespace: true };
const assertStable = async (input, output, options) => {
assert.strictEqual(await minify(input, options), output);
assert.strictEqual(await minify(output, options), output);
};

// The block’s own whitespace stands in for the whitespace outside it
await assertStable(`a ${ignore} x ${ignore} b`, 'a x b', collapse);
await assertStable(`<div>\n\t${ignore}\n<span>x</span>\n${ignore}\n\t</div>`, '<div>\n<span>x</span>\n</div>', { collapseWhitespace: true, preserveLineBreaks: true });
await assertStable(`<span>a</span> ${ignore} <b>x</b> ${ignore} <span>b</span>`, '<span>a</span> <b>x</b> <span>b</span>', collapse);
await assertStable(`<p>a ${ignore} x ${ignore} b</p>`, '<p>a x b</p>', { collapseWhitespace: true, conservativeCollapse: true });
await assertStable(` ${ignore} x ${ignore} `, ' x ', { collapseWhitespace: true, partialMarkup: true });
await assertStable(`<p>a ${ignore} x ${ignore} b</p>`, '<p\n>a x b</p>', { collapseWhitespace: true, maxLineLength: 5 });

// The block’s own whitespace stays, even where it would go once no longer ignored
assert.strictEqual(await minify(`<div>a\n${ignore}\nx\n${ignore}\nb</div>`, collapse), '<div>a\nx\nb</div>');
assert.strictEqual(await minify(`<div> ${ignore} x ${ignore} </div>`, collapse), '<div> x </div>');
assert.strictEqual(await minify(`a ${ignore} x ${ignore} \n ${ignore} y ${ignore} b`, collapse), 'a x y b');
assert.strictEqual(await minify(`<div></div> ${ignore} x ${ignore} <div></div>`, collapse), '<div></div> x <div></div>');

// A line break outside stays where the block holds none
assert.strictEqual(await minify(`<p>a\n${ignore} x ${ignore}\nb</p>`, { collapseWhitespace: true, preserveLineBreaks: true }), '<p>a\n x \nb</p>');

// A no-break space isn’t collapsible whitespace, outside or in the block
await assertStable(`a&nbsp;${ignore} x ${ignore}&nbsp;b`, 'a&nbsp; x &nbsp;b', collapse);
assert.strictEqual(await minify(`a ${ignore}\u00a0x\u00a0${ignore} b`, collapse), 'a \u00a0x\u00a0 b');

// Whitespace elsewhere stays: Across a tag, which the block’s whitespace doesn’t lie beyond …
assert.strictEqual(await minify(`<p>a <span>${ignore} x ${ignore}</span> b</p>`, collapse), '<p>a <span> x </span> b</p>');
// … where it doesn’t collapse …
assert.strictEqual(await minify(`<pre>a ${ignore} x ${ignore} b</pre>`, collapse), '<pre>a x b</pre>');
assert.strictEqual(await minify(`<textarea>a ${ignore} x ${ignore} b</textarea>`, collapse), '<textarea>a x b</textarea>');
assert.strictEqual(await minify(`<div title="a ${ignore} x ${ignore} b">c</div>`, collapse), '<div title="a x b">c</div>');
// … and without `collapseWhitespace`
assert.strictEqual(await minify(`a ${ignore} x ${ignore} b`), `a x b`);
});

test('Drops whitespace between custom fragments and `htmlmin:ignore` blocks under `trimCustomFragments`', async () => {
const ignore = '<!-- htmlmin:ignore -->';
const input = `a {{ x }} ${ignore} y ${ignore} {{ z }} b`;
const options = { collapseWhitespace: true, ignoreCustomFragments: [/\{\{[\s\S]*?\}\}/] };
assert.strictEqual(await minify(input, { ...options, trimCustomFragments: true }), 'a {{ x }} y {{ z }} b');
assert.strictEqual(await minify('a {{ x }} y {{ z }} b', { ...options, trimCustomFragments: true }), 'a {{ x }} y {{ z }} b');

// Otherwise, whitespace around custom fragments stays
assert.strictEqual(await minify(input, options), 'a {{ x }} y {{ z }} b');
});

test('Minifies `meta` viewport', async () => {
let input, output;

Expand Down
30 changes: 30 additions & 0 deletions test/svg+mathml.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1764,6 +1764,36 @@ describe('SVG and MathML', () => {
assert.strictEqual(result, '<svg>\n <!-- keep -->\n <rect width="100" height="100" />\n</svg>');
});

test('Skips SVGO for an `svg` element holding `htmlmin:ignore` markup', async () => {
const ignore = '<!-- htmlmin:ignore -->';
const logs = [];
const options = { minifySVG: true, collapseWhitespace: true, log: message => logs.push(String(message)) };

// In content, in text, and in attribute values, which SVGO would all drop
assert.strictEqual(await minify(`<svg><g id="a"></g>${ignore}<g id="b"></g>${ignore}</svg>`, options), '<svg><g id="a"></g><g id="b"></g></svg>');
assert.strictEqual(await minify(`<svg><text>a ${ignore} x ${ignore} b</text></svg>`, options), '<svg><text>a x b</text></svg>');
assert.strictEqual(await minify(`<svg><rect title="${ignore}x y${ignore}"/></svg>`, options), '<svg><rect title="x y"/></svg>');
// HTML text with whitespace at an end passes SVGO as a placeholder, which still collapses
assert.strictEqual(
await minify(`<svg><foreignObject><p>a ${ignore} x ${ignore} b</p></foreignObject></svg>`, options),
'<svg><foreignObject><p>a x b</p></foreignObject></svg>'
);
assert.ok(logs.some(message => message.includes('htmlmin:ignore')));

// Other `svg` elements are still optimized, as is one an ignored block holds entirely
assert.strictEqual(
await minify(`<svg><g id="a"></g>${ignore}<g id="b"></g>${ignore}</svg><svg><g id="c"></g></svg>${ignore}<svg><g></g></svg>${ignore}`, options),
'<svg><g id="a"></g><g id="b"></g></svg><svg/><svg><g></g></svg>'
);

// A function of one’s own is skipped, too, also for raw text in HTML content
assert.strictEqual(await minify(`<svg>${ignore}<g></g>${ignore}</svg>`, { minifySVG: () => '<svg/>' }), '<svg><g></g></svg>');
assert.strictEqual(
await minify(`<svg><foreignObject><script>${ignore}keep()${ignore}</script></foreignObject></svg>`, { minifySVG: () => '<svg/>' }),
'<svg><foreignObject><script>keep()</script></foreignObject></svg>'
);
});

test('Leaves CSS within an `svg` element as written only through `canMinifySVG`', async () => {
const source = '<svg><style>.a { fill: red; }</style><rect class="a" width="10" height="10"/></svg>';
const options = { minifySVG: true, minifyCSS: true, canMinifyCSS: () => false };
Expand Down