HTMLMinifier

4.0.0 · active · verified Sun Apr 19

HTMLMinifier is a highly configurable and well-tested JavaScript-based tool designed for aggressive HTML minification. The current stable version is 4.0.0. While minor bug fixes and dependency upgrades are released periodically, major version updates, like the transition from v3 to v4, occur less frequently. Its core functionality involves parsing HTML into a tree structure, applying various optimization rules, and then outputting a compacted HTML string. A key differentiator highlighted in its documentation is its effectiveness in reducing file sizes compared to several alternative solutions, making it suitable for performance optimization in web projects. It provides extensive options to control minification, including collapsing whitespace, removing comments, minifying inline CSS and JavaScript, and handling various HTML tag-specific optimizations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically minify an HTML string using a comprehensive set of common options for maximum compression, showing before and after output.

const { minify } = require('html-minifier');

const html = `
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Hello World</title>
    <!-- This is a comment -->
    <style>
        body { font-family: sans-serif; color: #333; /* some comment */ }
    </style>
</head>
<body>
    <h1>  Welcome to my Page!  </h1>
    <p>This is a paragraph with   extra    spaces.</p>
    <script>
        // Inline JavaScript
        function greet() {
            console.log("Hello from HTMLMinifier!");
        }
        greet();
    </script>
</body>
</html>
`;

const minifiedHtml = minify(html, {
  removeComments: true,
  collapseWhitespace: true,
  collapseBooleanAttributes: true,
  removeEmptyAttributes: true,
  removeOptionalTags: true,
  minifyJS: true,
  minifyCSS: true,
  useShortDoctype: true,
  sortAttributes: true,
  sortClassName: true,
  decodeEntities: true,
});

console.log(minifiedHtml);
/* Expected output:
<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Hello World</title><style>body{font-family:sans-serif;color:#333}</style></head><body><h1>Welcome to my Page!</h1><p>This is a paragraph with extra spaces.</p><script>function greet(){console.log("Hello from HTMLMinifier!")}greet()</script></body></html>
*/

view raw JSON →