### Install HTMLMinifier Globally (CLI) Source: https://github.com/kangax/html-minifier/blob/gh-pages/README.md Install the html-minifier package globally to use it as a command-line application. ```shell npm install html-minifier -g ``` -------------------------------- ### Install HTMLMinifier from Git Source: https://github.com/kangax/html-minifier/blob/gh-pages/README.md Clone the repository and link the package locally for development or testing. ```shell git clone git://github.com/kangax/html-minifier.git cd html-minifier npm link . ``` -------------------------------- ### Install html-minifier globally Source: https://context7.com/kangax/html-minifier/llms.txt Install the html-minifier package globally using npm to use its command-line interface. ```bash # Install globally npm install -g html-minifier ``` -------------------------------- ### Example JSON configuration for html-minifier Source: https://context7.com/kangax/html-minifier/llms.txt A sample JSON file demonstrating various html-minifier configuration options, including whitespace collapsing, comment removal, and CSS/JS minification. ```json { "collapseWhitespace": true, "removeComments": true, "removeOptionalTags": true, "removeRedundantAttributes": true, "removeScriptTypeAttributes": true, "removeStyleLinkTypeAttributes": true, "removeTagWhitespace": true, "useShortDoctype": true, "minifyCSS": true, "minifyJS": true, "sortAttributes": true, "sortClassName": true, "processConditionalComments": true, "ignoreCustomFragments": [ "<%[\s\S]*?%>", "<\?[\s\S]*?\?>" ], "processScripts": ["text/html"] } ``` -------------------------------- ### Install HTMLMinifier Locally (Programmatic) Source: https://github.com/kangax/html-minifier/blob/gh-pages/README.md Install the html-minifier package locally for use within your Node.js projects. ```shell npm install html-minifier ``` -------------------------------- ### Basic HTML Minification with HTMLMinifier Source: https://context7.com/kangax/html-minifier/llms.txt Demonstrates basic HTML minification using the `minify` function with options for whitespace collapsing, comment removal, attribute cleaning, and doctype simplification. Ensure the 'html-minifier' package is installed. ```javascript const { minify } = require('html-minifier'); // Basic whitespace and comment removal const result = minify( "\n \n \n \n \n \n Hello World\n \n \n

Hello, World!

\n \n \n", { collapseWhitespace: true, removeComments: true, removeRedundantAttributes: true, useShortDoctype: true } ); console.log(result); // -> Hello World

Hello, World!

``` -------------------------------- ### Basic Node.js HTML Minification Source: https://github.com/kangax/html-minifier/blob/gh-pages/README.md Programmatically minify an HTML string using the html-minifier module. Ensure the module is installed and required. ```javascript var minify = require('html-minifier').minify; var result = minify('

foo

', { removeAttributeQuotes: true }); result; // '

foo

' ``` -------------------------------- ### Gulp HTML Minification Task Source: https://github.com/kangax/html-minifier/blob/gh-pages/README.md Configure a Gulp task to minify HTML files. This example uses specific options for minification and streams files through the minifier. ```javascript const { src, dest, series } = require('gulp'); const htmlMinify = require('html-minifier'); const options = { includeAutoGeneratedTags: true, removeAttributeQuotes: true, removeComments: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, sortClassName: true, useShortDoctype: true, collapseWhitespace: true }; function html() { return src('app/**/*.html') .on('data', function(file) { const buferFile = Buffer.from(htmlMinify.minify(file.contents.toString(), options)) return file.contents = buferFile }) .pipe(dest('build')) } exports.html = series(html) ``` -------------------------------- ### Valid HTML with Handlebars Source: https://github.com/kangax/html-minifier/wiki/Minifying Handlebars templates This is an example of valid HTML when using Handlebars within an attribute value, where string arguments are single-quoted. ```handlebars ``` -------------------------------- ### Comment Stripping with Exceptions in HTMLMinifier Source: https://context7.com/kangax/html-minifier/llms.txt Shows how to remove HTML comments using `removeComments` while preserving specific comments with `ignoreCustomComments`. By default, comments starting with '!' are kept. Requires 'html-minifier' package. ```javascript const { minify } = require('html-minifier'); const html = "\n \n \n \n

content

\n"; // Default: removes all except /^!/ matches console.log(minify(html, { removeComments: true })); // ->

content

// Custom: also preserve comments starting with @license console.log(minify(html, { removeComments: true, ignoreCustomComments: [/^!/, /^@license/] })); // ->

content

``` -------------------------------- ### removeComments + ignoreCustomComments Source: https://context7.com/kangax/html-minifier/llms.txt Strips all HTML comments. Comments whose text matches any regex in `ignoreCustomComments` are preserved. By default, comments starting with `//!` are kept. ```APIDOC ## removeComments + ignoreCustomComments — Comment stripping with exceptions ### Description Strips all HTML comments. Comments whose text matches any regex in `ignoreCustomComments` are preserved. By default `[/^!/]` is kept (e.g., ``). ### Options - `removeComments` (boolean): Strips all HTML comments. - `ignoreCustomComments` (Array): An array of regular expressions to match custom comments that should be preserved. ### Example ```javascript const { minify } = require('html-minifier'); const html = `

content

`; // Default: removes all except /^!/ matches console.log(minify(html, { removeComments: true })); // ->

content

// Custom: also preserve comments starting with @license console.log(minify(html, { removeComments: true, ignoreCustomComments: [/^!/, /^@license/] })); // ->

content

``` ``` -------------------------------- ### Invalid HTML with Handlebars Source: https://github.com/kangax/html-minifier/wiki/Minifying Handlebars templates This example demonstrates invalid HTML generated by Handlebars when string arguments within an attribute value are double-quoted, causing the HTML parser to terminate prematurely. ```handlebars ``` -------------------------------- ### Drop Default-Value Attributes Source: https://context7.com/kangax/html-minifier/llms.txt Use `removeRedundantAttributes` to remove attributes that have their default values according to the HTML specification, like `type="text"` on `` or `method="get"` on `
`. ```javascript const { minify } = require('html-minifier'); const html = `
`; console.log(minify(html, { removeRedundantAttributes: true })); // ->
``` -------------------------------- ### Use JSON config file for CLI options Source: https://context7.com/kangax/html-minifier/llms.txt Specify all minification options in a JSON configuration file and pass it to the CLI using the `-c` flag. Regex values should be string-delimited by `/`. ```bash html-minifier -c config/htmlmin.json -o dist/index.html src/index.html ``` -------------------------------- ### Run HTMLMinifier Benchmarks Source: https://github.com/kangax/html-minifier/blob/gh-pages/README.md Execute the benchmark script to measure the performance of HTMLMinifier. ```shell node benchmark.js ``` -------------------------------- ### Process directory recursively via CLI Source: https://context7.com/kangax/html-minifier/llms.txt Minify all HTML files within a directory recursively using `--input-dir` and `--output-dir`. Specify file extensions with `--file-ext`. ```bash html-minifier \ --input-dir src/templates \ --output-dir dist/templates \ --file-ext html \ --collapse-whitespace \ --remove-comments \ --minify-css true \ --minify-js true ``` -------------------------------- ### Minify a single file via CLI Source: https://context7.com/kangax/html-minifier/llms.txt Minify a single HTML file using the `html-minifier` command-line tool with various options. Output is written to a specified file. ```bash # Minify a file with common options, write to output file html-minifier \ --collapse-whitespace \ --remove-comments \ --remove-optional-tags \ --remove-redundant-attributes \ --remove-script-type-attributes \ --remove-style-link-type-attributes \ --remove-tag-whitespace \ --use-short-doctype \ --minify-css true \ --minify-js true \ -o dist/index.html \ src/index.html ``` -------------------------------- ### Minify from STDIN to STDOUT via CLI Source: https://context7.com/kangax/html-minifier/llms.txt Pipe HTML content from standard input to `html-minifier` and redirect the output to standard output. This is useful for chaining commands. ```bash # Read from STDIN, write to STDOUT cat src/index.html | html-minifier --collapse-whitespace > dist/index.html ``` -------------------------------- ### minify(value, options) Source: https://context7.com/kangax/html-minifier/llms.txt The sole exported function for programmatic HTML minification. It accepts an HTML string and an options object, returning the minified HTML string synchronously. All options default to false or their documented defaults when omitted; unrecognized keys are silently ignored. ```APIDOC ## minify(value, options) — Programmatic HTML minification ### Description The sole exported function. Accepts an HTML string and an options object, returns the minified HTML string synchronously. All options default to `false` or their documented defaults when omitted; unrecognized keys are silently ignored. ### Method ```javascript const { minify } = require('html-minifier'); // Basic whitespace and comment removal const result = minify(` Hello World

Hello, World!

`, { collapseWhitespace: true, removeComments: true, removeRedundantAttributes: true, useShortDoctype: true }); console.log(result); // -> Hello World

Hello, World!

``` ``` -------------------------------- ### Sort Attributes and Class Names with sortAttributes/sortClassName Source: https://context7.com/kangax/html-minifier/llms.txt Enable `sortAttributes` and `sortClassName` to reorder HTML attributes and CSS class names by frequency. This improves gzip/brotli compression without altering the rendered output. ```javascript const { minify } = require('html-minifier'); const html = `
`; console.log(minify(html, { sortAttributes: true, sortClassName: true })); ``` -------------------------------- ### Configure html-minifier for Handlebars Attribute Surrounding Source: https://github.com/kangax/html-minifier/wiki/Minifying Handlebars templates Configure html-minifier to recognize Handlebars double-curly bracket pairs surrounding element attributes by defining custom attribute surrounding regular expressions. ```javascript var hbAttrWrapOpen = /\{\{#[^}]+\}\}//; var hbAttrWrapClose = /\{\{\/[^}]+\}\}//; var hbAttrWrapPair = [hbAttrWrapOpen, hbAttrWrapClose]; var minifier = require('html-minifier', { customAttrSurround: [hbAttrWrapPair] }); ``` -------------------------------- ### Limit output line length with maxLineLength Source: https://context7.com/kangax/html-minifier/llms.txt The `maxLineLength` option inserts newlines at valid HTML boundaries to keep lines under a specified character count. This is helpful for environments with line-length restrictions. ```javascript const { minify } = require('html-minifier'); const html = '
one
two
three
'; console.log(minify(html, { maxLineLength: 30 })); // ->
one
// ->
two
// ->
three
``` -------------------------------- ### Preserve markup blocks with Source: https://context7.com/kangax/html-minifier/llms.txt Wrap arbitrary HTML blocks with `` to prevent them from being minified. This is useful for preserving specific formatting or content. ```javascript const { minify } = require('html-minifier'); const html = `
    Preserving   all    whitespace
    and  formatting here.
  

This gets minified.

`; console.log(minify(html, { collapseWhitespace: true, removeComments: true })); // ->
//
//        Preserving   all    whitespace
//        and  formatting here.
//      
//

This gets minified.

``` -------------------------------- ### Process IE Conditional Comments with processConditionalComments Source: https://context7.com/kangax/html-minifier/llms.txt Set `processConditionalComments` to `true` to run the HTML content within IE conditional comments through the minifier using the same options. This optimizes content specifically for older IE versions. ```javascript const { minify } = require('html-minifier'); const html = ``; console.log(minify(html, { processConditionalComments: true, collapseWhitespace: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true })); ``` -------------------------------- ### Controlling Whitespace Collapse in HTMLMinifier Source: https://context7.com/kangax/html-minifier/llms.txt Illustrates the `collapseWhitespace` option in HTMLMinifier. Use `conservativeCollapse` to retain at least one space, and `preserveLineBreaks` to keep a single newline when whitespace contains one. Requires 'html-minifier' package. ```javascript const { minify } = require('html-minifier'); const html = '
foo bar baz
'; console.log(minify(html, { collapseWhitespace: true })); // ->
foo bar baz
// conservativeCollapse: always keep at least one space console.log(minify(html, { collapseWhitespace: true, conservativeCollapse: true })); // ->
foo bar baz
// preserveLineBreaks: retain a single newline when whitespace contains one const multiline = '

line one\n\n\nline two

'; console.log(minify(multiline, { collapseWhitespace: true, preserveLineBreaks: true })); // ->

line one\nline two

``` -------------------------------- ### Handlebars Expression for Individual Attributes (Recognized) Source: https://github.com/kangax/html-minifier/wiki/Minifying Handlebars templates This HTML markup shows the correct way to use Handlebars for conditional attributes by wrapping each attribute individually, which html-minifier can recognize. ```html ``` -------------------------------- ### Minify Inline JavaScript with minifyJS Source: https://context7.com/kangax/html-minifier/llms.txt Use the `minifyJS` option to minify JavaScript within ` `; console.log(minify(html, { minifyJS: true })); ``` ```javascript console.log(minify(html, { minifyJS: { compress: { drop_console: true }, mangle: true } })); ``` -------------------------------- ### Preserve Template Engine Syntax with ignoreCustomFragments Source: https://context7.com/kangax/html-minifier/llms.txt Use `ignoreCustomFragments` with an array of regexes to prevent minification of template engine tags like PHP, ERB, or Mustache. This ensures template syntax remains intact. ```javascript const { minify } = require('html-minifier'); const html = `

Hello, name; ?>

{{ greeting }}

`; console.log(minify(html, { collapseWhitespace: true, ignoreCustomFragments: [/<%[\s\S]*?%>/, /<\?[\s\S]*?\?>/, /\{\{[\s\S]*?\}\}/] })); ``` -------------------------------- ### Relativize/Shorten URLs with minifyURLs Source: https://context7.com/kangax/html-minifier/llms.txt The `minifyURLs` option uses `relateurl` to shorten absolute URLs in attributes like `href`, `src`, and `action`. It can be a base-URL string, an options object, or a custom function. ```javascript const { minify } = require('html-minifier'); const html = `link `; console.log(minify(html, { minifyURLs: 'https://example.com/foo/' })); ``` -------------------------------- ### Delete Elements with No Content Source: https://context7.com/kangax/html-minifier/llms.txt Use `removeEmptyElements` to remove elements that contain no content. Elements with functional meaning even when empty, such as `