Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
9 changes: 8 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@ 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.1] - 2026-11-22

### Fixed

* Fixed `minifyJS` breaking scripts where a custom fragment starts a statement after a label or `case` the fragment check missed—after a template literal holding a backtick (``var s = `${"`"}`; l: <?= $x ?>;`` became ``var s="`";b(), <?= $x ?>``), after a label with a non-ASCII name, and after a label within a block (`switch (a) { case 1: { l: <?= $x ?> } }`)—by parsing JavaScript with Acorn rather than reading it by hand
* Fixed `minifyCSS` and `minifyJS` changing the quotes around custom fragments in strings, which breaks values escaped for the original quotes (e.g., `var a = '<?= $x ?>'` became `var a="<?= $x ?>"`, and `url('<?= $u ?>')` became `url(<?= $u ?>)`), turning template literals holding custom fragments into strings, and repeating custom fragments (`x = { <?= $x ?> }` became `x={<?= $x ?>:<?= $x ?>}`); such code now stays as written
* Fixed `minifyJS` doubling whitespace next to custom fragments in strings that Terser escapes (e.g., a tab before `<?= $x ?>` in a string became `\t` and the tab)

### Changed

* Made minification faster by checking short attribute and class lists for repeats without building a set
* Changed the backtest’s user agent to `html-minifier-backtest (+https://github.com/j9t/html-minifier/tree/main/backtest)`, dropping the placeholder version and adding a URL

## [5.4.0] - 2026-11-20
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -735,7 +735,9 @@ HTML reads CRLF and CR line breaks as line feeds, so HM writes them so, too. Mar

By default, `ignoreCustomFragments` preserves `<?php … ?>`, `<?= … ?>`, `<? … ?>`, and `<% … %>` blocks (as well as XML declarations), so PHP, ERB, JSP, and ASP templates can be minified as part of a build, with the markup, CSS, and JavaScript around those blocks being minified as usual. For includes and other partials, add `partialMarkup`.

CSS and JavaScript are only left as written where a template block starts a rule or statement (`<?php if ($a): ?>` between two statements, `<?= $rules ?>` after a rule, or `<?= $code ?>` after `case 1:`, `default:`, or a label), as it may render as anything or as nothing, or where it sits in an `@charset`, `@import`, or `@namespace` statement that would otherwise be dropped with it (`@import <?= $url ?>;`). Template blocks within values (`color: <?= $color ?>`) are safe—here, the code around them is minified, so a block in code that minification removes (such as an unused rule or dead code) goes with that code. This detection is best-effort, as HTML Minifier doesn’t parse template code. To exempt anything it misses, use [`canMinifyCSS`](#css-minification) or [`canMinifyJS`](#javascript-minification).
CSS and JavaScript are only left as written where a template block starts a rule or statement (`<?php if ($a): ?>` between two statements, `<?= $rules ?>` after a rule, or `<?= $code ?>` after `case 1:`, `default:`, or a label), as it may render as anything or as nothing, or where it sits in an `@charset`, `@import`, or `@namespace` statement that would otherwise be dropped with it (`@import <?= $url ?>;`). They’re also left as written where minifying would move a template block into another kind of string (Terser and Lightning CSS turn `'<?= $name ?>'` into `"<?= $name ?>"`, which breaks if the value is escaped for single quotes only), repeat it, or change the whitespace around it within a string, and JavaScript is left as written where it doesn’t parse with the template blocks in it.

Template blocks within values (`color: <?= $color ?>`) are safe—here, the code around them is minified, so a block in code that minification removes (such as an unused rule or dead code) goes with that code. This detection is best-effort: HTML Minifier parses JavaScript (with [Acorn](https://github.com/acornjs/acorn)), but not the template code itself. To exempt anything it misses, use [`canMinifyCSS`](#css-minification) or [`canMinifyJS`](#javascript-minification).
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Whitespace next to template blocks is collapsed but kept, as it may matter once the template renders. `trimCustomFragments` removes it where HTML Minifier would remove whitespace anyway, as between block-level elements: `<ul> <?php foreach ($items as $item): ?> <li>` loses it, `Hello <?= $name ?>!` keeps it. Tags keep the spacing of their source, and whitespace next to template blocks in attribute values, CSS, and JavaScript is always kept.

Expand Down
31 changes: 16 additions & 15 deletions package-lock.json

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

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
},
"bugs": "https://github.com/j9t/html-minifier/issues",
"dependencies": {
"acorn": "^8.19.0",
"commander": "^15.1.0",
"entities": "^9.0.0",
"lightningcss": "^1.33.0",
"svgo": "^4.1.0",
"terser": "^5.51.3"
"terser": "^5.51.4"
},
"description": "Highly effective, super-configurable, well-tested web page minifier",
"devDependencies": {
Expand Down Expand Up @@ -98,5 +99,5 @@
},
"type": "module",
"types": "dist/types/htmlminifier.d.ts",
"version": "5.4.0"
"version": "5.4.1"
}
10 changes: 7 additions & 3 deletions src/htmlminifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ import {

import { declinesMinify, processOptions } from './lib/options.js';
import { canScriptFollow, canStyleSheetsJoin, getMergeKey, holdsHashbang, joinScripts, joinStyleSheets } from './lib/merging.js';
import { toFragment, replaceCustomFragments, isMinifiedCodeSafe } from './lib/fragments.js';
import { toFragment, replaceCustomFragments, isMinifiedCSSSafe, isMinifiedJSSafe } from './lib/fragments.js';

/** @import { ProcessedOptions } from './lib/options.js' */

Expand Down Expand Up @@ -1208,11 +1208,15 @@ async function minifyHTML(value, options, partialMarkup) {
return (chunks?.[1] ?? '') + uidAttr + index + uidAttr + (chunks?.[2] ?? '');
});
const result = fn(source, ...args);
const finish = (/** @type {string} */ output) => {
if (isMinifiedCodeSafe(source, output, uidPlaceholderPattern, isJS)) return output;
const settle = (/** @type {string} */ output, /** @type {boolean} */ isSafe) => {
if (isSafe) return output;
options.log('Keeping CSS or JavaScript as written, as minifying could break or lose a custom fragment');
return source;
};
// `args` are the inline and module flags `minifyJS` is called with
const finish = (/** @type {string} */ output) => isJS
? isMinifiedJSSafe(source, output, uidPlaceholderPattern, Boolean(args[0]), Boolean(args[1])).then(isSafe => settle(output, isSafe))
: settle(output, isMinifiedCSSSafe(source, output, uidPlaceholderPattern));
return isThenable(result) ? Promise.resolve(result).then(finish) : finish(result);
};

Expand Down
29 changes: 26 additions & 3 deletions src/lib/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,15 +137,29 @@ function deduplicateAttributes(attrs, caseSensitive) {
return attrs;
}

// Most tags hold a few attributes, which are faster compared with each other than in a set
const keys = attrs.map(attr => caseSensitive ? attr.name : attr.name.toLowerCase());
let hasDuplicates = false;
if (keys.length <= 8) {
for (let i = 1; i < keys.length && !hasDuplicates; i++) {
hasDuplicates = keys.lastIndexOf(/** @type {string} */ (keys[i]), i - 1) !== -1;
}
} else {
hasDuplicates = new Set(keys).size !== keys.length;
}
if (!hasDuplicates) {
return attrs;
}

const seen = new Set();
let writeIndex = 0;

for (const attr of attrs) {
const key = caseSensitive ? attr.name : attr.name.toLowerCase();
for (let i = 0; i < attrs.length; i++) {
const key = keys[i];

if (!seen.has(key)) {
seen.add(key);
attrs[writeIndex++] = attr;
attrs[writeIndex++] = /** @type {HTMLAttribute} */ (attrs[i]);
}
}

Expand Down Expand Up @@ -786,6 +800,15 @@ function dedupeClassNames(value) {
return value;
}
const names = value.split(RE_ATTR_WS_COLLAPSE);
// As with attributes, a short list is faster checked name by name than through a set
if (names.length <= 16) {
for (let i = 1; i < names.length; i++) {
if (names.lastIndexOf(/** @type {string} */ (names[i]), i - 1) !== -1) {
return [...new Set(names)].join(' ');
}
}
return value;
}
const unique = new Set(names);
return unique.size === names.length ? value : [...unique].join(' ');
}
Expand Down
Loading