Contents

jaywcjlove/htmlminifier

HTMLMinifier

Installation

Swift Package Manager

Add CodeMirror to your project using Xcode:

  1. In Xcode, go to FileAdd Package Dependencies...
  2. Enter the repository URL: https://github.com/jaywcjlove/HTMLMinifier.git
  3. Click Add Package

Or add it to your Package.swift file:

dependencies: [
    .package(url: "https://github.com/jaywcjlove/HTMLMinifier.git", from: "1.0.0")
]

Usage

Basic Usage

import HTMLMinifier

let html = """
<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <p class="test">  Hello World  </p>
    <!-- This is a comment -->
</body>
</html>
"""

// Using default options
let minified = try HTMLMinifier.minify(html)
print(minified)

Custom Options

import HTMLMinifier

let options = HTMLMinifierOptions(
    removeComments: true,
    collapseWhitespace: true,
    removeAttributeQuotes: true,
    useShortDoctype: true
)

let minifier = try HTMLMinifier()
let result = try minifier.minify(html, options: options)

Static Methods

// Using default options
let result1 = try HTMLMinifier.minify(html)

// Using custom options
let result2 = try HTMLMinifier.minify(html, options: options)

Available Options

All options are disabled by default unless specified otherwise.

Core Options

  • caseSensitive (default: false): Treat attributes in case sensitive manner (useful for custom HTML tags)
  • html5 (default: true): Parse input according to HTML5 specifications
  • includeAutoGeneratedTags (default: true): Insert tags generated by HTML parser
  • continueOnParseError (default: false): Handle parse errors instead of aborting

Whitespace & Formatting

  • collapseWhitespace (default: false): Collapse white space that contributes to text nodes in a document tree
  • collapseInlineTagWhitespace (default: false): Don't leave any spaces between display:inline; elements when collapsing (must be used with collapseWhitespace=true)
  • conservativeCollapse (default: false): Always collapse to 1 space (never remove it entirely). Must be used with collapseWhitespace=true
  • preserveLineBreaks (default: false): Always collapse to 1 line break when whitespace between tags include a line break. Must be used with collapseWhitespace=true
  • trimCustomFragments (default: false): Trim white space around ignoreCustomFragments
  • noNewlinesBeforeTagClose (default: false): Never add a newline before a tag that closes an element

Attributes

  • removeAttributeQuotes (default: false): Remove quotes around attributes when possible
  • collapseBooleanAttributes (default: false): Omit attribute values from boolean attributes
  • removeEmptyAttributes (default: false): Remove all attributes with whitespace-only values
  • removeRedundantAttributes (default: false): Remove attributes when value matches default
  • preventAttributesEscaping (default: false): Prevents the escaping of the values of attributes
  • removeTagWhitespace (default: false): Remove space between attributes whenever possible (Note: this will result in invalid HTML!)
  • sortAttributes (default: false): Sort attributes by frequency

Comments & Elements

  • removeComments (default: false): Strip HTML comments
  • processConditionalComments (default: false): Process contents of conditional comments through minifier
  • removeEmptyElements (default: false): Remove all elements with empty contents
  • removeOptionalTags (default: false): Remove optional tags

Type Attributes

  • removeScriptTypeAttributes (default: false): Remove type="text/javascript" from script tags. Other type attribute values are left intact
  • removeStyleLinkTypeAttributes (default: false): Remove type="text/css" from style and link tags. Other type attribute values are left intact

Content Minification

  • minifyJS (default: false): Minify JavaScript in script elements and event attributes
  • minifyCSS (default: false): Minify CSS in style elements and style attributes
  • minifyURLs (default: false): Minify URLs in various attributes

Document Structure

  • useShortDoctype (default: false): Replaces the doctype with the short (HTML5) doctype
  • keepClosingSlash (default: false): Keep the trailing slash on singleton elements
  • decodeEntities (default: false): Use direct Unicode characters whenever possible
  • sortClassName (default: false): Sort style classes by frequency

Advanced Options

  • quoteCharacter (default: nil): Type of quote to use for attribute values ("'" or """)
  • maxInputLength (default: nil): Maximum input length to prevent ReDoS attacks
  • maxLineLength (default: nil): Specify a maximum line length. Compressed output will be split by newlines at valid HTML split-points

Example with Common Options

let options = HTMLMinifierOptions(
    removeComments: true,
    collapseWhitespace: true,
    removeAttributeQuotes: true,
    collapseBooleanAttributes: true,
    removeEmptyAttributes: true,
    removeRedundantAttributes: true,
    removeScriptTypeAttributes: true,
    removeStyleLinkTypeAttributes: true,
    useShortDoctype: true,
    minifyJS: true,
    minifyCSS: true
)

Error Handling

do {
    let result = try HTMLMinifier.minify(html)
    print(result)
} catch HTMLMinifierError.jsContextCreationFailed {
    print("Failed to create JavaScript context")
} catch HTMLMinifierError.jsScriptLoadFailed(let message) {
    print("JavaScript script loading failed: \(message)")
} catch HTMLMinifierError.minificationFailed(let message) {
    print("Minification failed: \(message)")
} catch HTMLMinifierError.invalidInput {
    print("Invalid input")
}

License

Licensed under the MIT License.

Package Metadata

Repository: jaywcjlove/htmlminifier

Default branch: main

README: README.md