CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-minify

Minifier of js, css, html and img files with CLI and programmatic interfaces

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

html-minification.mddocs/

HTML Minification

Comprehensive HTML minification using html-minifier-next with aggressive default settings and extensive customization options.

Capabilities

HTML Minifier Function

Minifies HTML data with comprehensive optimization settings including embedded JavaScript and CSS minification.

/**
 * Minifies HTML data using html-minifier-next
 * @param data - HTML source code to minify
 * @param userOptions - Configuration options for HTML minification
 * @returns Minified HTML code (synchronous)
 */
function minify.html(data: string, userOptions?: MinifyOptions): string;

interface MinifyOptions {
  html?: HTMLMinifierOptions;
}

interface HTMLMinifierOptions {
  removeComments?: boolean;                    // Remove HTML comments
  removeCommentsFromCDATA?: boolean;          // Remove comments from CDATA sections
  removeCDATASectionsFromCDATA?: boolean;     // Remove CDATA sections
  collapseWhitespace?: boolean;               // Collapse whitespace
  collapseBooleanAttributes?: boolean;        // Collapse boolean attributes
  removeAttributeQuotes?: boolean;            // Remove attribute quotes when safe
  removeRedundantAttributes?: boolean;        // Remove redundant attributes
  useShortDoctype?: boolean;                  // Use short doctype
  removeEmptyAttributes?: boolean;            // Remove empty attributes
  removeEmptyElements?: boolean;              // Remove empty elements
  removeOptionalTags?: boolean;               // Remove optional tags
  removeScriptTypeAttributes?: boolean;       // Remove type="text/javascript"
  removeStyleLinkTypeAttributes?: boolean;    // Remove type="text/css"
  minifyJS?: boolean;                         // Minify inline JavaScript
  minifyCSS?: boolean;                        // Minify inline CSS
}

Usage Examples:

import { minify } from "minify";

// Default minification with aggressive settings
const html = `
<html>
  <head>
    <title>  My Page  </title>
    <script type="text/javascript">
      function hello() {
        console.log("Hello World");
      }
    </script>
    <style type="text/css">
      body {  color: red;  }
    </style>
  </head>
  <body>
    <p id="">Hello World</p>
    <!-- This is a comment -->
  </body>
</html>
`;

const minified = await minify.html(html);
// Result: <html><head><title>My Page</title><script>function hello(){console.log("Hello World")}</script><style>body{color:red}</style></head><body><p>Hello World</p></body></html>

// Custom configuration
const customMinified = await minify.html(html, {
  html: {
    removeComments: false,        // Keep comments
    removeOptionalTags: false,    // Keep optional tags
    minifyJS: false,              // Don't minify inline JS
    collapseWhitespace: true      // Still collapse whitespace
  }
});

Default Minification Settings

The HTML minifier uses these aggressive default settings for maximum file size reduction:

const defaultHTMLOptions = {
  removeComments: true,                       // Remove <!-- comments -->
  removeCommentsFromCDATA: true,              // Clean CDATA sections
  removeCDATASectionsFromCDATA: true,         // Remove CDATA wrappers
  collapseWhitespace: true,                   // Collapse all whitespace
  collapseBooleanAttributes: true,            // checked="checked" → checked
  removeAttributeQuotes: true,                // Remove quotes when safe
  removeRedundantAttributes: true,            // Remove default attributes
  useShortDoctype: true,                      // <!DOCTYPE html>
  removeEmptyAttributes: true,                // Remove empty attributes
  removeEmptyElements: false,                 // Keep empty elements (for dynamic content)
  removeOptionalTags: true,                   // Remove optional HTML tags
  removeScriptTypeAttributes: true,           // Remove type="text/javascript"
  removeStyleLinkTypeAttributes: true,        // Remove type="text/css"
  minifyJS: true,                            // Minify <script> content
  minifyCSS: true                            // Minify <style> content
};

Advanced HTML Minification Options

Comment Handling

Control how comments are processed during minification.

interface CommentOptions {
  removeComments?: boolean;                   // Remove all HTML comments
  removeCommentsFromCDATA?: boolean;          // Remove comments from CDATA
  removeCDATASectionsFromCDATA?: boolean;     // Remove CDATA section markers
}

Usage:

const result = await minify.html(htmlContent, {
  html: {
    removeComments: false,              // Preserve comments for debugging
    removeCommentsFromCDATA: true,      // Clean CDATA sections
    removeCDATASectionsFromCDATA: false // Keep CDATA markers
  }
});

Whitespace and Formatting

Configure whitespace collapse and formatting behavior.

interface WhitespaceOptions {
  collapseWhitespace?: boolean;               // Collapse consecutive whitespace
  conservativeCollapse?: boolean;             // Conservative whitespace collapsing
  preserveLineBreaks?: boolean;               // Preserve line breaks
  ignoreCustomFragments?: RegExp[];           // Ignore custom patterns
}

Usage:

const result = await minify.html(htmlContent, {
  html: {
    collapseWhitespace: true,
    conservativeCollapse: false,        // Aggressive collapsing
    preserveLineBreaks: false,          // Remove all line breaks
    ignoreCustomFragments: [
      /<%[\s\S]*?%>/,                  // Preserve template tags
      /<\?[\s\S]*?\?>/                 // Preserve PHP tags
    ]
  }
});

Attribute Optimization

Configure how HTML attributes are optimized.

interface AttributeOptions {
  removeAttributeQuotes?: boolean;            // Remove quotes when safe
  removeRedundantAttributes?: boolean;        // Remove default attributes
  removeEmptyAttributes?: boolean;            // Remove empty attributes
  collapseBooleanAttributes?: boolean;        // Simplify boolean attributes
  sortAttributes?: boolean;                   // Sort attributes alphabetically
  sortClassName?: boolean;                    // Sort CSS class names
}

Usage:

const result = await minify.html(htmlContent, {
  html: {
    removeAttributeQuotes: true,        // class=btn → class=btn
    removeRedundantAttributes: true,    // Remove input type="text"
    removeEmptyAttributes: true,        // Remove empty attributes
    collapseBooleanAttributes: true,    // checked="checked" → checked
    sortAttributes: true,               // Alphabetical attribute order
    sortClassName: true                 // Sort class names
  }
});

Tag and Element Optimization

Control removal of optional tags and empty elements.

interface TagOptions {
  removeOptionalTags?: boolean;               // Remove optional HTML tags
  removeEmptyElements?: boolean;              // Remove empty elements
  removeScriptTypeAttributes?: boolean;       // Remove script type attributes
  removeStyleLinkTypeAttributes?: boolean;    // Remove style/link type attributes
  useShortDoctype?: boolean;                  // Use HTML5 doctype
}

Usage:

const result = await minify.html(htmlContent, {
  html: {
    removeOptionalTags: false,          // Keep <html>, <head>, <body>
    removeEmptyElements: false,         // Keep empty divs for JS
    removeScriptTypeAttributes: true,   // Remove type="text/javascript"
    removeStyleLinkTypeAttributes: true, // Remove type="text/css"
    useShortDoctype: true              // Use <!DOCTYPE html>
  }
});

Embedded Content Minification

Configure minification of inline JavaScript and CSS.

interface EmbeddedContentOptions {
  minifyJS?: boolean | object;                // Minify inline JavaScript
  minifyCSS?: boolean | object;               // Minify inline CSS
  minifyURLs?: boolean | object;              // Minify URLs in attributes
}

Usage:

const result = await minify.html(htmlContent, {
  html: {
    minifyJS: {                         // Custom JS minification
      mangle: false,
      compress: {
        drop_console: false
      }
    },
    minifyCSS: {                        // Custom CSS minification
      level: 1,
      compatibility: '*'
    },
    minifyURLs: true                    // Shorten URLs where possible
  }
});

HTML Processing Examples

Basic Document Minification

const document = `
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Sample Page</title>
    <style type="text/css">
      body { margin: 0; padding: 20px; }
      .header { color: blue; }
    </style>
  </head>
  <body>
    <div class="header">
      <h1>Welcome</h1>
    </div>
    <script type="text/javascript">
      console.log('Page loaded');
    </script>
  </body>
</html>
`;

const minified = await minify.html(document);
// Result: <!DOCTYPE html><html lang=en><head><meta charset=UTF-8><title>Sample Page</title><style>body{margin:0;padding:20px}.header{color:blue}</style></head><body><div class=header><h1>Welcome</h1></div><script>console.log("Page loaded")</script></body></html>

Template-Friendly Minification

const template = `
<div class="user-card">
  <%= user.name %>
  <% if (user.avatar) { %>
    <img src="<%= user.avatar %>" alt="" />
  <% } %>
</div>
`;

const minified = await minify.html(template, {
  html: {
    ignoreCustomFragments: [/<%[\s\S]*?%>/],  // Preserve template syntax
    removeEmptyAttributes: false,              // Keep empty alt attributes
    collapseWhitespace: true
  }
});

Error Handling

HTML minification handles various error conditions:

  • Invalid HTML: Malformed HTML is processed with error tolerance
  • Missing Data: Throws assertion error if data parameter is empty
  • Minifier Errors: html-minifier-next errors are propagated with context
  • Template Conflicts: Custom fragment preservation prevents template corruption

Error Examples:

// Empty data validation
try {
  const result = minify.html("");
} catch (error) {
  console.log(error); // AssertionError
}

// Malformed HTML handling
const malformed = '<div><p>Unclosed paragraph</div>';
const result = minify.html(malformed); // Processed with tolerance

// Custom configuration errors
try {
  const result = minify.html(htmlContent, {
    html: {
      invalidOption: true  // Unknown option
    }
  });
} catch (error) {
  console.log(error.message); // Configuration error
}

docs

auto-detection.md

cli-interface.md

configuration.md

css-minification.md

html-minification.md

image-processing.md

index.md

javascript-minification.md

tile.json