minify-html Python Library
minify-html is a Python binding for an extremely fast and smart HTML + JS + CSS minifier written in Rust. It offers advanced minification strategies that outperform other minifiers in both speed and effectiveness, handling invalid HTML and templating syntax. The library is actively maintained with frequent minor releases, often multiple times a month, and is currently at version 0.18.1.
Warnings
- gotcha When configuring minification options, the Python binding uses `snake_case` keyword arguments (e.g., `keep_comments=False`). Users accustomed to other language bindings (like Java's `setKeepComments(true)`) or older documentation might incorrectly try `camelCase` or `set_` prefixed methods, which will result in a `TypeError`. Always refer to the Python API documentation for the exact parameter names.
- gotcha Enabling JavaScript (`minify_js=True`) or CSS (`minify_css=True`) minification, particularly when building the package from source or in specific environments, might require the Go compiler to be installed. This is because the underlying Rust library leverages `esbuild` for JS/CSS minification via its `js-esbuild` feature. Pre-built wheels typically include this functionality, but custom installations might fail if Go is not present in the environment.
- gotcha The `minify-html` library employs an advanced, context-aware whitespace minification strategy. While this is generally highly effective, in specific edge cases where precise whitespace rendering is critical (e.g., between certain inline elements or custom components), it might remove more whitespace than anticipated.
Install
-
pip install minify-html
Imports
- minify
from minify_html import minify
Quickstart
from minify_html import minify
html_input = """
<!DOCTYPE html>
<html>
<head>
<title> Test Page </title>
<style>
body { background-color: #f0f0f0; }
h1 { color: blue; }
</style>
</head>
<body>
<!-- Main Content -->
<h1> Hello, World! </h1>
<p> This is a <span> test </span> paragraph. </p>
<script>
// Some JavaScript
function greet() {
console.log("Welcome!");
}
greet();
</script>
</body>
</html>
"""
minified_html = minify(
html_input,
keep_comments=False,
minify_css=True,
minify_js=True,
do_not_minify_doctype=True
)
print(minified_html)