minify-html

repository·master·Indexed 22 days ago

https://github.com/wilsonzlin/minify-html

A high-performance Rust-based HTML minifier that supports JS and CSS minification via oxc and lightningcss. It provides a CLI tool (minhtml), a standard library, and a high-speed one-pass variant (minify-html-onepass). Bindings are available for Rust, Node.js, Python, Java, Ruby, Deno, and WASM. The tool supports advanced strategies such as preserving templating syntax, handling invalid HTML, and offering both spec-compliant and non-compliant optimization levels.

Tokens
21K
Snippets
65
Records
84
Agent score
78%

What's inside minify-html

  1. Overview of minify-html-onepass

    master

    minify-html-onepass is a high-performance HTML minifier designed to provide the same advanced minification strategies as the standard minify-html library, but with significantly higher speed.

    Key characteristics include:

    • One-pass minification: Processes the HTML in a single pass.
    • Zero memory allocations: Optimized for minimal memory overhead.
    • In-place output: Minifies directly without requiring additional copies or buffers.

    Note that this variant is optimized for speed at the cost of being less configurable and having stricter parsing requirements than the original minify-html.

  2. How attribute minification works

    master

    The minifier optimizes attributes using the following rules:

    • Shortest Representation: Decodes entities in attribute values and then selects the shortest possible representation (Double quoted, Single quoted, or Unquoted).
    • Boolean Attributes: Values for boolean attributes are removed.
    • Empty/Default Attributes: Some attributes are completely removed if their value is empty or matches the default after processing.
    • Script Types: type attributes on <script> tags with JavaScript MIME types are removed.
    • Empty Attribute Names: If an attribute value is empty after processing, the name is kept but the = is removed (e.g., attr="" becomes attr).
    • Whitespace: Spaces between attributes are removed where possible.
  3. How entity minification works

    master

    The minifier optimizes HTML entities using these rules:

    • Decoding: Entities are decoded if the decoded version is valid and shorter than or equal to the original length.
    • Encoding: UTF-8 sequences that have a shorter entity representation are encoded.
    • Unicode Safety: Numeric entities referring to invalid Unicode Scalar Values are replaced with the replacement character.
    • Selective Encoding: < is only encoded in content if it is followed by a valid tag name character. Otherwise, the shortest entity representation is chosen.
  4. Understand minify-html parsing behavior and limitations

    master

    Core Parsing Philosophy

    minify-html does not have error states and will always output a value. It attempts to match HTML5 specifications and modern browser behavior, but may differ from browsers when handling highly complex malformed syntax.

    Input Limitations

    • Encoding: Input must be valid UTF-8 without BOM.
    • Spec: All HTML is interpreted as HTML5.
    • Script Content: Escaped and double-escaped script content is not supported.

    EOF (End of File) Handling

    If the input ends while in the middle of a tag or an attribute value, minify-html will automatically close that tag/attribute and all its ancestor tags.

  5. Preserve templating syntax during minification

    master

    The minifier can parse and preserve various templating syntaxes, including {{, {%, {#, and <%. This allows you to minify HTML files used by engines like Mustache, Django, Jinja, Handlebars, EJS, and others.

    To enable this, use the preserve_*_template_syntax Cfg options.

    Note: PHP blocks (<?php or <?=) are treated as processing instructions and are preserved by default. The parsing for these syntaxes is 'dumb' (matching the next closing delimiter), which may cause issues with complex nesting or string literals inside the blocks.

  6. Handling of script data and nested script tags in minify-html

    master

    By design, minify-html does not support the legacy HTML behavior where an HTML comment containing a <script token prevents the first following </script> from closing the main script tag.

    In standard legacy HTML parsing, if a <script appears inside a comment within a script block, the parser enters a special state where it ignores </script> tags until it finds a matching closing sequence. minify-html omits this logic to maintain high performance and reduce complexity, as this legacy behavior is rarely used and not recommended.

    Implication for users: If your HTML relies on nesting <script> tags inside comments within a <script> block to prevent premature closing of the main tag, minify-html may not preserve that specific parsing edge case during minification.

  7. Parsing requirements for minify-html-onepass

    master

    Because minify-html-onepass is optimized for performance, it enforces stricter parsing rules than the standard minify-html. To ensure successful minification, your input HTML must adhere to the following requirements in addition to the standard minify-html rules:

    • No omitted opening tags: All opening tags must be explicitly present.
    • No invalid closing tags: Closing tags must be syntactically correct and valid.
    • No unexpected document endings: The document must not end abruptly or unexpectedly.
  8. How whitespace minification works

    master

    The minifier uses context-aware whitespace strategies based on the type of HTML element being processed. It distinguishes between whitespace-sensitive elements (like pre and code) and others to ensure layout and content integrity.

    Whitespace Minification Methods

    1. Collapse whitespace: Reduces a sequence of whitespace characters in text nodes to a single space (U+0020). Applies to any element except whitespace-sensitive ones.
    2. Destroy whole whitespace: Removes text nodes that consist entirely of whitespace characters between tags. Applies to any element except whitespace-sensitive, content, content-first, or formatting elements.
    3. Trim whitespace: Removes leading and trailing whitespace from text nodes within a tag. Applies to any element except whitespace-sensitive and formatting elements.

    Element Group Assumptions

    minify-html applies different strategies based on these element groups:

    GroupElementsExpected ChildrenWhitespace Strategy
    Formattinga, strong, etc.Formatting elements, textCollapsed
    Contenth1, p, etc.Formatting elements, textTrimmed and Collapsed
    Layoutdiv, ul, etc.Layout elements, content elementsTrimmed, Collapsed, and Whole Whitespace Removed
    Content-firstlabel, li, etc.Like content but can be layoutTrimmed and Collapsed
  9. Canonicalize HTML using the c14n tool

    master

    The c14n tool parses HTML from stdin and writes a canonicalized version to stdout. This is primarily used to preprocess HTML documents for consistent diffing by normalizing the structure and encoding.

    Canonicalization performs the following transformations:

    • Sorts all attributes by name.
    • Decodes all entities, then re-encodes only special characters consistently.
    • Converts all tag and attribute names to lowercase.
    # Example usage via pipe
    cat input.html | c14n > output.html
  10. Use charlines for subsequence diffing of minified text

    master
    The charlines utility outputs every character from stdin onto its own line in stdout. This is specifically useful for performing subsequence diffs on text that lacks natural line breaks, such as minified HTML, where standard line-based diffing tools would fail to show granular changes.
  11. Use minify-html in Rust

    master

    Add minify-html as a dependency in your Cargo.toml to use the library directly in your Rust projects. For detailed API documentation and usage examples, refer to the official docs.rs page.

    [dependencies]
    minify-html = "0.18.1"
  12. Install minify-html-onepass for Python or Rust

    master

    You can use minify-html-onepass in Python or Rust via their respective package managers. Refer to the specific package documentation for detailed API usage.

    Python Install via PyPI:

    pip install minify-html-onepass

    Rust Add to your Cargo.toml via crates.io:

    minify-html-onepass = "0.18.1" # Use the latest version
    pip install minify-html-onepass