UNPKG

html-minifier-next

Version:

Super-configurable and well-tested web page minifier (enhanced successor of HTML Minifier)

491 lines 19.2 kB
export function minify(value: string, options?: MinifierOptions): Promise<string>; declare namespace _default { export { minify }; export { presets }; export { getPreset }; export { getPresetNames }; } export default _default; /** * Representation of an attribute from the HTML parser. */ export type HTMLAttribute = { name: string; value?: string; quote?: string; customAssign?: string; customOpen?: string; customClose?: string; }; /** * Options that control how HTML is minified. All of these are optional * and usually default to a disabled/safe value unless noted. */ export type MinifierOptions = { /** * Predicate that determines whether whitespace inside a given element * can be collapsed. * * Default: Built-in `canCollapseWhitespace` function */ canCollapseWhitespace?: (tag: string, attrs: HTMLAttribute[], canCollapseWhitespace: (tag: string) => boolean) => boolean; /** * Predicate that determines whether leading/trailing whitespace around * the element may be trimmed. * * 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 * - Explicit `0` values are coerced to `1` (minimum functional cache 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 * - Explicit `0` values are coerced to `1` (minimum functional cache 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 * - Explicit `0` values are coerced to `1` (minimum functional cache size) * * Default: `500` */ cacheSVG?: number; /** * When true, tag and attribute names are treated as case-sensitive. * Useful for custom HTML tags. * If false (default) names are lower-cased via the `name` function. * * 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; /** * When false (default) whitespace around `inline` tags is preserved in * more cases. When true, whitespace around inline tags may be collapsed. * Must also enable `collapseWhitespace` to have effect. * * Default: `false` */ collapseInlineTagWhitespace?: 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[]; /** * Limits the quantifier used when building a safe regex for custom * fragments to avoid ReDoS. See source use for details. * * Default: `200` */ customFragmentQuantifierLimit?: number; /** * 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. * * Default: `[/<%[\s\S]*?%>/, /<\?[\s\S]*?\?>/]` */ 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>; /** * Preserve the trailing slash in self-closing tags when present. * * 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. * * Default: No limit */ maxLineLength?: number; /** * When true, consecutive inline `<script>` elements are merged into one. * Only merges compatible scripts (same `type`, matching `async`/`defer`/ * `nomodule`/`nonce` attributes). Does not merge external scripts (with `src`). * * Default: `false` */ mergeScripts?: 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`. * Note: Inline event handlers (e.g., `onclick="…"`) always use Terser * regardless of engine setting, as swc doesn’t support bare return statements. * - 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, 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. * If an object is provided, it is passed to SVGO as configuration options. * If disabled, SVG content is minified using standard HTML rules only. * * Default: `false` */ minifySVG?: boolean | any; /** * Function used to normalise tag/attribute names. By default, this lowercases * names, unless `caseSensitive` is enabled. * * Default: `(name) => name.toLowerCase()`, * or `(name) => name` (no-op function) if `caseSensitive` is enabled. */ name?: (name: string) => string; /** * When wrapping lines, prevent inserting a newline directly before a * closing tag (useful to keep tags like `</a>` on the same line). * * Default: `false` */ noNewlinesBeforeTagClose?: boolean; /** * When true, treat 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; /** * When true, attribute values will not be HTML-escaped (dangerous for * untrusted input). By default, attributes are escaped. * * Default: `false` */ preventAttributesEscaping?: boolean; /** * When true, conditional comments (for example `<!--[if IE]> … <![endif]-->`) * will have their inner content processed by the minifier. * Useful to minify HTML that appears inside conditional comments. * * Default: `false` */ processConditionalComments?: 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; /** * 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`). * 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: `["<span aria-hidden='true'>"]`—preserves only when attribute values match * * With boolean attributes: `["<input disabled>"]`—preserves only when 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 * * Attribute name matching respects the `caseSensitive` option * * 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">`). * See also: https://perfectionkills.com/experimenting-with-html-minifier/#remove_redundant_attributes * * Default: `false` */ removeRedundantAttributes?: boolean; /** * Remove `type` attributes from `<script>` when they are unnecessary * (e.g. `type="text/javascript"`). * * Default: `false` */ removeScriptTypeAttributes?: boolean; /** * Remove `type` attributes from `<style>` and `<link>` elements when * they are unnecessary (e.g. `type="text/css"`). * * Default: `false` */ removeStyleLinkTypeAttributes?: 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; /** * 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 may be trimmed * more aggressively. This affects how preserved fragments interact with * surrounding whitespace collapse. * * Default: `false` */ trimCustomFragments?: boolean; /** * Replace the HTML doctype with the short `<!doctype html>` form. * See also: https://perfectionkills.com/experimenting-with-html-minifier/#use_short_doctype * * Default: `false` */ useShortDoctype?: boolean; }; import { presets } from './presets.js'; import { getPreset } from './presets.js'; import { getPresetNames } from './presets.js'; export { presets, getPreset, getPresetNames }; //# sourceMappingURL=htmlminifier.d.ts.map