Detalhes do pacote

@minify-html/node

wilsonzlin9.4kMIT0.16.4

Extremely fast and smart HTML + JS + CSS minifier

compress, compressor, fast, html

readme (leia-me)

minify-html

A Rust HTML minifier meticulously optimised for speed and effectiveness, with bindings for other languages.

View the changelog to see the latest updates.

Performance

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

Chart showing speed of HTML minifiersChart showing compression of HTML minifiers

The onepass variant is even more optimised for speed. See its README for more details.

Compatibility and usage

<summary> CLI</summary> The CLI is called minhtml. Precompiled binaries are available for Linux (ARM64 and x64), macOS (ARM64 and x64), and Windows (x64). You can download them in the GitHub release. If you have Cargo installed, you can also build and install from source: cargo install minhtml. ### Use Use the --help argument for more details. bash minhtml --output /path/to/output.min.html --keep-closing-tags --minify-css /path/to/src.html To quickly parallel process a batch of files in place: bash minhtml --keep-closing-tags --minify-css /path/to/**/*.html
<summary> Rust</summary> ### Get toml [dependencies] minify-html = "0.16.4" ### Use Check out the docs for API and usage examples.
<summary> Deno</summary> - Package: @minify-html/deno - Binding: WASM - Platforms: All ### Get Add the JSR package: deno add jsr:@minify-html/deno ### Use ts import init, {minify} from "@minify-html/deno"; const encoder = new TextEncoder(); const decoder = new TextDecoder(); await init(); const minified = decoder.decode(minify(encoder.encode("<p> Hello, world! </p>"), { keep_spaces_between_attributes: true, keep_comments: true })); All Cfg fields are available as snake_case properties on the object provided as the second argument; if any are not set, they default to false.
<summary> Node.js</summary> - Package: @minify-html/node - Binding: Neon - Platforms: Linux (ARM64 and x64), macOS (ARM64 and x64), Windows (x64); Node.js 8.6.0 and higher ### Get Using npm: bash npm i @minify-html/node Using Yarn: bash yarn add @minify-html/node ### Use TypeScript definitions are available. ts import { Buffer } from "node:buffer"; import minifyHtml from "@minify-html/node"; // Or `const minifyHtml = require("@minify-html/node")` if not using TS/ESM. const minified = minifyHtml.minify(Buffer.from("<p> Hello, world! </p>"), { keep_spaces_between_attributes: true, keep_comments: true }); All Cfg fields are available as snake_case properties on the object provided as the second argument; if any are not set, they default to false.
<summary> Java</summary> - Package: in.wilsonl.minifyhtml - Binding: JNI - Platforms: Linux (ARM64 and x64), macOS (ARM64 and x64), Windows (x64); Java 7 and higher ### Get Add as a Maven dependency: xml <dependency> <groupId>in.wilsonl.minifyhtml</groupId> <artifactId>minify-html</artifactId> <version>0.16.4</version> </dependency> ### Use java import in.wilsonl.minifyhtml.Configuration; import in.wilsonl.minifyhtml.MinifyHtml; Configuration cfg = new Configuration.Builder() .setKeepHtmlAndHeadOpeningTags(true) .setMinifyCss(true) .build(); String minified = MinifyHtml.minify("<p> Hello, world! </p>", cfg); All Cfg fields are available as camelCase setter methods on the Builder; if any are not set, they default to false.
<summary> Python</summary> - Package: minify-html - Binding: PyO3 - Platforms: Linux (ARM64 and x64), macOS (ARM64 and x64), Windows (x64); Python 3.8 to 3.13 ### Get Add the PyPI project as a dependency and install it using pip or pipenv. ### Use python import minify_html minified = minify_html.minify("<p> Hello, world! </p>", minify_js=True, remove_processing_instructions=True) All Cfg fields are available as Python keyword arguments; if any are omitted, they default to False.
<summary> Ruby</summary> - Package: minify_html - Binding: rb-sys and magnus - Platforms: Linux (ARM64 and x64), macOS (ARM64 and x64), Windows (x64); Ruby 2.7 to 3.4 ### Get Add the library as a dependency to Gemfile or *.gemspec. ### Use ruby require 'minify_html' print minify_html("<p> Hello, world! </p>", { :keep_spaces_between_attributes => true, :minify_js => true }) All Cfg fields are available; if any are omitted, they default to false.
<summary> WASM</summary> - Package: @minify-html/wasm - Binding: WASM - Platforms: All A bundler may be required to use the WebAssembly module, see this for more details. ### Use ts import init, {minify} from "@minify-html/wasm"; const encoder = new TextEncoder(); const decoder = new TextDecoder(); await init(); const minified = decoder.decode(minify(encoder.encode("<p> Hello, world! </p>"), { keep_spaces_between_attributes: true, keep_comments: true })); All Cfg fields are available as snake_case properties on the object provided as the second argument; if any are not set, they default to false.

Templating syntax

minify-html can parse and preserve {{/{%/{# and <% syntax in the source code, which allows minification of many HTML templates written for most engines like Pebble, Mustache, Django, Go, Jinja, Twix, Nunjucks, Handlebars, Sailfish, JSP, EJS, and ERB. Look for the preserve_*_template_syntax Cfg options.

PHP blocks (<?php or <?=) also happen to be processing instructions, which are preserved by default.

Note that in all of these syntax, the parsing is "dumb": it will simply look for the next subsequence of characters that match the closing delimiter. This may cause issues if nesting or string literals appear inside these blocks, but this should be rare.

Minification

Spec compliance

WHATWG is the current HTML standard and obsoletes all previous standards. WHATWG lists suggested validators here.

To minify even further, it's possible to enable options that may output HTML that doesn't fully pass validation, but is still interpreted and rendered correctly according to the WHATWG parsing specification, which major browser engines (Firefox, Chrome, Safari) implement. Refer to these options:

  • allow_noncompliant_unquoted_attribute_values
  • allow_optimal_entities
  • allow_removing_spaces_between_attributes
  • minify_doctype

In Rust, Cfg::enable_possibly_noncompliant can enable all of these at once.

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.

<summary>Collapse whitespace</summary> > Applies to: any element except whitespace sensitive elements. Reduce a sequence of whitespace characters in text nodes to a single space (U+0020).
BeforeAfter
html <p>↵ ··The·quick·brown·fox↵ ··jumps·over·the·lazy↵ ··dog.↵ </p> html <p>·The·quick·brown·fox·jumps·over·the·lazy·dog.·</p>
<summary>Destroy whole whitespace</summary> > 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
html <ul>↵ ··<li>A</li>↵ ··<li>B</li>↵ ··<li>C</li>↵ </ul> html <ul>↵ ··<li>A</li><li>B</li><li>C</li>↵ </ul>
<summary>Trim whitespace</summary> > 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
html <p>↵ ··Hey,·I·<em>just</em>·found↵ ··out·about·this·<strong>cool</strong>·website!↵ ··<sup>[1]</sup>↵ </p> html <p>Hey,·I·<em>just</em>·found↵ ··out·about·this·<strong>cool</strong>·website!↵ ··<sup>[1]</sup></p>

Element types

minify-html assumes HTML and SVG elements are used in specific ways, based on standards and best practices. By making these assumptions, it can apply optimal whitespace minification strategies. If these assumptions do not hold, consider adjusting the HTML source or turning off whitespace minification.

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.
<summary>Formatting elements</summary> > 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.
<summary>Content elements</summary> > 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 html <p>↵ ··Hey,·I·<em>just</em>·found↵ ··out·about·this·<strong>cool</strong>·website!↵ ··<sup>[1]</sup>↵ </p> ###### After html <p>Hey,·I·<em>just</em>·found·out·about·this·<strong>cool</strong>·website!·<sup>[1]</sup></p>
<summary>Layout elements</summary> > 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 html <ul>↵ ··<li>A</li>↵ ··<li>B</li>↵ ··<li>C</li>↵ </ul> ###### After html <ul><li>A</li><li>B</li><li>C</li></ul>
<summary>Content-first elements</summary> > 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 html <li>↵ ··<article>↵ ····<section></section>↵ ····<section></section>↵ ··</article>↵ </li> ###### After html <li><article><section></section><section></section></article></li>

Tags

Optional opening and 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), any >, and any whitespace encoded.

Attributes have their whitespace (after any decoding) trimmed and collapsed when possible.

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 when possible.

Entities

Entities are decoded if they're valid and shorter or equal in length when decoded. UTF-8 sequences that have a shorter entity representation are encoded.

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

Encoding is avoided when possible; for example, < are only encoded in content if they are followed by a valid tag name character. If necessary, the shortest entity representation is chosen.

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

minify-html can process any HTML, handling all possible syntax (including invalid ones) gracefully like browsers. See Parsing.md for more details.

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.

changelog (log de mudanças)

minify-html changelog

0.16.4

  • Fix macOS label for GitHub Actions.

0.16.3

  • Bump macOS version for GitHub Actions.

0.16.2

  • Fix Node.js builds.
  • Fix Deno builds.

0.16.1

  • Fix Node.js builds.
  • Fix Deno builds.

0.16.0

  • BREAKING: Cfg options have changed such that spec compliance is the default, to avoid confusion with users:
    • do_not_minify_doctype => minify_doctype
    • ensure_spec_compliant_unquoted_attribute_values => allow_noncompliant_unquoted_attribute_values
    • keep_spaces_between_attributes => allow_removing_spaces_between_attributes
    • Cfg::spec_compliant() => Cfg::enable_possibly_noncompliant(&mut self)
  • BREAKING: Some entity minifications are now classified as "possibly noncompliant" and can be enabled via the allow_optimal_entities option but won't be performed by default.
  • [Internal] Migrate to aHash for faster more consistent performance and once_cell for modern ergonomics.
  • [Internal] Downgrade aho-corasick to 0.7 temporarily to support minify-js.
  • [Node.js] Fix ARM64 package metadata.
  • [Python] Add Python 3.13 support.
  • [Ruby] Add Ruby 3.3/3.4 support.
  • [Deno] Publish to JSR.
  • [Rust] Deny unsafe code in minify-html crate.

0.15.0

  • Add keep_input_type_text_attr option to keep type=text on <input> elements.
  • [Java] The Configuration class constructor has been made private to enforce the use of the builder. The constructor has a lot of params which can easily cause bugs due to ordering and confusion.

0.14.0

  • Add new options to parse and preserve common templating syntax in content source code. NOTE: The parsing is "dumb" and merely looks for the next subsequence in the source code that matches the closing delimiter characters. This means that literal closing delimiter characters (e.g. strings) and nesting may cause parsing to be incorrect.
    • preserve_brace_template_syntax: When {{, {#, or {% are seen in content, all source code until the subsequent matching closing }}, #}, or %} respectively gets piped through untouched.
      • Templating engines: Pebble, Mustache, Django, Go, Jinja, Twix, Nunjucks, Handlebars, Liquid.
    • preserve_chevron_percent_template_syntax: When <% is seen in content, all source code until the subsequent matching closing %> gets piped through untouched.
      • Templating engines: Sailfish, JSP, EJS, ERB.

0.13.3

  • Avoid downloading html-data JSON from network on build.

0.13.2

  • [Java] Set up cross compilation for macOS and Linux ARM64 builds.

0.13.1

  • [CLI] Add missing Cargo metadata.

0.13.0

  • Use lightningcss instead of css-minify, which is better maintained.
    • BREAKING: The minify_css_level_* Cfg options no longer apply and have been removed.
  • [onepass] Implement Display and Error for Error and FriendlyError structs.

0.12.0

  • Change CLI name to minhtml as it's a more concise command name and allows for cargo install minhtml.
  • Add keep_ssi_comments to preserve SSI comments.
  • [Ruby] BREAKING: The class method is now a global function, so call minify_html instead of MinifyHtml.minify. All else remains the same. This is due to migrating from Rutie (see 0.11.3).
    • This change was inadvertently released in patch version bumps from 0.11.3 to 0.11.5; these gems have been yanked.

0.11.5

  • Omit Rust source files from Node.js package.

0.11.4

  • Bump minify-js version.
  • Fix Node.js native package names.

0.11.3

  • Fix detection of module type scripts.
  • Derive Clone for Cfg in minify-html.
  • Fix parsing of malformed closing tags.
  • Cross compile Python library for macOS ARM64.
  • Migrate to rb-sys and magnus for Ruby library, which adds support for up to Ruby 3.2 and more platforms.
  • Cross compile Node.js library for macOS ARM64.
  • Use optional dependencies instead of downloading from remote server for Node.js library.

0.11.2

  • Build and release for Python 3.12.
  • Restructure project to use top-level Cargo workspace instead of separate isolated crates.
  • Extract out common Rust code to separate published shared crate instead of symlinking.
  • Port gen code to build.rs in common Rust library to avoid requiring Node.js in order to build, and to ensure code stays in sync.
  • Rename library folders to minify-html-* to better distinguish them from other assorted project code.

0.11.1

  • Bump GitHub Actions Ubuntu image version.

0.11.0

  • Change the default CSS minifier optimisation level to 1, as higher levels may perform dangerous optimisations.
  • Allow configuring the CSS minifier optimisation level.
  • Fix building from source in Node.js postinstall.js script.

0.10.8

  • [Node.js] Fix assertion failure panic on invalid argument type.
  • Do not consider empty href attributes as redundant.

0.10.7

0.10.6

  • Improve handling of RCDATA text content in edge cases.

0.10.5

  • Do not encode entities in RCDATA text content (e.g. contents of <textarea> and <title>).

0.10.4

  • Use FxHasher for internal hash-based data structures.
  • Bump css-minify to 0.3.1.
  • [WASM] Add type and main fields to package.json.
  • [Node.js] Improve invalid argument type error messages.

0.10.3

  • [Python] Add Python 3.11 support.
  • [Python] Build source distribution wheels that will compile on install when prebuilt variants are not available. The Rust compiler must be available.

0.10.2

0.10.1

  • Bump minify-js to 0.2.
  • Minify JS as module instead of global script if type is module.

0.10.0

  • Drop unmatched closing tags instead of reinterpreting them as opening tags. This avoids the possibility of unintentionally creating a large deep tree due to malformed inputs where there are repeated unmatched closing tags (e.g. broken HTML template).
  • Fix parallel minification in CLI mode, where some inputs were ignored.
  • Output file names as they're processed in parallel mode from the CLI.
  • Allow self-closing <svg> tags.
  • Drop support for macOS ARM64 due to lack of GitHub Actions runners.

0.9.2

  • Fix Node.js dependency version.
  • Create onepass variant for Python.
  • Bump minify-js to 0.1.1.
  • Implement parallel in-place minification for CLI.

0.9.1

  • Fix Node.js postinstall script.

0.9.0

  • Replace esbuild with minify-js as the JS minifier, a fast minifier written from scratch in Rust. This alleviates many of the problems with integrating with esbuild, including interference with process signals by the Go runtime, compatibility issues with C libraries other than glibc, use of threading libraries without actually threading, inability to compile to rarer Rust targets, dependency on the Go compiler, maintaining a fork of esbuild, unsafe FFI, and more. CSS minification is now done by css-minify.
    • As minify-js is a relatively new library, any feedback, suggestions, and issues around JS minification is most welcome! Please report them to the repo.
  • Use Neon for the Node.js library instead of custom hand-written N-API bindings in C. This simplifies the code and makes it safer and easier to extend. It also allows building from source if a prebuilt binary is not available (the Rust compiler must be installed).
    • The package has been renamed to @minify-js/node.
    • There is a slight API change: instead of calling createConfiguration, directly pass the JavaScript object to the minify function. The minify function also no longer takes a string.
  • Thanks to the change to the fully-Rust minify-js, we can now add support for Deno and WebAssembly.
  • Due to the dropping of esbuild, there is no more core variant for Node.js and Python, as the issues should no longer exist.

0.8.1

  • Create wrapper index.js for Node.js library to support ESM.
  • Do not consider empty value attributes on option elements as redundant.
  • Consider crossorigin attributes as boolean.

0.8.0

  • Minify whitespace in SVG elements.

0.7.2

  • Fix Node.js library build process on Windows.

0.7.1

  • Do not remove alt attribute when empty.

0.7.0

  • Fix Node.js library not including cli.js.
  • [CLI] Add support for macOS ARM64.
  • [Node.js] Add support for macOS ARM64.
  • [Python] Add support for Linux ARM64 and macOS ARM64. Drop support for Python 3.7 (breaking change).

0.6.10

  • Fix the Node.js library TypeScript definitions. minifyJs has been fixed to minify_js and minifyCss has been fixed to minify_css. This is not a breaking change the library itself only ever accepted the fixed names, so this is actually a typo fix.
  • Implement a basic CLI script for Node.js to allow using the library from the command line e.g. quick testing or sandboxing without needing to download and install the CLI separately. It accepts all configuration properties (all of which are currently booleans) using hyphen case e.g. --do-not-minify-doctype, as well as --output [path] and one default (i.e. not after an option switch) argument for the path to the input. It's only a few lines long and should not have a tangible effect on library size.

0.6.9

  • Intrepret type=module on <script> tags as a JavaScript MIME eligible for its contents to be minified as JavaScript (previously it would not be and so its contents would be considered data and never minified as JavaScript).
  • Fix issue where spaces are not added between unquoted attributes even when cfg.keep_spaces_between_attributes is true.