8 releases

0.3.5 Jul 30, 2020
0.3.4 Jul 29, 2020
0.2.6 Jul 11, 2020

#57 in Build Utils

38 downloads per month

MIT license

2MB
48K SLoC

minify-html

An HTML minifier meticulously optimised for both speed and effectiveness, available for Rust, Node.js, Python, Java, and Ruby.

  • Advanced minification strategy beats other minifiers with only one pass.
  • Uses zero memory allocations, SIMD searching, direct tries, and lookup tables.
  • Well tested with a large test suite and extensive fuzzing.
  • Natively binds to esbuild for super fast JS minification.

Performance

Comparison with html-minfier and minimize, run on the top web pages. See the breakdown here.

Chart showing speed of HTML minifiers Chart showing effectiveness of HTML minifiers

Usage

CLI

Precompiled binaries are available for x86-64 Linux, macOS, and Windows.

Get

Linux | macOS | Windows

Use

Use the --help argument for more details.

minify-html --src /path/to/src.html --out /path/to/output.min.html

API

Rust
Get
[dependencies]
minify-html = { version = "0.3.5", features = ["js-esbuild"] }

Building with the js-esbuild feature requires the Go compiler to be installed as well, to build the JS minifier.

If the js-esbuild feature is not enabled, cfg.minify_js will have no effect.

Use
use minify_html::{Cfg, Error, FriendlyError, in_place, copy, with_friendly_error, truncate};

fn main() {
    let mut code = b"<p>  Hello, world!  </p>".to_vec();
    let cfg = &Cfg {
        minify_js: false,
    };

    // Minifies a slice in-place and returns the new minified length,
    // but leaves any original code after the minified code intact.
    match in_place(&mut code, cfg) {
        Ok(minified_len) => {}
        Err(Error { error_type, position }) => {}
    };

    // Creates a vector copy containing only minified code
    // instead of minifying in-place.
    match copy(&code, cfg) {
        Ok(minified) => {}
        Err(Error { error_type, position }) => {}
    };

    // Minifies a vector in-place, and then truncates the
    // vector to the new minified length.
    match truncate(&mut code, cfg) {
        Ok(()) => {}
        Err(Error { error_type, position }) => {}
    };

    // Identical to `in_place` except with FriendlyError instead.
    // `code_context` is a string of a visual representation of the source,
    // with line numbers and position markers to aid in debugging syntax.
    match with_friendly_error(&mut code, cfg) {
        Ok(minified_len) => {}
        Err(FriendlyError { position, message, code_context }) => {
            eprintln!("Failed at character {}:", position);
            eprintln!("{}", message);
            eprintln!("{}", code_context);
        }
    };
}
Node.js
  • Package: @minify-html/js
  • Binding: N-API
  • Platforms: Linux, macOS, Windows; Node.js 8.6.0 and higher
Get

Using npm:

npm i @minify-html/js

Using Yarn:

yarn add @minify-html/js
Use
const minifyHtml = require("@minify-html/js");

const cfg = minifyHtml.createConfiguration({ minifyJs: false });
const minified = minifyHtml.minify("<p>  Hello, world!  </p>", cfg);

// Alternatively, minify in place to avoid copying.
const source = Buffer.from("<p>  Hello, world!  </p>");
// This is a Buffer representing a slice of `source`, not newly allocated memory.
const minified = minifyHtml.minifyInPlace(source, cfg);

minify-html is also available for TypeScript:

import * as minifyHtml from "@minify-html/js";
import * as fs from "fs";

const cfg = minifyHtml.createConfiguration({ minifyJs: false });
const minified = minifyHtml.minify("<p>  Hello, world!  </p>", cfg);
// Or alternatively:
const minified = minifyHtml.minifyInPlace(fs.readFileSync("source.html"), cfg);
Java
Get

Add as a Maven dependency:

<dependency>
  <groupId>in.wilsonl.minifyhtml</groupId>
  <artifactId>minify-html</artifactId>
  <version>0.3.5</version>
</dependency>
Use
import in.wilsonl.minifyhtml.MinifyHtml;

MinifyHtml.Configuration cfg = new MinifyHtml.Configuration.Builder()
    .setMinifyJs(false)
    .build();
try {
    String minified = MinifyHtml.minify("<p>  Hello, world!  </p>", cfg);
} catch (MinifyHtml.SyntaxException e) {
    System.err.println(e.getMessage());
}

// Alternatively, minify in place:
assert source instanceof ByteBuffer && source.isDirect();
MinifyHtml.minifyInPlace(source, cfg);
Python
  • Package: minify-html
  • Binding: PyO3
  • Platforms: Linux, macOS, Windows; Python 3.5 and higher
Get

Add the PyPI project as a dependency and install it using pip or pipenv.

Use
import minify_html

try:
    minified = minify_html.minify("<p>  Hello, world!  </p>", minify_js=False)
except SyntaxError as e:
    print(e)
Ruby
  • Package: minify_html
  • Binding: Rutie
  • Platforms: Linux, macOS; Ruby 2.5 and higher
Get

Add the library as a dependency to Gemfile or *.gemspec.

Use
require 'minify_html'

print MinifyHtml.minify("<p>  Hello, world!  </p>", { :minify_js => false })

Minification

Whitespace

minify-html has advanced context-aware whitespace minification that does things such as:

  • Leave whitespace untouched in pre and code, which are whitespace sensitive.
  • Trim and collapse whitespace in content tags, as whitespace is collapsed anyway when rendered.
  • Remove whitespace in layout tags, which allows the use of inline layouts while keeping formatted code.

Methods

There are three whitespace minification methods. When processing text content, minify-html chooses which ones to use depending on the containing element.

Collapse whitespace

Applies to: any element except whitespace sensitive elements.

Reduce a sequence of whitespace characters in text nodes to a single space (U+0020).

BeforeAfter
<p>↵
··The·quick·brown·fox↵
··jumps·over·the·lazy↵
··dog.↵
</p>
<p>·The·quick·brown·fox·jumps·over·the·lazy·dog.·</p>
Destroy whole whitespace

Applies to: any element except whitespace sensitive, content, content-first, and formatting elements.

Remove any text nodes between tags that only consist of whitespace characters.

BeforeAfter
<ul>↵
··<li>A</li>↵
··<li>B</li>↵
··<li>C</li></ul>
<ul>↵
··<li>A</li><li>B</li><li>C</li></ul>
Trim whitespace

Applies to: any element except whitespace sensitive and formatting elements.

Remove any leading/trailing whitespace from any leading/trailing text nodes of a tag.

BeforeAfter
<p>↵
··Hey,·I·<em>just</em>·found↵
··out·about·this·<strong>cool</strong>·website!↵
··<sup>[1]</sup></p>
<p>Hey,·I·<em>just</em>·found↵
··out·about·this·<strong>cool</strong>·website!↵
··<sup>[1]</sup></p>

Element types

minify-html recognises elements based on one of a few ways it assumes they are used. By making these assumptions, it can apply optimal whitespace minification strategies.

Group Elements Expected children
Formatting a, strong, and others Formatting elements, text.
Content h1, p, and others Formatting elements, text.
Layout div, ul, and others Layout elements, content elements.
Content-first label, li, and others Like content but could be layout with only one child.
Formatting elements

Whitespace is collapsed.

Formatting elements are usually inline elements that wrap around part of some text in a content element, so its whitespace isn't trimmed as they're probably part of the content.

Content elements

Whitespace is trimmed and collapsed.

Content elements usually represent a contiguous and complete unit of content such as a paragraph. As such, whitespace is significant but sequences of them are most likely due to formatting.

Before
<p>↵
··Hey,·I·<em>just</em>·found↵
··out·about·this·<strong>cool</strong>·website!↵
··<sup>[1]</sup></p>
After
<p>Hey,·I·<em>just</em>·found·out·about·this·<strong>cool</strong>·website!·<sup>[1]</sup></p>
Layout elements

Whitespace is trimmed and collapsed. Whole whitespace is removed.

These elements should only contain other elements and no text. This makes it possible to remove whole whitespace, which is useful when using display: inline-block so that whitespace between elements (e.g. indentation) does not alter layout and styling.

Before
<ul>↵
··<li>A</li>↵
··<li>B</li>↵
··<li>C</li></ul>
After
<ul><li>A</li><li>B</li><li>C</li></ul>
Content-first elements

Whitespace is trimmed and collapsed.

These elements are usually like content elements but are occasionally used like a layout element with one child. Whole whitespace is not removed as it might contain content, but this is OK for using as layout as there is only one child and whitespace is trimmed.

Before
<li>↵
··<article>↵
····<section></section>↵
····<section></section>↵
··</article></li>
After
<li><article><section></section><section></section></article></li>

Tags

Optional closing tags are removed.

Attributes

Any entities in attribute values are decoded, and then the shortest representation of the value is calculated and used:

  • Double quoted, with any " encoded.
  • Single quoted, with any ' encoded.
  • Unquoted, with "/' first character (if applicable), > last character (if applicable), and any whitespace encoded.

class and d attributes have their whitespace (after any decoding) trimmed and collapsed.

Boolean attribute values are removed. Some other attributes are completely removed if their value is empty or the default value after any processing.

type attributes on script tags with a value equaling a JavaScript MIME type are removed.

If an attribute value is empty after any processing, everything but the name is completely removed (i.e. no =), as an empty attribute is implicitly the same as an attribute with an empty string value.

Spaces are removed between attributes if possible.

Entities

Entities are decoded if they're valid and shorter or equal in length when decoded.

Numeric entities that do not refer to a valid Unicode Scalar Value are replaced with the replacement character.

If an entity is unintentionally formed after decoding, the leading ampersand is encoded, e.g. &&#97;&#109;&#112;; becomes &ampamp;. This is done as &amp is equal to or shorter than all other entity representations of characters part of an entity ([&#a-zA-Z0-9;]), and there is no other conflicting entity name that starts with amp.

It's possible to get an unintentional entity after removing comments, e.g. &am<!-- -->p.

Left chevrons after any decoding in text are encoded to &LT if possible or &LT; otherwise.

Comments

Comments are removed.

Ignored

Bangs, processing instructions, and empty elements are not removed as it is assumed there is a special reason for their declaration.

Parsing

Only UTF-8/ASCII-encoded HTML code is supported.

minify-html does no syntax checking or standards enforcement for performance and code complexity reasons.

For example, this means that it's not an error to have self-closing tags, declare multiple <body> elements, use incorrect attribute names and values, or write something like <br>alert('');</br>

However, there are some syntax requirements for speed and sanity.

Tags

Opening tags must not be omitted.

Script and style

minify-html does not handle escaped and double-escaped script content.

Issues and contributions

Pull requests and any contributions welcome!

If minify-html did something unexpected, misunderstood some syntax, or incorrectly kept/removed some code, raise an issue with some relevant code that can be used to reproduce and investigate the issue.

Dependencies

~0.5–0.9MB
~17K SLoC