A Swift HTML minification library based on JavaScriptCore and html-minifier-next.
Add CodeMirror to your project using Xcode:
- In Xcode, go to
File→Add Package Dependencies... - Enter the repository URL:
https://github.com/jaywcjlove/HTMLMinifier.git - Click
Add Package
Or add it to your Package.swift file:
dependencies: [
.package(url: "https://github.com/jaywcjlove/HTMLMinifier.git", from: "1.0.0")
]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)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)// Using default options
let result1 = try HTMLMinifier.minify(html)
// Using custom options
let result2 = try HTMLMinifier.minify(html, options: options)All options are disabled by default unless specified otherwise.
caseSensitive(default:false): Treat attributes in case sensitive manner (useful for custom HTML tags)html5(default:true): Parse input according to HTML5 specificationsincludeAutoGeneratedTags(default:true): Insert tags generated by HTML parsercontinueOnParseError(default:false): Handle parse errors instead of aborting
collapseWhitespace(default:false): Collapse white space that contributes to text nodes in a document treecollapseInlineTagWhitespace(default:false): Don't leave any spaces betweendisplay:inline;elements when collapsing (must be used withcollapseWhitespace=true)conservativeCollapse(default:false): Always collapse to 1 space (never remove it entirely). Must be used withcollapseWhitespace=truepreserveLineBreaks(default:false): Always collapse to 1 line break when whitespace between tags include a line break. Must be used withcollapseWhitespace=truetrimCustomFragments(default:false): Trim white space aroundignoreCustomFragmentsnoNewlinesBeforeTagClose(default:false): Never add a newline before a tag that closes an element
removeAttributeQuotes(default:false): Remove quotes around attributes when possiblecollapseBooleanAttributes(default:false): Omit attribute values from boolean attributesremoveEmptyAttributes(default:false): Remove all attributes with whitespace-only valuesremoveRedundantAttributes(default:false): Remove attributes when value matches defaultpreventAttributesEscaping(default:false): Prevents the escaping of the values of attributesremoveTagWhitespace(default:false): Remove space between attributes whenever possible (Note: this will result in invalid HTML!)sortAttributes(default:false): Sort attributes by frequency
removeComments(default:false): Strip HTML commentsprocessConditionalComments(default:false): Process contents of conditional comments through minifierremoveEmptyElements(default:false): Remove all elements with empty contentsremoveOptionalTags(default:false): Remove optional tags
removeScriptTypeAttributes(default:false): Removetype="text/javascript"fromscripttags. Othertypeattribute values are left intactremoveStyleLinkTypeAttributes(default:false): Removetype="text/css"fromstyleandlinktags. Othertypeattribute values are left intact
minifyJS(default:false): Minify JavaScript in script elements and event attributesminifyCSS(default:false): Minify CSS in style elements and style attributesminifyURLs(default:false): Minify URLs in various attributes
useShortDoctype(default:false): Replaces thedoctypewith the short (HTML5) doctypekeepClosingSlash(default:false): Keep the trailing slash on singleton elementsdecodeEntities(default:false): Use direct Unicode characters whenever possiblesortClassName(default:false): Sort style classes by frequency
quoteCharacter(default:nil): Type of quote to use for attribute values ("'" or """)maxInputLength(default:nil): Maximum input length to prevent ReDoS attacksmaxLineLength(default:nil): Specify a maximum line length. Compressed output will be split by newlines at valid HTML split-points
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
)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")
}Licensed under the MIT License.