cssmin - YUI CSS Compressor
A Python port of the YUI CSS compression algorithm, providing minification for CSS files. The library is currently at version 0.2.0 and has seen minimal updates recently, suggesting a stable but slow release cadence. It aims to replicate the functionality of the original YUI Compressor for CSS.
Common errors
-
ModuleNotFoundError: No module named 'cssmin'
cause The `cssmin` package is not installed in your current Python environment.fixInstall the package using pip: `pip install cssmin` -
AttributeError: module 'cssmin' has no attribute 'compress'
cause You are attempting to call a non-existent compression function. The primary function for minification in the `cssmin` library is `cssmin.cssmin()`.fixUse the correct function name: `minified_css = cssmin.cssmin(css_string)` -
TypeError: expected string or bytes-like object, os.PathLike object given
cause You are trying to pass a file path (or a `Path` object) directly to `cssmin.cssmin()` instead of the actual CSS content from the file.fixRead the content of your CSS file into a string first, then pass the string to the minifier: ```python with open('your_style.css', 'r') as f: css_content = f.read() minified_css = cssmin.cssmin(css_content) ```
Warnings
- gotcha The `cssmin` library is based on the YUI CSS compression algorithm, which was last updated in 2011. This means it may not fully support modern CSS features (e.g., custom properties/variables, `calc()`, newer pseudo-classes, grid/flexbox syntax) introduced after this period. Using it with complex, modern CSS might lead to incorrect minification, malformed output, or outright errors.
- gotcha The `cssmin` library has not been actively maintained since 2021. While it remains stable for its intended purpose, this lack of active development means bug fixes for new edge cases, performance improvements, or support for future Python or CSS standard changes are unlikely.
- gotcha The `cssmin.cssmin()` function expects a string containing the CSS content to be minified, not a file path. Passing a `Path` object or a string representing a file path directly will result in a `TypeError`.
Install
-
pip install cssmin
Imports
- cssmin
import cssmin
Quickstart
import cssmin
css_content = """
body {
font-family: Arial, sans-serif;
color: #333;
}
h1 {
margin-bottom: 10px;
/* This is a comment */
padding: 5px;
}
"""
minified_css = cssmin.cssmin(css_content)
print("Original CSS size:", len(css_content), "bytes")
print("Minified CSS size:", len(minified_css), "bytes")
print("Minified CSS:\n", minified_css)