Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ 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.0] - 2026-11-20

### Fixed

* Fixed `partialMarkup` failing on a stray `</svg>` or `</math>` end tag (e.g., `</svg><svg><rect/></svg>` threw “Cannot read properties of undefined”)

### Changed

* Changed `collapseWhitespace` to keep whitespace at either end of `partialMarkup` fragments as a single space (or line break, with `preserveLineBreaks`) where it may separate the fragment from what surrounds it, as next to text, inline elements, and elements that don’t render (previously, ` <b>Jane</b>\n` became `<b>Jane</b>`, and `a <link rel="x">` became `a<link rel="x">`), while it still goes next to block elements
* Made pages with inline SVG or MathML faster to minify, as the first `svg` or `math` element slowed down the minification of the rest of the page (by 10–20% on pages without much SVG or MathML)

## [5.3.1] - 2026-11-19
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ Where the modifiers disagree, the preserving one wins—`conservativeCollapse` a

`collapseWhitespace` goes by the element, not by CSS, so whitespace in an element styled `white-space: pre` collapses unless you protect it with [`canCollapseWhitespace` and `canTrimWhitespace`](#api-only-options).

Regardless of these options, whitespace at the start and end of the output goes, and so do lines that a removed comment or tag leaves with nothing but whitespace (blank lines of the source stay). Whitespace stays, however, where it’s kept verbatim (in `pre` or `textarea`, or in `pre`, `textarea`, or `script` content left open at the end), next to custom fragments where their handling keeps it (see `trimCustomFragments`), at either end of partial markup (cf. `partialMarkup`), and where `conservativeCollapse` or `preserveLineBreaks` keep it.
Regardless of these options, whitespace at the start and end of the output goes, and so do lines that a removed comment or tag leaves with nothing but whitespace (blank lines of the source stay). Whitespace stays, however, where it’s kept verbatim (in `pre` or `textarea`, or in `pre`, `textarea`, or `script` content left open at the end), next to custom fragments where their handling keeps it (see `trimCustomFragments`), at either end of partial markup (cf. `partialMarkup`; `collapseWhitespace` collapses it there), and where `conservativeCollapse` or `preserveLineBreaks` keep it.

Note: `preserveLineBreaks` keeps line breaks, not indentation. HTML Minifier doesn’t format: To keep the source formatting, leave `collapseWhitespace` off (as in the first row of the table above). Line breaks and indentation then stay as written, while other options still apply.

Expand Down Expand Up @@ -707,7 +707,7 @@ By default, HM parses markup into a complete tree structure, then modifies it (r

_Input markup (e.g., `<p id="">foo`) → Internal representation of markup in a form of tree (e.g., `{ tag: "p", attr: "id", children: ["foo"] }`) → Transformation of internal representation (e.g., removal of `id` attribute) → Output of resulting markup (e.g., `<p>foo</p>`)_

For partial HTML fragments (such as template includes, SSI fragments, or closing tags without opening tags), use the `partialMarkup: true` option. This preserves stray end tags and prevents auto-closing of unclosed tags at the end of input. Note that normal HTML auto-closing rules still apply during parsing—for example, a closing parent tag will still auto-close its unclosed child elements, and an end tag browsers ignore because a block element is still open inside its element is removed (use `<!-- htmlmin:ignore -->` to keep such markup as written). Whitespace at the start and end of a fragment stays, too, as it may separate the fragment from what surrounds it (unless `collapseWhitespace` removes it). `removeRedundantAttributes` keeps `target="_self"` in partial markup, as there may be a `base` element setting another target elsewhere. (Where an external script adds such a `base` element, wrap links whose `target="_self"` needs to stay in `<!-- htmlmin:ignore -->`.)
For partial HTML fragments (such as template includes, SSI fragments, or closing tags without opening tags), use the `partialMarkup: true` option. This preserves stray end tags and prevents auto-closing of unclosed tags at the end of input. Note that normal HTML auto-closing rules still apply during parsing—for example, a closing parent tag will still auto-close its unclosed child elements, and an end tag browsers ignore because a block element is still open inside its element is removed (use `<!-- htmlmin:ignore -->` to keep such markup as written). Whitespace at the start and end of a fragment stays, too, as it may separate the fragment from what surrounds it. `collapseWhitespace` collapses it to a space (or line break, with `preserveLineBreaks`) where text in its place would keep one, as next to text and inline elements, and removes it next to block elements (e.g., ` <b>Jane</b>\n` becomes ` <b>Jane</b> `, while `\n<div>…</div>\n` becomes `<div>…</div>`). `removeRedundantAttributes` keeps `target="_self"` in partial markup, as there may be a `base` element setting another target elsewhere. (Where an external script adds such a `base` element, wrap links whose `target="_self"` needs to stay in `<!-- htmlmin:ignore -->`.)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Markup with [parse errors](https://html.spec.whatwg.org/multipage/parsing.html#parse-errors) that HM cannot read, like a stray `</>` or an `=` in an unquoted attribute value, makes it abort with the line and column of the error, so that the error can be fixed. With `continueOnParseError`, HM handles such errors the way browsers do instead.

Expand Down
18 changes: 9 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"entities": "^9.0.0",
"lightningcss": "^1.33.0",
"svgo": "^4.1.0",
"terser": "^5.51.2"
"terser": "^5.51.3"
},
"description": "Highly effective, super-configurable, well-tested web page minifier",
"devDependencies": {
Expand Down Expand Up @@ -98,5 +98,5 @@
},
"type": "module",
"types": "dist/types/htmlminifier.d.ts",
"version": "5.3.1"
"version": "5.4.0"
}
33 changes: 24 additions & 9 deletions src/htmlminifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -973,6 +973,13 @@ function matchPlainEndTag(str) {
return str.slice(2, end - 1);
}

// At either end of partial markup, collapsed whitespace may separate the fragment from what
// surrounds it, and so stays where text in its place would keep it
/** @param {ProcessedOptions} options */
function keepsEdgeWhitespace(options) {
return Boolean(options.collapseWhitespace && options.partialMarkup && !options.conservativeCollapse);
}

/**
* @param {string} value
* @param {ProcessedOptions} options
Expand All @@ -985,7 +992,9 @@ async function minifyHTML(value, options, partialMarkup) {
throw new Error(`Input length (${value.length}) exceeds maximum allowed length (${options.maxInputLength})`);
}

if (options.collapseWhitespace) {
const keepsEdges = keepsEdgeWhitespace(options);

if (options.collapseWhitespace && !keepsEdges) {
value = collapseWhitespace(value, options, true, true);
}

Expand Down Expand Up @@ -1949,7 +1958,8 @@ async function minifyHTML(value, options, partialMarkup) {
index--;
}
}
return false;
// What precedes partial markup may run into it, too
return keepsEdges;
}

// Per-text-node context for `charsCollapse`/`charsFinalize`, set by the `chars`
Expand Down Expand Up @@ -2084,7 +2094,7 @@ async function minifyHTML(value, options, partialMarkup) {
}
}
} else {
text = collapseWhitespace(text, options, true, true);
text = collapseWhitespace(text, options, !keepsEdges, !keepsEdges);
}
if (!text && RE_TRAILING_WHITESPACE.test(currentChars) && textPrevTag && textPrevTag.charAt(0) === '/' && !holdTransparentGap(buffer.length - 1, textNextTag)) {
trimTrailingWhitespace(buffer.length - 1, textNextTag);
Expand Down Expand Up @@ -2995,15 +3005,16 @@ async function minifyHTML(value, options, partialMarkup) {
}
}
},
chars: function (/** @type {string} */ text, /** @type {string} */ prevTag, /** @type {string} */ nextTag, /** @type {HTMLAttribute[]} */ prevAttrs, /** @type {HTMLAttribute[]} */ nextAttrs, /** @type {boolean} */ source) {
chars: function (/** @type {string} */ text, /** @type {string} */ prevTag, /** @type {string} */ nextTag, /** @type {HTMLAttribute[]} */ prevAttrs, /** @type {HTMLAttribute[]} */ nextAttrs, /** @type {boolean} */ source, /** @type {boolean} */ first, /** @type {boolean} */ last) {
if (mergeRecord) {
if (mergeRecord.content === -1) mergeRecord.content = buffer.length;
// Custom fragments may hold anything, which minified CSS can’t take as written
if (mergeRecord.kind === 'style' && markers.length && markers.some(marker => text.includes(marker))) mergeRecord.key = null;
}
// Publish this node’s context for the `charsCollapse`/`charsFinalize` phases
textPrevTag = followsRemovedBlock ? charsPrevTag || 'comment' : prevTag === '' ? 'comment' : prevTag;
textNextTag = nextTag === '' ? 'comment' : nextTag;
// An edge of partial markup reads as no tag, so that whitespace there may stay
textPrevTag = followsRemovedBlock ? charsPrevTag || 'comment' : first && keepsEdges ? '' : prevTag === '' ? 'comment' : prevTag;
textNextTag = last && keepsEdges ? '' : nextTag === '' ? 'comment' : nextTag;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
textPrevAttrs = prevAttrs || [];
textNextAttrs = nextAttrs || [];

Expand Down Expand Up @@ -3103,7 +3114,7 @@ async function minifyHTML(value, options, partialMarkup) {

// Nothing follows at the end, so pending whitespace goes (before SVG blocks shift the buffer)
if (transparentGapIndex !== -1) {
settleTransparentGap(Boolean(options.conservativeCollapse));
settleTransparentGap(Boolean(options.conservativeCollapse) || keepsEdges);
}

if (mergeRecords && (mergeRecords.length > 1 || mergeRecords[0]?.deferred)) {
Expand Down Expand Up @@ -3151,7 +3162,7 @@ async function minifyHTML(value, options, partialMarkup) {
}
// Collapsing also trims whitespace before trailing inline end tags; trimming the output
// catches what it leaves at either end, like a space after a removed leading comment
if (options.collapseWhitespace) {
if (options.collapseWhitespace && !keepsEdges) {
squashTrailingWhitespace('br');
}
trimOutputWhitespace();
Expand Down Expand Up @@ -3264,7 +3275,11 @@ function joinResultSegments(results, resultTags, markers, options, restoreCustom
} else {
str = restoreIgnore(restoreCustom(results.join('')));
}
return options.collapseWhitespace ? collapseWhitespace(str, options, true, true) : str;
if (!options.collapseWhitespace) {
return str;
}
const trims = !keepsEdgeWhitespace(options);
return collapseWhitespace(str, options, trims, trims);
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/htmlparser.js
Original file line number Diff line number Diff line change
Expand Up @@ -808,8 +808,9 @@ export class HTMLParser {
}

if (handler.chars) {
// An element whose end tag follows its start tag’s text alone has that text for content
const result = handler.chars(text, prevTag, nextTag, prevAttrs, nextAttrs, sourcePos !== -1 && isSource(pos - text.length));
// An element whose end tag follows its start tag’s text alone has that text for content;
// the last two arguments say whether the text starts or ends the input
const result = handler.chars(text, prevTag, nextTag, prevAttrs, nextAttrs, sourcePos !== -1 && isSource(pos - text.length), pos === text.length, pos === fullLength);
if (isThenable(result)) await result;
}
prevTag = '';
Expand Down
48 changes: 46 additions & 2 deletions test/html.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3446,11 +3446,13 @@ describe('HTML', () => {
assert.strictEqual(await minify(' <p>a</p> ', { collapseWhitespace: true, conservativeCollapse: true }), ' <p>a</p> ');
assert.strictEqual(await minify('\n<p>a</p>\n', { collapseWhitespace: true, preserveLineBreaks: true }), '\n<p>a</p>\n');

// Partial markup ends where other markup joins it, so `collapseWhitespace` alone decides
// Partial markup ends where other markup joins it, so `collapseWhitespace` collapses
// whitespace there as next to text
assert.strictEqual(await minify('Hello ', { partialMarkup: true }), 'Hello ');
assert.strictEqual(await minify(' <b>x</b> ', { partialMarkup: true }), ' <b>x</b> ');
assert.strictEqual(await minify('<!-- c --> world', { partialMarkup: true, removeComments: true }), ' world');
assert.strictEqual(await minify(' <b>x</b> ', { partialMarkup: true, collapseWhitespace: true }), '<b>x</b>');
assert.strictEqual(await minify(' \n<b>x</b>\n ', { partialMarkup: true, collapseWhitespace: true }), ' <b>x</b> ');
assert.strictEqual(await minify(' <p>x</p> ', { partialMarkup: true, collapseWhitespace: true }), '<p>x</p>');
});

// https://github.com/kangax/html-minifier/issues/10
Expand Down Expand Up @@ -7971,6 +7973,48 @@ describe('HTML', () => {
'partialMarkup and removeOptionalTags work independently (optional </p> is removed)');
});

test('Collapses whitespace at the edges of partial markup', async () => {
const options = { partialMarkup: true, collapseWhitespace: true };
const cases = [
// Text and inline elements may join what surrounds the fragment
[' foo ', ' foo '],
[' <b>x</b> ', ' <b>x</b> '],
['\n\t<span>x</span>\n', ' <span>x</span> '],
['<p>foo ', '<p>foo '],
[' \n ', ' '],
// So may what precedes elements that don’t render
['a <link rel="x">', 'a <link rel="x">'],
['a <link rel="x"> ', 'a <link rel="x">'],
[' <link rel="x"> b', '<link rel="x"> b'],
['<span>x</span> <link rel="x">', '<span>x</span> <link rel="x">'],
// Next to block elements, whitespace doesn’t render
['\n<p>x</p>\n', '<p>x</p>'],
['</div> ', '</div>'],
[' <div>x</div> ', '<div>x</div>'],
// Whitespace inside stays collapsed as before
['<div> x </div>', '<div>x</div>'],
['</div> </div> <div class="clearfix"></div>', '</div></div><div class="clearfix"></div>']
];
for (const [input, output] of cases) {
assert.strictEqual(await minify(input, options), output, JSON.stringify(input));
}

// Comments, kept or removed
assert.strictEqual(await minify('foo <!-- c --> ', options), 'foo<!-- c --> ');
assert.strictEqual(await minify('foo <!-- c -->', { ...options, removeComments: true }), 'foo ');

// `preserveLineBreaks` keeps a line break, and a space where there is none
assert.strictEqual(await minify('\n<span>x</span>\n', { ...options, preserveLineBreaks: true }), '\n<span>x</span>\n');
assert.strictEqual(await minify(' foo ', { ...options, preserveLineBreaks: true }), ' foo ');
assert.strictEqual(await minify('\n<p>x</p>\n', { ...options, preserveLineBreaks: true }), '\n<p>x</p>\n');

// Unchanged: Full documents, `conservativeCollapse`, and no `collapseWhitespace`
assert.strictEqual(await minify(' foo ', { collapseWhitespace: true }), 'foo');
assert.strictEqual(await minify('a <link rel="x">', { collapseWhitespace: true }), 'a<link rel="x">');
assert.strictEqual(await minify('\n<p>x</p>\n', { ...options, conservativeCollapse: true }), ' <p>x</p> ');
assert.strictEqual(await minify(' foo ', { partialMarkup: true }), ' foo ');
});

test('Runs the code minifiers once with `sortAttributes` and `sortClassNames`', async () => {
const input = '<style>p{color:red}</style><p style="color:blue" onclick="go()" class="b a"><a href="/x">x</a></p><script>go()</script><svg><circle r="1"/></svg>';
const calls = { css: 0, js: 0, urls: 0, svg: 0 };
Expand Down