HTMLMinifier-Terser

7.2.0 · active · verified Sun Apr 19

HTMLMinifier-Terser is a highly configurable, well-tested JavaScript-based HTML minifier designed to optimize web page load times by significantly reducing the size of HTML, CSS, and JavaScript within HTML documents. The current stable version is 7.2.0, with regular updates addressing bug fixes, dependency updates, and minor feature enhancements. Major versions, like v7.0.0, introduce significant breaking changes such as the migration to ESM and updated Node.js requirements. It differentiates itself through extensive configurability, allowing fine-grained control over the minification process, and its strong performance compared to other minifiers, often yielding smaller output sizes as demonstrated in its minification comparison benchmarks.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically minify HTML using various common options like collapsing whitespace, removing comments, and minifying embedded JavaScript and CSS.

import { minify } from 'html-minifier-terser';

async function runMinification() {
  const htmlInput = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Test Page</title>
      <style>body { color: red; } /* important */</style>
    </head>
    <body>
      <!-- This is a comment -->
      <p title="  some title  " id="moo">Hello, world!  </p>
      <script>  function greet() { console.log('Hi!'); }  </script>
    </body>
    </html>
  `;

  const minifiedHtml = await minify(htmlInput, {
    removeComments: true,
    collapseWhitespace: true,
    minifyJS: true,
    minifyCSS: true,
    removeAttributeQuotes: true,
    processConditionalComments: true,
  });

  console.log(minifiedHtml);
  // Expected output (approx): "<!DOCTYPE html><html lang=en><head><meta charset=UTF-8><title>Test Page</title><style>body{color:red}</style></head><body><p title=some title id=moo>Hello, world!</p><script>function greet(){console.log('Hi!')}</script></body></html>"
}

runMinification();

view raw JSON →