@ohos-ports/html-minifier-next 8.4.2-beta.0 → 8.10.8-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +147 -33
- package/cli.js +70 -54
- package/dist/types/htmlminifier.d.ts +87 -33
- package/dist/types/htmlminifier.d.ts.map +1 -1
- package/dist/types/htmlparser.d.ts +4 -1
- package/dist/types/htmlparser.d.ts.map +1 -1
- package/dist/types/lib/attributes.d.ts +12 -10
- package/dist/types/lib/attributes.d.ts.map +1 -1
- package/dist/types/lib/constants.d.ts +38 -3
- package/dist/types/lib/constants.d.ts.map +1 -1
- package/dist/types/lib/content.d.ts.map +1 -1
- package/dist/types/lib/elements.d.ts.map +1 -1
- package/dist/types/lib/fragments.d.ts +1 -0
- package/dist/types/lib/fragments.d.ts.map +1 -1
- package/dist/types/lib/option-definitions.d.ts.map +1 -1
- package/dist/types/lib/options.d.ts +14 -46
- package/dist/types/lib/options.d.ts.map +1 -1
- package/dist/types/lib/unused-css.d.ts +34 -4
- package/dist/types/lib/unused-css.d.ts.map +1 -1
- package/dist/types/lib/urls.d.ts.map +1 -1
- package/dist/types/lib/utils.d.ts +31 -1
- package/dist/types/lib/utils.d.ts.map +1 -1
- package/dist/types/lib/whitespace.d.ts +57 -5
- package/dist/types/lib/whitespace.d.ts.map +1 -1
- package/dist/types/presets.d.ts +1 -2
- package/dist/types/presets.d.ts.map +1 -1
- package/dist/types/tokenchain.d.ts.map +1 -1
- package/html-minifier-next.schema.json +15 -7
- package/package.json +17 -18
- package/src/htmlminifier.js +1103 -392
- package/src/htmlparser.js +452 -200
- package/src/lib/attributes.js +201 -112
- package/src/lib/constants.js +130 -19
- package/src/lib/content.js +1 -6
- package/src/lib/elements.js +17 -12
- package/src/lib/file-pool.js +18 -2
- package/src/lib/file-write.js +87 -0
- package/src/lib/fragments.js +74 -8
- package/src/lib/option-definitions.js +17 -10
- package/src/lib/options.js +151 -71
- package/src/lib/unused-css.js +145 -27
- package/src/lib/urls.js +0 -9
- package/src/lib/utils.js +210 -45
- package/src/lib/whitespace.js +173 -63
- package/src/presets.js +1 -2
- package/src/tokenchain.js +1 -4
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
Your web page optimization precision tool: HTML Minifier Next (HMN) is a **highly effective, super-configurable, well-tested HTML minifier**, written in JavaScript, that also handles in-document CSS, JavaScript, and SVG minification.
|
|
6
6
|
|
|
7
|
-
The project was based on [HTML Minifier Terser (HMT)](https://github.com/terser/html-minifier-terser), which in turn had been based on [Juriy “kangax” Zaytsev’s HTML Minifier (HM)](https://github.com/kangax/html-minifier). HMN is **the official successor to HTML Minifier**: It’s actively maintained, richer in features, easier to use, and significantly faster. Note that HMN is largely compatible with HM and HMT but isn’t fully drop-in—find [migration guidance in the changelog](https://github.com/j9t/html-minifier-next/blob/main/CHANGELOG.md).
|
|
7
|
+
The project was based on [HTML Minifier Terser (HMT)](https://github.com/terser/html-minifier-terser), which in turn had been based on [Juriy “kangax” Zaytsev’s HTML Minifier (HM)](https://github.com/kangax/html-minifier). HMN is **the official successor to HTML Minifier**: It’s actively maintained, richer in features, easier to use, and significantly faster ([HMN engineering philosophy](https://meiert.com/blog/html-minifier-next-engineering-philosophy/)). Note that HMN is largely compatible with HM and HMT but isn’t fully drop-in—find [migration guidance in the changelog](https://github.com/j9t/html-minifier-next/blob/main/CHANGELOG.md).
|
|
8
8
|
|
|
9
9
|
## Installation
|
|
10
10
|
|
|
@@ -32,7 +32,7 @@ Use `npx html-minifier-next --help` to check all available options:
|
|
|
32
32
|
|
|
33
33
|
| Option | Description | Example |
|
|
34
34
|
| --- | --- | --- |
|
|
35
|
-
| `--zero`, `-z` | Minify all HTML files in the current folder and its subfolders in place (except node_modules), using comprehensive settings (standalone—flag is ignored when combined with other options) | `npx html-minifier-next --zero` |
|
|
35
|
+
| `--zero`, `-z` | Minify all HTML files in the current folder and its subfolders in place (except node_modules), using comprehensive settings (standalone—the flag is ignored when combined with other options) | `npx html-minifier-next --zero` |
|
|
36
36
|
| `--input-dir <dir>`, `-I <dir>` | Specify an input directory | `--input-dir=src` |
|
|
37
37
|
| `--ignore-dir <patterns>`, `-X <patterns>` | Exclude directories—relative to input directory—from processing (comma-separated, overrides config file setting) | `--ignore-dir=libs`, `--ignore-dir=libs,vendor,node_modules` |
|
|
38
38
|
| `--output-dir <dir>`, `-O <dir>` | Specify an output directory | `--output-dir=dist` |
|
|
@@ -83,6 +83,8 @@ export default {
|
|
|
83
83
|
};
|
|
84
84
|
```
|
|
85
85
|
|
|
86
|
+
A module can also hold values JSON cannot express, like regular expressions (e.g., `ignoreCustomFragments: [/\{\{[\s\S]*?\}\}/]`) and functions (for `minifyCSS`, `minifyJS`, and `minifyURLs`, or in custom SVGO plugins for `minifySVG`). As functions cannot be passed to worker threads, a run using them minifies in-process.
|
|
87
|
+
|
|
86
88
|
### Node.js
|
|
87
89
|
|
|
88
90
|
```js
|
|
@@ -106,7 +108,7 @@ HTML Minifier Next provides presets for common use cases. Presets are pre-config
|
|
|
106
108
|
* `conservative`: Basic minification with whitespace collapsing, comment removal, and removal of select attributes.
|
|
107
109
|
* `comprehensive`: More advanced minification for better file size reduction, including relevant conservative options plus attribute quote removal, optional tag removal, and more.
|
|
108
110
|
|
|
109
|
-
To review the specific options set, [presets.js](https://github.com/j9t/html-minifier-next/blob/main/src/presets.js) lists them in an accessible manner.
|
|
111
|
+
To review the specific options set, [presets.js](https://github.com/j9t/html-minifier-next/blob/main/src/presets.js) lists them in an accessible manner. For output served with Gzip or Brotli, see [“Optimizing for compression”](#optimizing-for-compression) for what to add.
|
|
110
112
|
|
|
111
113
|
**Using presets:**
|
|
112
114
|
|
|
@@ -135,10 +137,12 @@ Options can be used in config files (camelCase) or via CLI flags (kebab-case wit
|
|
|
135
137
|
| `cacheCSS`<br>`--cache-css` | Set CSS minification cache size; higher values improve performance for batch processing | `500` |
|
|
136
138
|
| `cacheJS`<br>`--cache-js` | Set JavaScript minification cache size; higher values improve performance for batch processing | `500` |
|
|
137
139
|
| `cacheSVG`<br>`--cache-svg` | Set SVG minification cache size; higher values improve performance for batch processing | `500` |
|
|
138
|
-
| `caseSensitive`<br>`--case-sensitive` |
|
|
140
|
+
| `caseSensitive`<br>`--case-sensitive` | Keep element and attribute names as written (e.g., for framework components like `<MyButton>`) | `false` |
|
|
139
141
|
| `collapseAttributeWhitespace`<br>`--collapse-attribute-whitespace` | Trim and collapse whitespace characters within attribute values | `false` |
|
|
140
142
|
| `collapseBooleanAttributes`<br>`--collapse-boolean-attributes` | [Omit attribute values from boolean attributes](https://perfectionkills.com/experimenting-with-html-minifier/#collapse_boolean_attributes) | `false` |
|
|
143
|
+
| `collapseEmptyAttributes`<br>`--collapse-empty-attributes` | Omit empty attribute values (e.g., `alt=""` → `alt`) | `false` |
|
|
141
144
|
| `collapseInlineTagWhitespace`<br>`--collapse-inline-tag-whitespace` | Collapse whitespace more aggressively between inline elements—use with [`collapseWhitespace`](#combining-whitespace-options) | `false` |
|
|
145
|
+
| `collapseNoBreakSpaces`<br>`--collapse-no-break-spaces` | Remove whitespace next to no-break spaces, narrow no-break spaces, and figure spaces in text (e.g., `a b` → `a b`), keeping runs of them—use with [`collapseWhitespace`](#combining-whitespace-options) | `false` |
|
|
142
146
|
| `collapseWhitespace`<br>`--collapse-whitespace` | [Collapse whitespace that contributes to text nodes in a document tree](https://perfectionkills.com/experimenting-with-html-minifier/#collapse_whitespace); [enable other whitespace options](#combining-whitespace-options) | `false` |
|
|
143
147
|
| `conservativeCollapse`<br>`--conservative-collapse` | Always collapse to one space (never remove it entirely)—use with [`collapseWhitespace`](#combining-whitespace-options) | `false` |
|
|
144
148
|
| `continueOnMinifyError`<br>`--continue-on-minify-error`<br>`--no-continue-on-minify-error` | Continue on minification errors; when `false`, minification errors throw and abort processing | `true` |
|
|
@@ -149,18 +153,18 @@ Options can be used in config files (camelCase) or via CLI flags (kebab-case wit
|
|
|
149
153
|
| `customEventAttributes`<br>`--custom-event-attributes` | Array of regexes that allow to support custom event attributes (e.g., `ng-click`)—use with `minifyJS` | `[ /^on[a-z]{3,}$/ ]` |
|
|
150
154
|
| `decodeEntities`<br>`--decode-entities` | Use direct Unicode characters whenever possible | `false` |
|
|
151
155
|
| `ignoreCustomComments`<br>`--ignore-custom-comments` | Array of regexes that allow to ignore matching comments | `[ /^!/, /^\s*#/ ]` |
|
|
152
|
-
| `ignoreCustomFragments`<br>`--ignore-custom-fragments` | Array of regexes that allow to ignore certain fragments, when matched (e.g., `<?php … ?>`, `{{ … }}`, etc
|
|
156
|
+
| `ignoreCustomFragments`<br>`--ignore-custom-fragments` | Array of regexes that allow to ignore certain fragments, when matched (e.g., `<?php … ?>`, `{{ … }}`, etc.; see [“Minifying server-side templates”](#minifying-server-side-templates)) | `[ /<%[\s\S]*?%>/, /<\?(?:php[\t\n\r ]\|=\|\$\|xml(?:-stylesheet)?(?![\w-])\|\s)[\s\S]*?\?>/i ]` |
|
|
153
157
|
| `includeAutoGeneratedTags`<br>`--include-auto-generated-tags` | Insert elements generated by HTML parser | `false` |
|
|
154
158
|
| `inlineCustomElements`<br>`--inline-custom-elements` | Array of names of custom elements which are inline, for whitespace handling—use with `collapseWhitespace` | `[]` |
|
|
155
159
|
| `keepClosingSlash`<br>`--keep-closing-slash` | Keep the trailing slash on void elements and other start tags that carry one, and read it as closing the element | `false` |
|
|
156
160
|
| `maxInputLength`<br>`--max-input-length` | Maximum input length to prevent ReDoS attacks (disabled by default) | `undefined` |
|
|
157
|
-
| `maxLineLength`<br>`--max-line-length` | Specify a maximum line length;
|
|
161
|
+
| `maxLineLength`<br>`--max-line-length` | Specify a maximum line length; output will be split by newlines in tags only (between attributes or before a tag’s `>`), where they can’t change the page, so lines may run longer | `undefined` |
|
|
158
162
|
| `mergeScripts`<br>`--merge-scripts` | Merge consecutive inline `script` elements into one (only merges compatible scripts with same `type`, matching `async`/`defer`/`nomodule`/`nonce`) | `false` |
|
|
159
163
|
| `minifyCSS`<br>`--minify-css` | Minify CSS in `style` elements and attributes (uses [Lightning CSS](https://lightningcss.dev/)) | `false` (could be `true`, `Object`, `Function(text, type)`) |
|
|
160
164
|
| `minifyJS`<br>`--minify-js` | Minify JavaScript in `script` elements and event attributes (uses [Terser](https://terser.org/) or [SWC](https://swc.rs/)) | `false` (could be `true`, `Object`, `Function(text, inline)`) |
|
|
161
165
|
| `minifySVG`<br>`--minify-svg` | Minify SVG elements (uses [SVGO](https://svgo.dev/)) | `false` (could be `true`, `Object`) |
|
|
162
166
|
| `minifyURLs`<br>`--minify-urls` | Minify URLs in various attributes | `false` (could be `true`, `String`, `Object`, `Function(text)`) |
|
|
163
|
-
| `noNewlinesBeforeTagClose`<br>`--no-newlines-before-tag-close` | Never
|
|
167
|
+
| `noNewlinesBeforeTagClose`<br>`--no-newlines-before-tag-close` | Never split a line in a tag that closes an element—use with `maxLineLength` | `false` |
|
|
164
168
|
| `partialMarkup`<br>`--partial-markup` | Treat input as a partial HTML fragment, preserving stray end tags (closing tags without opening tags) and preventing auto-closing of unclosed tags at end of input | `false` |
|
|
165
169
|
| `preserveLineBreaks`<br>`--preserve-line-breaks` | Always collapse to one line break (never remove it entirely) when whitespace between tags includes a line break—use with [`collapseWhitespace`](#combining-whitespace-options) | `false` |
|
|
166
170
|
| `preventAttributesEscaping`<br>`--prevent-attributes-escaping` | Prevents the escaping of the values of attributes | `false` |
|
|
@@ -170,16 +174,16 @@ Options can be used in config files (camelCase) or via CLI flags (kebab-case wit
|
|
|
170
174
|
| `removeComments`<br>`--remove-comments` | [Strip HTML comments](https://perfectionkills.com/experimenting-with-html-minifier/#remove_comments) | `false` |
|
|
171
175
|
| `removeDefaultTypeAttributes`<br>`--remove-default-type-attributes` | Remove default `type` attributes from `style`/`link` (e.g., `type="text/css"`) and `script` (e.g., `type="text/javascript"`) elements; other `type` attribute values are left intact | `false` |
|
|
172
176
|
| `removeEmptyAttributes`<br>`--remove-empty-attributes` | [Remove all attributes with whitespace-only values](https://perfectionkills.com/experimenting-with-html-minifier/#remove_empty_or_blank_attributes) | `false` (could be `true`, `Function(attrName, tag)`) |
|
|
173
|
-
| `removeEmptyElements`<br>`--remove-empty-elements` | [Remove all elements with empty contents](
|
|
174
|
-
| `removeEmptyElementsExcept`<br>`--remove-empty-elements-except` | Array of elements to preserve—use with `removeEmptyElements`; accepts simple tag names (e.g., `["td"]`) or HTML-like markup with attributes (e.g., `["<
|
|
177
|
+
| `removeEmptyElements`<br>`--remove-empty-elements` | [Remove all elements with empty contents](#removing-empty-elements) | `false` |
|
|
178
|
+
| `removeEmptyElementsExcept`<br>`--remove-empty-elements-except` | Array of elements to preserve—use with `removeEmptyElements`; accepts simple tag names (e.g., `["td"]`) or HTML-like markup with attributes (e.g., `["<i class='test'>"]`); supports double quotes, single quotes, and unquoted attribute values | `[]` |
|
|
175
179
|
| `removeOptionalTags`<br>`--remove-optional-tags` | [Remove optional tags](https://perfectionkills.com/experimenting-with-html-minifier/#remove_optional_tags) | `false` |
|
|
176
180
|
| `removeRedundantAttributes`<br>`--remove-redundant-attributes` | [Remove attributes when value matches default](https://meiert.com/blog/optional-html/#toc-attribute-values) | `false` |
|
|
177
181
|
| `removeTagWhitespace`<br>`--remove-tag-whitespace` | Remove space between attributes whenever possible; **note that this will result in invalid HTML** | `false` |
|
|
178
|
-
| `removeUnusedCSS`<br>`--remove-unused-css` | [Remove
|
|
182
|
+
| `removeUnusedCSS`<br>`--remove-unused-css` | [Remove CSS from `style` elements](#unused-css-removal) that name an element, class, or ID the document doesn’t reference—use with `minifyCSS`, and `safelist` for names only external scripts use | `false` (could be `true`, `{ safelist, scripts }`) |
|
|
179
183
|
| `sortAttributes`<br>`--sort-attributes` | [Sort attributes by frequency](#sorting-attributes-and-style-classes) | `false` |
|
|
180
184
|
| `sortClassNames`<br>`--sort-class-names` | [Sort style classes by frequency](#sorting-attributes-and-style-classes) | `false` |
|
|
181
185
|
| `strictCustomFragments`<br>`--strict-custom-fragments` | [Reject `ignoreCustomFragments` patterns that risk catastrophic backtracking](#redos-protection) (rather than warning about them) | `false` |
|
|
182
|
-
| `trimCustomFragments`<br>`--trim-custom-fragments` | Trim whitespace around custom fragments (`ignoreCustomFragments`)—use with `collapseWhitespace` | `false` |
|
|
186
|
+
| `trimCustomFragments`<br>`--trim-custom-fragments` | Trim whitespace around custom fragments (`ignoreCustomFragments`) where it does not affect the output (see [“Minifying server-side templates”](#minifying-server-side-templates))—use with `collapseWhitespace` | `false` |
|
|
183
187
|
| `useShortDoctype`<br>`--use-short-doctype` | [Replaces the doctype with the short HTML doctype](https://perfectionkills.com/experimenting-with-html-minifier/#use_short_doctype) | `false` |
|
|
184
188
|
|
|
185
189
|
### API-only options
|
|
@@ -188,9 +192,12 @@ A few options take functions and are therefore only available programmatically,
|
|
|
188
192
|
|
|
189
193
|
| Option | Description | Default |
|
|
190
194
|
| --- | --- | --- |
|
|
191
|
-
| `canCollapseWhitespace` | `Function(tag, attrs, defaultFn)` that determines whether whitespace inside an element can be collapsed—override to protect additional elements, delegating to `defaultFn` for the rest | Built-in handling (protects `pre`, `textarea`, etc.) |
|
|
192
|
-
| `
|
|
193
|
-
| `
|
|
195
|
+
| `canCollapseWhitespace` | `Function(tag, attrs, defaultFn)` that determines whether runs of whitespace inside an element can be collapsed (whether its content may be trimmed is up to `canTrimWhitespace`)—override to protect additional elements, delegating to `defaultFn` for the rest | Built-in handling (protects `pre`, `textarea`, etc.) |
|
|
196
|
+
| `canMinifyCSS` | Synchronous `Function(text, type)` that determines whether `minifyCSS` may process a given piece of CSS—returning `false` [leaves it as if `minifyCSS` were off](#css-minification) | All CSS is minified |
|
|
197
|
+
| `canMinifyJS` | Synchronous `Function(text, inline)` that determines whether `minifyJS` may process a given piece of JavaScript—returning `false` [leaves it unminified](#javascript-minification) | All JavaScript is minified |
|
|
198
|
+
| `canMinifySVG` | Synchronous `Function(text)` that determines whether `minifySVG` may pass a given outermost `svg` element to SVGO—returning `false` [skips SVGO for it](#svg-minification) | All SVG is minified |
|
|
199
|
+
| `canTrimWhitespace` | `Function(tag, attrs, defaultFn)` that determines whether whitespace inside an element may be trimmed; where not, it stays as written, as in `pre` | Built-in handling (protects `pre`, `textarea`, etc.) |
|
|
200
|
+
| `log` | `Function(message)` called with warnings and errors, including minification errors (`continueOnMinifyError`) and parse errors (`continueOnParseError`); the CLI wires this up under `--verbose` and `--dry` | No-op (errors are silent) |
|
|
194
201
|
|
|
195
202
|
### Options that rely on another option
|
|
196
203
|
|
|
@@ -202,7 +209,11 @@ HTML Minifier Next: Ignoring `conservativeCollapse`—use with `collapseWhitespa
|
|
|
202
209
|
|
|
203
210
|
| Option | Needs |
|
|
204
211
|
| --- | --- |
|
|
212
|
+
| `canMinifyCSS` | `minifyCSS`, and not [a function of your own](#css-minification) |
|
|
213
|
+
| `canMinifyJS` | `minifyJS`, and not [a function of your own](#javascript-minification) |
|
|
214
|
+
| `canMinifySVG` | `minifySVG`, and not [a function of your own](#svg-minification) |
|
|
205
215
|
| `collapseInlineTagWhitespace` | `collapseWhitespace` |
|
|
216
|
+
| `collapseNoBreakSpaces` | `collapseWhitespace` |
|
|
206
217
|
| `conservativeCollapse` | `collapseWhitespace` |
|
|
207
218
|
| `customEventAttributes` | `minifyJS` |
|
|
208
219
|
| `inlineCustomElements` | `collapseWhitespace` |
|
|
@@ -212,11 +223,11 @@ HTML Minifier Next: Ignoring `conservativeCollapse`—use with `collapseWhitespa
|
|
|
212
223
|
| `removeUnusedCSS` | `minifyCSS`, and not [a function of your own](#unused-css-removal) |
|
|
213
224
|
| `trimCustomFragments` | `collapseWhitespace` |
|
|
214
225
|
|
|
215
|
-
Passing the option `false`, or an empty array, asks for nothing and is not reported. `cacheCSS`, `cacheJS`, and `cacheSVG` are not
|
|
226
|
+
Passing the option `false`, or an empty array, asks for nothing and is not reported. `cacheCSS`, `cacheJS`, and `cacheSVG` are not included because they size a cache rather than transform markup, and therefore don’t change output.
|
|
216
227
|
|
|
217
228
|
### Combining whitespace options
|
|
218
229
|
|
|
219
|
-
`collapseInlineTagWhitespace`, `conservativeCollapse`, and `preserveLineBreaks` are modifiers: They do nothing on their own, and only take effect when `collapseWhitespace` is enabled.
|
|
230
|
+
`collapseInlineTagWhitespace`, `collapseNoBreakSpaces`, `conservativeCollapse`, and `preserveLineBreaks` are modifiers: They do nothing on their own, and only take effect when `collapseWhitespace` is enabled.
|
|
220
231
|
|
|
221
232
|
Given input
|
|
222
233
|
|
|
@@ -237,11 +248,53 @@ you get the following output (condensed, `\n` represents an actual line break):
|
|
|
237
248
|
| `collapseWhitespace`, `preserveLineBreaks` | `<nav>\n<button>A</button> <button>B</button>\n</nav>` |
|
|
238
249
|
| `collapseWhitespace`, `preserveLineBreaks`, `collapseInlineTagWhitespace` | `<nav>\n<button>A</button><button>B</button>\n</nav>` |
|
|
239
250
|
|
|
251
|
+
`collapseInlineTagWhitespace` only removes whitespace between tags, and keeps it around text-level elements (like `a`, `code`, or `em`), where it separates words: `<p><button>A</button> <button>B</button> or <code>C</code> <code>D</code></p>` becomes `<p><button>A</button><button>B</button> or <code>C</code> <code>D</code></p>`.
|
|
252
|
+
|
|
240
253
|
Where the modifiers disagree, the preserving one wins—`conservativeCollapse` and `preserveLineBreaks` do not let `collapseInlineTagWhitespace` remove a space or line break entirely.
|
|
241
254
|
|
|
255
|
+
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.
|
|
256
|
+
|
|
242
257
|
### Sorting attributes and style classes
|
|
243
258
|
|
|
244
|
-
|
|
259
|
+
`sortAttributes` and `sortClassNames` reorder attributes and class names by frequency, so that repeated markup looks more alike. This doesn’t change the plain-text size of the output, only how well it compresses: `sortAttributes` makes Gzip and Brotli output slightly smaller on average, though not on every page (see [“Optimizing for compression”](#optimizing-for-compression)); `sortClassNames` doesn’t help, and alongside `sortAttributes` cancels most of its gain with Brotli.
|
|
260
|
+
|
|
261
|
+
### Optimizing for compression
|
|
262
|
+
|
|
263
|
+
Most HTML is served compressed, so the Gzip or Brotli size is often what counts—and it doesn’t always follow the raw size. Added to the `comprehensive` preset, these options changed output size as follows (average per page, relative to `comprehensive`):
|
|
264
|
+
|
|
265
|
+
| Added to `comprehensive` | Raw | Gzip (level 6) | Brotli (quality 6) | Brotli (quality 11) |
|
|
266
|
+
| --- | --- | --- | --- | --- |
|
|
267
|
+
| `sortAttributes` | ±0% | −0.10% | −0.11% | −0.07% |
|
|
268
|
+
| `sortAttributes`, `removeAttributeQuotes: false`, `quoteCharacter: '"'` | +1.68% | +0.20% | −0.02% | −0.30% |
|
|
269
|
+
| `removeEmptyElements` | −1.37% | −0.76% | −0.65% | −0.66% |
|
|
270
|
+
|
|
271
|
+
* **Gzip or on-the-fly Brotli:** Add `sortAttributes`. The gain is small and uneven, however, and sorting can double minification time for very large documents.
|
|
272
|
+
* **Brotli precompressed at quality 11** (as for static files compressed at build time): Add `sortAttributes`, don’t remove attribute quotes, and make the quotes double quotes. Raw and Gzip output grow, so this only pays off when clients receive the precompressed Brotli files.
|
|
273
|
+
* **`removeEmptyElements`** saves more than either, but may change the respective document—see [“Removing empty elements”](#removing-empty-elements) before enabling it.
|
|
274
|
+
|
|
275
|
+
```shell
|
|
276
|
+
# Gzip or on-the-fly Brotli
|
|
277
|
+
npx html-minifier-next --preset comprehensive --sort-attributes input.html
|
|
278
|
+
|
|
279
|
+
# Brotli precompressed at quality 11
|
|
280
|
+
npx html-minifier-next --preset comprehensive --sort-attributes --no-remove-attribute-quotes --quote-character='"' input.html
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
These figures were measured in October 2026 with HMN 8.8.1 on 61 pages of the [backtest corpus](#regression-tests) (retrieved February and September 2026). They are indications, not guarantees, as they depend on the markup and will shift as HMN and the minifiers it bundles change. The [benchmark](#working-tree-benchmarks) reports Gzip and Brotli (quality 6) sizes to re-check them.
|
|
284
|
+
|
|
285
|
+
### Removing empty elements
|
|
286
|
+
|
|
287
|
+
`removeEmptyElements` removes elements without content—no text and no child elements (comments don’t count; whitespace does, unless `collapseWhitespace` removes it). It keeps:
|
|
288
|
+
|
|
289
|
+
* elements with an `id` attribute,
|
|
290
|
+
* elements with a `role`, `tabindex`, or ARIA attribute (e.g., `aria-label` or `aria-hidden`), and `label`, `output`, and `template` elements with a `for` attribute (e.g., a `label` styled as a menu toggle), unless its value is empty,
|
|
291
|
+
* custom elements (e.g., `<my-player></my-player>`), `canvas`, and `textarea` elements,
|
|
292
|
+
* `audio`, `video`, and `script` elements with a `src` attribute, `iframe` elements with `src` or `srcdoc`, `object` elements with `data`, and `applet` elements with `code`,
|
|
293
|
+
* elements inside SVG and MathML—though an empty `svg` or `math` element itself is removed, and HTML inside them (as in `foreignObject` or `annotation-xml`) is still processed.
|
|
294
|
+
|
|
295
|
+
Everything else goes, including elements that are empty on purpose: icons and other elements styled with CSS (e.g., `<i class="test"></i>` or `<span style="width:50%"></span>`), named anchors (`<a name="top"></a>`), other elements that scripts fill, empty `option` elements, and empty table cells (which shifts the cells that follow). Keep such elements with `removeEmptyElementsExcept`, for example `["td", "<i class='test'>"]`. A parent that is left empty by the removal goes, too, unless the above keeps it.
|
|
296
|
+
|
|
297
|
+
Where the markup allows it, the option is effective: On a test corpus, it reduced output by 1.37% raw and 0.76% with Gzip on average (see [“Optimizing for compression”](#optimizing-for-compression)).
|
|
245
298
|
|
|
246
299
|
### CSS minification
|
|
247
300
|
|
|
@@ -282,9 +335,18 @@ const result = await minify(html, {
|
|
|
282
335
|
});
|
|
283
336
|
```
|
|
284
337
|
|
|
338
|
+
To exempt individual pieces of CSS, pass `canMinifyCSS` a synchronous function. It receives the CSS and its type—`undefined` for `style` elements, `'inline'` for `style` attributes, and `'media'` for `media` attributes. CSS for which it returns `false` comes out as if `minifyCSS` were off, so its URLs are not minified and its unused rules not removed, either. (Within `svg` elements, `minifySVG` has SVGO minify CSS as well—exempt those with [`canMinifySVG`](#svg-minification).)
|
|
339
|
+
|
|
340
|
+
```js
|
|
341
|
+
const result = await minify(html, {
|
|
342
|
+
minifyCSS: true,
|
|
343
|
+
canMinifyCSS: text => !text.includes('/* keep */')
|
|
344
|
+
});
|
|
345
|
+
```
|
|
346
|
+
|
|
285
347
|
### Unused CSS removal
|
|
286
348
|
|
|
287
|
-
`removeUnusedCSS` removes
|
|
349
|
+
`removeUnusedCSS` removes selectors from `style` elements that name an element, class, or ID the document doesn’t reference, as well as rules that are left without selectors. In `.used, .unused { … }`, only `.unused` goes. It needs to be used with `minifyCSS`, because the removal runs through Lightning CSS—passing `minifyCSS` a function of your own replaces that step, so the removal does not apply, either. Both cases are reported through [the `log` hook](#api-only-options). It doesn’t touch `style` or `media` attributes.
|
|
288
350
|
|
|
289
351
|
```js
|
|
290
352
|
const result = await minify(html, {
|
|
@@ -293,7 +355,9 @@ const result = await minify(html, {
|
|
|
293
355
|
});
|
|
294
356
|
```
|
|
295
357
|
|
|
296
|
-
|
|
358
|
+
Elements are considered used when the markup contains them (`html`, `head`, and `body` always count, as do `tbody` and `tr` in tables, and `colgroup` with `col`) or when their name appears inside an inline `script` element, unless `scripts` is set to `false`. An element doesn’t count as a reference to a class of the same name, nor the other way around.
|
|
359
|
+
|
|
360
|
+
Classes and IDs are considered used when they appear
|
|
297
361
|
|
|
298
362
|
* in a `class` or `id` attribute,
|
|
299
363
|
* in an attribute that references an ID (`for`, `headers`, `list`, `popovertarget`, `aria-controls`, and similar),
|
|
@@ -301,15 +365,17 @@ Symbols are considered used when they appear
|
|
|
301
365
|
* anywhere in a `data-*` attribute value, or
|
|
302
366
|
* anywhere inside an inline `script` element, unless `scripts` is set to `false`.
|
|
303
367
|
|
|
368
|
+
Only a selector’s own compounds are judged: Names inside pseudo-classes and pseudo-elements, as in `:not(.unused)`, `:has(.unused)`, or `:host(.unused)`, keep their selector. Style sheets containing `@scope`—and all of them when [`minifyCSS` carries a Lightning CSS `visitor`](#css-minification) of your own—keep their selector lists whole and only lose rules whose selectors all go.
|
|
369
|
+
|
|
304
370
|
Names carrying characters that end a CSS identifier—`md:flex`, `w-1/2`, `p-[3px]`—are matched as whole tokens, so utility-CSS class names survive whether they come from markup, a `data-*` value, or a string in an inline script.
|
|
305
371
|
|
|
306
|
-
**
|
|
372
|
+
**Elements, classes, and IDs that only appear in external scripts cannot be detected.** A minifier sees one document, not the DOM that scripts later build from it, so a `dialog` that, say, a bundle.js creates, or a class it adds, looks exactly like one nobody uses. List those under `safelist`, as strings or regular expressions:
|
|
307
373
|
|
|
308
374
|
```js
|
|
309
375
|
const result = await minify(html, {
|
|
310
376
|
minifyCSS: true,
|
|
311
377
|
removeUnusedCSS: {
|
|
312
|
-
safelist: ['is-open', /^js
|
|
378
|
+
safelist: ['is-open', /^js-/, 'dialog'],
|
|
313
379
|
// Set to `false` to also drop rules only referenced from inline scripts
|
|
314
380
|
scripts: true
|
|
315
381
|
}
|
|
@@ -382,17 +448,28 @@ const result = await minify(html, {
|
|
|
382
448
|
});
|
|
383
449
|
```
|
|
384
450
|
|
|
451
|
+
To exempt individual pieces of JavaScript, pass `canMinifyJS` a synchronous function. It receives the JavaScript and whether it is inline—`true` for event handler attributes (e.g., `onclick`), `false` for `script` elements. JavaScript for which it returns `false` is left unminified, though `mergeScripts` still merges it with adjacent scripts:
|
|
452
|
+
|
|
453
|
+
```js
|
|
454
|
+
const result = await minify(html, {
|
|
455
|
+
minifyJS: true,
|
|
456
|
+
canMinifyJS: text => !text.includes('/* keep */')
|
|
457
|
+
});
|
|
458
|
+
```
|
|
459
|
+
|
|
385
460
|
### SVG minification
|
|
386
461
|
|
|
387
462
|
When `minifySVG` is set to `true`, HTML Minifier Next uses [SVGO](https://svgo.dev/) to optimize inline SVG elements. Complete `<svg>` subtrees are extracted and processed as a block, enabling deep structural optimization:
|
|
388
463
|
|
|
389
464
|
```js
|
|
390
465
|
const result = await minify(html, {
|
|
391
|
-
minifySVG: true // Enable with SVGO defaults
|
|
466
|
+
minifySVG: true // Enable with SVGO defaults fit for inline SVG
|
|
392
467
|
});
|
|
393
468
|
```
|
|
394
469
|
|
|
395
|
-
|
|
470
|
+
Unlike an SVG file, an inline SVG is part of the page. HMN runs SVGO’s `preset-default` with the plugins that assume a standalone file turned off (see overrides below). `style` elements in SVG are minified through `minifyCSS` and SVGO.
|
|
471
|
+
|
|
472
|
+
You can pass custom SVGO options. Options without `plugins` (e.g., `{ floatPrecision: 2 }`) keep HMN’s plugin set; options with `plugins` replace it, so include the overrides for inline SVG unless the SVGs don’t depend on the rest of the page:
|
|
396
473
|
|
|
397
474
|
```js
|
|
398
475
|
const result = await minify(html, {
|
|
@@ -401,6 +478,14 @@ const result = await minify(html, {
|
|
|
401
478
|
name: 'preset-default',
|
|
402
479
|
params: {
|
|
403
480
|
overrides: {
|
|
481
|
+
// Inline SVG
|
|
482
|
+
cleanupIds: false, // IDs may be referenced from the page (links, CSS, other SVGs)
|
|
483
|
+
inlineStyles: false, // `style` rules may target elements outside the SVG
|
|
484
|
+
minifyStyles: { usage: false }, // Keep rules the SVG itself doesn’t use
|
|
485
|
+
removeEmptyAttrs: false, // Empty attributes may be hooks (`[data-v-…]`) or meaningful (`alt=""`)
|
|
486
|
+
removeHiddenElems: false, // Hidden sprites are used from other SVGs
|
|
487
|
+
removeUnknownsAndDefaults: { keepRoleAttr: true }, // `role` matters for accessibility
|
|
488
|
+
// Custom
|
|
404
489
|
convertShapeToPath: false // Keep original shapes
|
|
405
490
|
}
|
|
406
491
|
}
|
|
@@ -409,10 +494,19 @@ const result = await minify(html, {
|
|
|
409
494
|
});
|
|
410
495
|
```
|
|
411
496
|
|
|
497
|
+
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.
|
|
498
|
+
|
|
499
|
+
```js
|
|
500
|
+
const result = await minify(html, {
|
|
501
|
+
minifySVG: true,
|
|
502
|
+
canMinifySVG: text => !text.includes('data-keep')
|
|
503
|
+
});
|
|
504
|
+
```
|
|
505
|
+
|
|
412
506
|
**Important:**
|
|
413
507
|
|
|
414
508
|
* SVG minification only applies within `<svg>` elements
|
|
415
|
-
* Case sensitivity and self-closing slashes are automatically preserved in SVG (regardless of global settings)
|
|
509
|
+
* Case sensitivity and self-closing slashes are automatically preserved in SVG (regardless of global settings); where SVGO reads, names are written the way HTML reads them (e.g., `viewbox` as `viewBox`), and attributes without a value get an empty one (e.g., Vue’s `data-v-…` markers), which `collapseEmptyAttributes` removes again after SVGO
|
|
416
510
|
* For maximum compression, use `minifySVG` together with `collapseWhitespace` and other options
|
|
417
511
|
|
|
418
512
|
### CSS, JavaScript, and SVG cache configuration
|
|
@@ -422,12 +516,11 @@ HTML Minifier Next uses in-memory caches to improve performance when processing
|
|
|
422
516
|
```js
|
|
423
517
|
const result = await minify(html, {
|
|
424
518
|
minifyCSS: true,
|
|
519
|
+
cacheCSS: 750, // CSS cache size, default: 500
|
|
425
520
|
minifyJS: true,
|
|
521
|
+
cacheJS: 250, // JS cache size, default: 500
|
|
426
522
|
minifySVG: true,
|
|
427
|
-
//
|
|
428
|
-
cacheCSS: 750, // CSS cache size, default: 500
|
|
429
|
-
cacheJS: 250, // JS cache size, default: 500
|
|
430
|
-
cacheSVG: 100 // SVG cache size, default: 500
|
|
523
|
+
cacheSVG: 100 // SVG cache size, default: 500
|
|
431
524
|
});
|
|
432
525
|
```
|
|
433
526
|
|
|
@@ -595,10 +688,28 @@ By default, HMN parses markup into a complete tree structure, then modifies it (
|
|
|
595
688
|
|
|
596
689
|
_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>`)_
|
|
597
690
|
|
|
598
|
-
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 (closing tags without corresponding opening 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.
|
|
691
|
+
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 (closing tags without corresponding opening 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. 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).
|
|
692
|
+
|
|
693
|
+
Markup with [parse errors](https://html.spec.whatwg.org/multipage/parsing.html#parse-errors) that HMN 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`, HMN handles such errors the way browsers do instead.
|
|
694
|
+
|
|
695
|
+
[Processing instructions](https://html.spec.whatwg.org/multipage/syntax.html#processing-instructions), like the `<?start name="…">`, `<?end>`, and `<?marker name="…">` that [`<template for>`](https://html.spec.whatwg.org/multipage/scripting.html#attr-template-for) targets, are kept as written: `removeComments` leaves them alone, and an element holding one counts as not empty. As content may be inserted at them, whitespace next to them is collapsed but kept next to text. `ignoreCustomFragments` takes precedence. What starts like one but isn’t, like `<?xml …>` or `<? …>`, is a bogus comment, which `continueOnParseError` keeps as written (unless `removeComments` removes it).
|
|
599
696
|
|
|
600
697
|
To validate complete HTML markup, use [the W3C validator](https://validator.w3.org/) or one of [several validator packages](https://meiert.com/blog/html-validator-packages/).
|
|
601
698
|
|
|
699
|
+
### Doctypes and quirks mode
|
|
700
|
+
|
|
701
|
+
Where browsers parse markup differently by document mode, HMN follows the doctype [as the HTML parser does](https://html.spec.whatwg.org/multipage/parsing.html#the-initial-insertion-mode): Under a doctype that sets quirks mode, like HTML 3.2 or HTML 4.01 Transitional without a system identifier, a `table` doesn’t close an open `p`, while under the HTML doctype and legacy doctypes that set no-quirks or limited-quirks mode, like XHTML 1.0 Strict or HTML 4.01 Strict, it does.
|
|
702
|
+
|
|
703
|
+
Only the first doctype counts, and only after nothing but comments and whitespace, as browsers ignore any other. Without such a doctype, the mode is unknown: The markup may be a fragment of a document in either mode, or a complete document, which renders in quirks mode—and text before the doctype, like template code (e.g., `<?php … ?>`), may render to nothing or to text that makes browsers ignore the doctype. HMN then keeps what either mode needs where the two differ—a `</p>` before a `table`, or after a `table` inside a `p`. `useShortDoctype` replaces the doctype with the HTML one, so where the doctype counts, markup is then read as no-quirks, which is how browsers will parse the output.
|
|
704
|
+
|
|
705
|
+
### Minifying server-side templates
|
|
706
|
+
|
|
707
|
+
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`.
|
|
708
|
+
|
|
709
|
+
Whitespace next to template blocks is collapsed but kept, as it may matter once the template renders. `trimCustomFragments` removes it where HTML Minifier Next 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.
|
|
710
|
+
|
|
711
|
+
Where pages are rendered ahead of serving, as with static exports or full-page caches, you can also minify the rendered HTML instead, which makes this a non-issue.
|
|
712
|
+
|
|
602
713
|
### Regex options and flags
|
|
603
714
|
|
|
604
715
|
`customAttrAssign` and `customAttrSurround` patterns are merged into one attribute pattern which carries no flags of its own. `i` and `s` are written into each pattern’s source instead, so they survive the merge. `u`, `v`, and `m` cannot be, and none of them fails loudly when dropped: `u` and `v` only narrow what syntax is legal, so a source valid under either stays valid without it and quietly matches something else—a dropped `u` leaves `\p{L}` matching the literal text `p{L}`—while a dropped `m` leaves `^` and `$` matching at the ends of the input rather than of each line.
|
|
@@ -720,7 +831,7 @@ npm i;
|
|
|
720
831
|
npm run backtest
|
|
721
832
|
```
|
|
722
833
|
|
|
723
|
-
The backtest tool tracks minification performance across Git history. Results are saved in the backtest folder
|
|
834
|
+
The backtest tool tracks minification performance—output size (raw, Gzip, and Brotli) and processing time—across Git history. Results are saved in the backtest folder (results.json).
|
|
724
835
|
|
|
725
836
|
Parameters:
|
|
726
837
|
|
|
@@ -738,7 +849,7 @@ npm i;
|
|
|
738
849
|
npm run benchmark
|
|
739
850
|
```
|
|
740
851
|
|
|
741
|
-
It reuses the backtest corpus (run `npm run backtest` once to download it) and reports per-file output size and processing time.
|
|
852
|
+
It reuses the backtest corpus (run `npm run backtest` once to download it) and reports per-file output size and processing time. Sizes are given raw and compressed—at common defaults for on-the-fly compression, i.e., Gzip at level 6 and Brotli at quality 6—since a change that shrinks raw output can still grow what is transferred.
|
|
742
853
|
|
|
743
854
|
Parameters:
|
|
744
855
|
|
|
@@ -747,10 +858,13 @@ Parameters:
|
|
|
747
858
|
* `--core`: Disables the external minifiers (CSS, JS, SVG, URLs) to isolate HMN’s processing time
|
|
748
859
|
* `--cold`: Switches the minification caches off so CSS, JS, and SVG work is redone on every iteration—without it, warm caches serve those results from memory after the warm-up run and the benchmark cannot see changes to those minifiers
|
|
749
860
|
* `--iterations=N`: Sets the number of timed iterations (default: 5)
|
|
750
|
-
* `--config=PATH`: Uses an alternative options file (default: html-minifier-next.config.json)
|
|
861
|
+
* `--config=PATH`: Uses an alternative options file (default: html-minifier-next.config.json); the file can name a `preset` to start from
|
|
862
|
+
* `--preset=NAME`: Uses a preset instead of an options file (e.g., `--preset=comprehensive`)
|
|
751
863
|
|
|
752
864
|
To compare branches (A/B run), execute `npm run benchmark -- --save` on `main`, then `npm run benchmark` on the branch to see the deltas. Add `--core` on both ends when measuring changes to HMN rather than bundled minifiers, or `--cold` when measuring changes to the CSS, JS, or SVG minification paths.
|
|
753
865
|
|
|
866
|
+
For changes of around 1% or less, use `npm run benchmark:ab -- main` instead: It times the working tree against any Git ref in the same session, runs both in turn per file, averages both loading orders, and reports `collapseWhitespace` on and off separately. Add `--aa` to compare the ref with a copy of itself—the noise floor any finding must clear. The script’s header lists further parameters.
|
|
867
|
+
|
|
754
868
|
Reported times are the *fastest* iteration, not the median: Interference can only make a run slower, so the minimum is the most stable estimate. Each run also reports its noise—how far the reported figure moves between the first and second half of the iterations—and any delta smaller than that is marked `within noise` rather than shown as a win or a regression. Raise `--iterations` until the noise sits below the change you are trying to measure.
|
|
755
869
|
|
|
756
870
|
#### Profiling
|
|
@@ -765,7 +879,7 @@ This writes a .cpuprofile file to the working directory. Load it with `npx speed
|
|
|
765
879
|
|
|
766
880
|
## Acknowledgements
|
|
767
881
|
|
|
768
|
-
With many thanks to the previous authors of and contributors to HTML Minifier, especially [Juriy “kangax” Zaytsev](https://github.com/kangax), and to everyone who helped make this new edition better, particularly [Daniel Ruf](https://github.com/DanielRuf), [Jonas Geiler](https://github.com/jonasgeiler),
|
|
882
|
+
With many thanks to the previous authors of and contributors to HTML Minifier, especially [Juriy “kangax” Zaytsev](https://github.com/kangax), and to everyone who helped make this new edition better, particularly [Daniel Ruf](https://github.com/DanielRuf), [Jonas Geiler](https://github.com/jonasgeiler), [Chris Morgan](https://github.com/chris-morgan), and [Andreas Borutta](https://github.com/fermiongithub)!
|
|
769
883
|
|
|
770
884
|
***
|
|
771
885
|
|