html-minifier
- Version 5.4.2
- Published
- 754 kB
- 6 dependencies
- MIT license
Install
npm i html-minifieryarn add html-minifierpnpm add html-minifierOverview
Highly effective, super-configurable, well-tested web page minifier
Index
Variables
Functions
Type Aliases
Variables
variable _default
const _default: { minify: typeof minify; presets: { conservative: { caseSensitive: boolean; collapseBooleanAttributes: boolean; collapseWhitespace: boolean; conservativeCollapse: boolean; preserveLineBreaks: boolean; removeComments: boolean; removeDefaultTypeAttributes: boolean; }; comprehensive: { collapseAttributeWhitespace: boolean; collapseBooleanAttributes: boolean; collapseEmptyAttributes: boolean; collapseWhitespace: boolean; decodeEntities: boolean; mergeScripts: boolean; mergeStyles: boolean; minifyCSS: boolean; minifyJS: boolean; minifyJSON: boolean; minifySVG: boolean; minifyURLs: boolean; removeAttributeQuotes: boolean; removeComments: boolean; removeDefaultTypeAttributes: boolean; removeEmptyAttributes: boolean; removeOptionalTags: boolean; removeRedundantAttributes: boolean; selfCloseForeignElements: boolean; useShortDoctype: boolean; }; }; getPreset: typeof getPreset; getPresetNames: typeof getPresetNames; getCacheStats: typeof getCacheStats;};variable presets
const presets: { conservative: { caseSensitive: boolean; collapseBooleanAttributes: boolean; collapseWhitespace: boolean; conservativeCollapse: boolean; preserveLineBreaks: boolean; removeComments: boolean; removeDefaultTypeAttributes: boolean; }; comprehensive: { collapseAttributeWhitespace: boolean; collapseBooleanAttributes: boolean; collapseEmptyAttributes: boolean; collapseWhitespace: boolean; decodeEntities: boolean; mergeScripts: boolean; mergeStyles: boolean; minifyCSS: boolean; minifyJS: boolean; minifyJSON: boolean; minifySVG: boolean; minifyURLs: boolean; removeAttributeQuotes: boolean; removeComments: boolean; removeDefaultTypeAttributes: boolean; removeEmptyAttributes: boolean; removeOptionalTags: boolean; removeRedundantAttributes: boolean; selfCloseForeignElements: boolean; useShortDoctype: boolean; };};Preset configurations
Presets provide curated option sets for common use cases: -
conservative: Safe minification suitable for most projects -comprehensive: Aggressive minification for maximum file size reduction
Functions
function getCacheStats
getCacheStats: () => { css: CacheStats; js: CacheStats; svg: CacheStats };Get hit/miss statistics for the CSS, JavaScript, and SVG minification caches.
Each cache is created lazily on the first
minify()call (seeinitCaches); before that first call, or for a cache never exercised (e.g.,minifyCSSdisabled), its entry reports all-zero stats.Returns
{{ css: CacheStats, js: CacheStats, svg: CacheStats }}
function getPreset
getPreset: (name: string) => object | null;Parameter name
Preset name (“conservative” or “comprehensive”)
Returns
{object|null} Preset options object or null if not found
function getPresetNames
getPresetNames: () => string[];Returns
{string[]} Array of preset names
function minify
minify: (value: string, options?: MinifierOptions) => Promise<string>;Parameter value
Parameter options
Returns
{Promise}
Type Aliases
type CacheStats
type CacheStats = { /** * Number of lookups attempted against the cache. */ gets: number; /** * Number of lookups that found a cached entry. */ hits: number; /** * Number of entries currently held in the cache. */ size: number; /** * Maximum number of entries the cache can hold. */ limit: number;};type HTMLAttribute
type HTMLAttribute = { name: string; value?: string; quote?: string; customAssign?: string; customOpen?: string; customClose?: string;};type MergeRecord
type MergeRecord = { kind: 'script' | 'style'; /** * - Index of the start tag’s first entry */ start: number; /** * - Index of the first content entry */ content: number; /** * - Index of the end tag */ end: number; /** * - What its attributes make of it (`null` to keep it apart) */ key: string | null; /** * - For style sheets, the last CSS of its run that isn’t blank, once parsed */ tail: string; /** * - For style sheets, whether its CSS is left to be minified with its run’s */ deferred: boolean;};type MinifierOptions
type MinifierOptions = { /** * Predicate that determines whether runs of whitespace inside a given element * can be collapsed (whether its content may be trimmed is up to `canTrimWhitespace`). * * Default: Built-in `canCollapseWhitespace` function */ canCollapseWhitespace?: ( tag: string, attrs: HTMLAttribute[], canCollapseWhitespace: (tag: string) => boolean ) => boolean; /** * Synchronous predicate that determines whether the built-in `minifyCSS` may * process a given piece of CSS—`type` is `undefined` for `style` elements, * `'inline'` for `style` attributes, and `'media'` for `media` attributes. * Returning false leaves that CSS as if `minifyCSS` were off, including its URLs * and unused rules (within `svg` elements, SVGO still minifies it under `minifySVG`). * * Default: `null` (all CSS is minified) */ canMinifyCSS?: ((text: string, type?: 'inline' | 'media') => boolean) | null; /** * Synchronous predicate that determines whether the built-in `minifyJS` may * process a given piece of JavaScript—`inline` is true for event handler * attributes. Returning false leaves that JavaScript unminified (`mergeScripts` * still applies). * * Default: `null` (all JavaScript is minified) */ canMinifyJS?: ((text: string, inline?: boolean) => boolean) | null; /** * Synchronous predicate that determines whether the built-in `minifySVG` may * pass a given outermost `svg` element, nested ones included, to SVGO. It * receives the element as serialized by the HTML pass (e.g., without comments * under `removeComments`); returning false leaves it as that pass wrote it. * * Default: `null` (all SVG is minified) */ canMinifySVG?: ((text: string) => boolean) | null; /** * Predicate that determines whether whitespace inside the element may be * trimmed; where not, it stays as written, as in `pre`. * * Default: Built-in `canTrimWhitespace` function */ canTrimWhitespace?: ( tag: string | null, attrs: HTMLAttribute[] | undefined, canTrimWhitespace: (tag: string) => boolean ) => boolean; /** * The maximum number of entries for the CSS minification cache. Higher values * improve performance for inputs with repeated CSS (e.g., batch processing). * - Cache is created on first `minify()` call and persists for the process lifetime * - Cache size is locked after first call—subsequent calls reuse the same cache * - `0` switches the cache off; negative and non-finite values fall back to the default size * * Default: `500` */ cacheCSS?: number; /** * The maximum number of entries for the JavaScript minification cache. Higher * values improve performance for inputs with repeated JavaScript. * - Cache is created on first `minify()` call and persists for the process lifetime * - Cache size is locked after first call—subsequent calls reuse the same cache * - `0` switches the cache off; negative and non-finite values fall back to the default size * * Default: `500` */ cacheJS?: number; /** * The maximum number of entries for the SVG minification cache. Higher * values improve performance for inputs with repeated SVG content. * - Cache is created on first `minify()` call and persists for the process lifetime * - Cache size is locked after first call—subsequent calls reuse the same cache * - `0` switches the cache off; negative and non-finite values fall back to the default size * * Default: `500` */ cacheSVG?: number; /** * When true, tag and attribute names are written as in the source rather than in lowercase. * Useful for framework components like `<MyButton>`. HTML names are still read in any case, * so every option applies to them as without it; hooks get names as written. * * Default: `false` */ caseSensitive?: boolean; /** * Collapse multiple whitespace characters within attribute values into a * single space. Also trims leading and trailing whitespace from attribute * values. Applied as an early normalization step before special attribute * handlers (CSS minification, class sorting, etc.) run. * * Default: `false` */ collapseAttributeWhitespace?: boolean; /** * Collapse boolean attributes to their name only (for example * `disabled="disabled"` → `disabled`). * See also: https://perfectionkills.com/experimenting-with-html-minifier/#collapse_boolean_attributes * * Default: `false` */ collapseBooleanAttributes?: boolean; /** * Collapse attributes with empty values to their name only (for example * `alt=""` → `alt`), which the HTML parser reads the same way. * * Default: `false` */ collapseEmptyAttributes?: boolean; /** * When false (default) whitespace around `inline` tags is preserved in * more cases. When true, whitespace between inline tags may be collapsed, * except around text-level elements (like `a`, `code`, or `em`); whitespace * next to text is kept as without the option. * Must also enable `collapseWhitespace` to have effect. * * Default: `false` */ collapseInlineTagWhitespace?: boolean; /** * Remove whitespace next to a no-break space (`U+00A0`), narrow no-break * space (`U+202F`), or figure space (`U+2007`) in text (for example * `a b` → `a b`), which changes how the text renders. Runs of * no-break spaces are kept. * Must also enable `collapseWhitespace` to have effect. * * Default: `false` */ collapseNoBreakSpaces?: boolean; /** * Collapse multiple whitespace characters into one where allowed. Also * controls trimming behaviour in several code paths. * See also: https://perfectionkills.com/experimenting-with-html-minifier/#collapse_whitespace * * Default: `false` */ collapseWhitespace?: boolean; /** * If true, be conservative when collapsing whitespace (preserve more * whitespace in edge cases). Affects collapse algorithms. * Must also enable `collapseWhitespace` to have effect. * * Default: `false` */ conservativeCollapse?: boolean; /** * When set to `false`, minification errors may throw. * By default, the minifier will attempt to recover from minification * errors, or ignore them and preserve the original content. * * Default: `true` */ continueOnMinifyError?: boolean; /** * When true, the parser will attempt to continue on recoverable parse * errors. Otherwise, parsing errors may throw. * * Default: `false` */ continueOnParseError?: boolean; /** * Array of regexes used to recognise custom attribute assignment * operators (e.g., `'<div flex?="{{mode != cover}}"></div>'`). * These are concatenated with the built-in assignment patterns. * * Default: `[]` */ customAttrAssign?: RegExp[]; /** * Regex matching attribute names whose values should be collapsed. * Basically used to remove newlines and excess spaces inside attribute values, * e.g., `/ng-class/`. */ customAttrCollapse?: RegExp; /** * Array of `[openRegExp, closeRegExp]` pairs used by the parser to * detect custom attribute surround patterns (for non-standard syntaxes, * e.g., `<input {{#if value}}checked="checked"{{/if}}>`). */ customAttrSurround?: [RegExp, RegExp][]; /** * Array of regexes used to detect event handler attributes for `minifyJS` * (e.g., `ng-click`). The default matches standard `on…` event attributes. * * Default: `[/^on[a-z]{3,}$/]` */ customEventAttributes?: RegExp[]; /** * Rejects `ignoreCustomFragments` patterns that risk catastrophic backtracking, * rather than warning about them: those that compound quantifiers or alternation * (`(a+)+`, `(a|b)*`), those that repeat the same unbounded atom twice in a row * (`.*.*`), and those too long or too deeply nested to analyze at all. * * Default: `false` */ strictCustomFragments?: boolean; /** * When true, decodes HTML entities in text and attributes before * processing, and re-encodes ambiguous ampersands when outputting. * * Default: `false` */ decodeEntities?: boolean; /** * Comments matching any pattern in this array of regexes will be * preserved when `removeComments` is enabled. The default preserves * “bang” comments and comments starting with `#`. * * Default: `[/^!/, /^\s*#/]` */ ignoreCustomComments?: RegExp[]; /** * Array of regexes used to identify fragments that should be * preserved (for example server templates). These fragments are temporarily * replaced during minification to avoid corrupting template code. * The default preserves ASP/PHP-style tags and XML declarations. * * Default: `[/<%[\s\S]*?%>/, /<\?(?:php[\t\n\r ]|=|\$|xml(?:-stylesheet)?(?![\w-])|\s)[\s\S]*?\?>/i]` */ ignoreCustomFragments?: RegExp[]; /** * If false, tags marked as auto-generated by the parser will be omitted * from output. Useful to skip injected tags. * * Default: `false` */ includeAutoGeneratedTags?: boolean; /** * Collection of custom element tag names that should be treated as inline * elements for white-space handling, alongside the built-in inline elements. * * Default: `[]` */ inlineCustomElements?: ArrayLike<string>; /** * Keep the trailing slash on void elements and other start tags that carry one, and read it * as closing the element. The default drops the slash and ignores it, as HTML does; in SVG * and MathML a slash closes the element either way. * * Default: `false` */ keepClosingSlash?: boolean; /** * Logging function used by the minifier for warnings/errors/info. * You can directly provide `console.log`, but `message` may also be an `Error` * object or other non-string value. * * Default: `() => {}` (no-op function) */ log?: (message: unknown) => void; /** * The maximum allowed input length. Used as a guard against ReDoS via * pathological inputs. If the input exceeds this length an error is * thrown. * * Default: No limit */ maxInputLength?: number; /** * Maximum line length for the output. When set the minifier will wrap * output to the given number of characters where possible, splitting * lines only in tags—between attributes or before a tag’s `>`. * * Default: No limit */ maxLineLength?: number; /** * When true, consecutive inline `<script>` elements are merged into one. * Only merges classic scripts whose attributes match (other than a JavaScript * `type`), and none with an `id`. Does not merge external scripts (with `src`). * * Default: `false` */ mergeScripts?: boolean; /** * When true, consecutive `<style>` elements are merged into one. Only merges * style sheets whose attributes match (other than a CSS `type`, and `media` * that matches all), and none with an `id`, where the first ends cleanly and * the next doesn’t hold `@import` or `@namespace`. * * Default: `false` */ mergeStyles?: boolean; /** * When true, enables CSS minification for inline `<style>` tags or * `style` attributes. If an object is provided, it is passed to * [Lightning CSS](https://www.npmjs.com/package/lightningcss) * as transform options. If a function is provided, it will be used to perform * custom CSS minification. If disabled, CSS is not minified. * * Default: `false` */ minifyCSS?: | boolean | Partial< import('lightningcss').TransformOptions< import('lightningcss').CustomAtRules > > | ((text: string, type?: string) => Promise<string> | string); /** * When true, enables JS minification for `<script>` contents and * event handler attributes. If an object is provided, it can include: * - `engine`: The minifier to use (`terser` or `swc`). Default: `terser`. * - Engine-specific options (e.g., Terser options if `engine: 'terser'`, * SWC options if `engine: 'swc'`). * If a function is provided, it will be used to perform * custom JS minification. If disabled, JS is not minified. * * Default: `false` */ minifyJS?: | boolean | import('terser').MinifyOptions | { engine?: 'terser' | 'swc'; [key: string]: any; } | ((text: string, inline?: boolean) => Promise<string> | string); /** * When true, removes whitespace from the content of JSON `<script>` types * (e.g., `application/ld+json`, `importmap`, `speculationrules`), leaving * values as written. Malformed JSON is left as is. * * Default: `false` */ minifyJSON?: boolean; /** * When true, enables URL rewriting/minification. If an object is provided, * the `site` property sets the base URL for computing relative paths. * If a string is provided, it is treated as an `{ site: string }` options * object. If a function is provided, it will be used to perform custom URL * minification. If disabled, URLs are not minified. * * Default: `false` */ minifyURLs?: | boolean | string | { site?: string; } | ((text: string) => Promise<string> | string); /** * When true, enables SVG minification using [SVGO](https://github.com/svg/svgo). * Complete SVG subtrees are extracted and optimized as a block, with the SVGO * plugins that assume a standalone SVG file turned off. * If an object is provided, it is passed to SVGO as configuration options; unless * it sets `plugins`, it keeps that plugin set. * If disabled, SVG content is minified using standard HTML rules only. * * Default: `false` */ minifySVG?: boolean | Object; /** * When wrapping lines, doesn’t split a line in an end tag (e.g., keeps * `</a>` from becoming `</a` and `>` on two lines). * * Default: `false` */ noNewlinesBeforeTagClose?: boolean; /** * When true, treats input as a partial HTML fragment rather than a complete * document. This preserves stray end tags (closing tags without corresponding * opening tags) and prevents auto-closing of unclosed tags at the end of input. * Useful for minifying template fragments, SSI includes, or other partial HTML * that will be combined with other fragments. * * Default: `false` */ partialMarkup?: boolean; /** * Preserve a single line break at the start/end of text nodes when * collapsing/trimming whitespace. * Must also enable `collapseWhitespace` to have effect. * * Default: `false` */ preserveLineBreaks?: boolean; /** * Name of a preset configuration to use as a base (`conservative` or * `comprehensive`). Explicitly provided options take precedence over * preset values. Unknown preset names are ignored (with a warning). * * Default: No preset */ preset?: string; /** * When true, attribute values will not be HTML-escaped (dangerous for * untrusted input). By default, attributes are escaped. * * Default: `false` */ preventAttributesEscaping?: boolean; /** * Array of `type` attribute values for `<script>` elements whose contents * should be processed as HTML * (e.g., `text/ng-template`, `text/x-handlebars-template`, etc.). * When present, the contents of matching script tags are recursively minified, * like normal HTML content. * * Default: `[]` */ processScripts?: string[]; /** * Preferred quote character for attribute values. If unspecified, the * minifier picks the safest quote based on the attribute value. * * Default: Auto-detected */ quoteCharacter?: '"' | "'"; /** * Remove quotes around attribute values where it is safe to do so. * See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_attribute_quotes * * Default: `false` */ removeAttributeQuotes?: boolean; /** * Remove HTML comments. Comments that match `ignoreCustomComments` will * still be preserved. * See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_comments * * Default: `false` */ removeComments?: boolean; /** * Remove default `type` attributes from `<style>`/`<link>` (e.g., `type="text/css"`) * and `<script>` (e.g., `type="text/javascript"`) elements. * * Default: `false` */ removeDefaultTypeAttributes?: boolean; /** * If true, removes attributes whose values are empty (some attributes * are excluded by name). Can also be a function to customise which empty * attributes are removed. * See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_empty_or_blank_attributes * * Default: `false` */ removeEmptyAttributes?: boolean | ((attrName: string, tag: string) => boolean); /** * Remove elements that are empty and safe to remove (for example * `<script />` without `src`), including elements left empty that way. * See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_empty_elements * * Default: `false` */ removeEmptyElements?: boolean; /** * Specifies empty elements to preserve when `removeEmptyElements` is enabled. * Has no effect unless `removeEmptyElements: true`. * * Accepts tag names or HTML-like element specifications: * * * Tag name only: `["td", "span"]`—preserves all empty elements of these types * * With valued attributes: `["<i class='test'>"]`—preserves only when attribute values match * * With boolean attributes: `["<input disabled>"]`—preserves only when the * boolean attribute is present * * Mixed: `["<button type='button' disabled>"]`—all specified attributes must match * * Attribute matching: * * * All specified attributes must be present and match (valued attributes must have exact values) * * Additional attributes on the element are allowed * * Element and attribute names match in any case * * Supports double quotes, single quotes, and unquoted attribute values in specifications * * Limitations: * * * Self-closing syntax (e.g., `["<span/>"]`) is not supported; use `["span"]` instead * * Definitions containing `>` within quoted attribute values (e.g., * `["<span title='a>b'>"]`) are not supported * * Default: `[]` */ removeEmptyElementsExcept?: string[]; /** * Drop optional start/end tags where the HTML specification permits it * (for example `</li>`, optional `<html>` etc.). * See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_optional_tags * * Default: `false` */ removeOptionalTags?: boolean; /** * Remove attributes that are redundant because they match the element’s * default values (for example `<button type="submit">`) or have no effect * (for example `xml:lang`), along with `meta` elements and `rel` keywords * that have no effect. * See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_redundant_attributes * * Default: `false` */ removeRedundantAttributes?: boolean; /** * **Note that this will result in invalid HTML!** * * When true, extra whitespace between tag name and attributes (or before * the closing bracket) will be removed where possible. Affects output spacing * such as the space used in the short doctype representation. * * Default: `false` */ removeTagWhitespace?: boolean; /** * Remove 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. * Requires `minifyCSS` (removal runs through Lightning CSS) and has no effect on * `style` or `media` attributes. * * Element, class, and ID names are collected from the markup and—unless `scripts` * is set to `false`—from inline `script` elements; class names and IDs also from * `data-*` attributes. Names that only ever appear in external scripts cannot * be detected; list those under `safelist` (strings or regular expressions) to * keep them. * * Default: `false` */ removeUnusedCSS?: | boolean | { safelist?: Array<string | RegExp>; scripts?: boolean; }; /** * When true, writes empty SVG and MathML elements as self-closing tags (for * example `<path d="…"/>` for `<path d="…"></path>`), which HTML reads as the * same element in foreign content; HTML elements, including those in * `foreignObject` and `annotation-xml`, keep their end tags. * * Default: `false` */ selfCloseForeignElements?: boolean; /** * When true, enables sorting of attributes. If a function is provided it * will be used as a custom attribute sorter, which should mutate `attrs` * in-place to the desired order. If disabled, the minifier will attempt to * preserve the order from the input. * * Default: `false` */ sortAttributes?: boolean | ((tag: string, attrs: HTMLAttribute[]) => void); /** * When true, enables sorting of class names inside `class` attributes. * If a function is provided, it will be used to transform/sort the class * name string. If disabled, the minifier will attempt to preserve the * class-name order from the input. * * Default: `false` */ sortClassNames?: boolean | ((value: string) => string); /** * When true, whitespace around ignored custom fragments is removed rather * than collapsed where the minifier removes whitespace anyway (e.g., between * block-level elements). Whitespace in tags, attribute values, CSS, and * JavaScript is kept. * * Default: `false` */ trimCustomFragments?: boolean; /** * Convert any doctype to the short `<!doctype html>` form * (switches pages with legacy doctypes to standards mode). * See also: https://perfectionkills.com/experimenting-with-html-minifier/#use_short_doctype * * Default: `false` */ useShortDoctype?: boolean;};Package Files (2)
Dependencies (6)
Dev Dependencies (9)
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/html-minifier.
- Markdown[](https://www.jsdocs.io/package/html-minifier)
- HTML<a href="https://www.jsdocs.io/package/html-minifier"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 4402 ms. - Missing or incorrect documentation? Open an issue for this package.
