RefreshCSS
is a Python library that removes unused classes, ids, and element selectors from CSS.
Make your CSS so fresh, so clean.
pip install refreshcss
pip install refreshcss[cli]
- Pure Python (no extra NodeJS build process needed)
- Filters out unused classes, ids, elements from CSS based on HTML templates
- Handles Django/Jinja styles HTML templates
- Can be used as a filter with
django-compressor
to minify CSS as part of thecompress
management command - Can be used via command-line interface in CI/CD
Make sure that the
cli
extra is installed first:pip install refreshcss[cli]
.
Usage: refreshcss [OPTIONS] CSS HTML...
Remove classes, ids, and element selectors not used in HTML from CSS.
Options:
-o, --output FILENAME Write to file instead of stdout.
-R, -r, --recursive Recursively search subdirectories listed.
--encoding TEXT Character encoding to use when reading files. If not
specified, the encoding will be guessed.
--version Show the version and exit.
--help Show this message and exit.
Add "refreshcss.filters.RefreshCSSFilter"
to COMPRESS_FILTERS
in the Django settings file.
COMPRESS_FILTERS = {
"css": [
"refreshcss.filters.RefreshCSSFilter",
...
],
"js": [...],
}
from refreshcss import RefreshCSS, PathSite
def clean_css(css_path: Path):
# Parse the HTML files
site = PathSite(paths=["templates"], recursive=True)
site.parse()
# Get clean CSS based on the parsed HTML
css_text = css_path.read_text()
cleaned_css = RefreshCSS(site).clean(css_text)
return cleaned_css
- Catalogue classes, ids, and elements that are currently being used in found HTML templates
- Catalogue classes, ids, elements, and at-rules in a particular CSS stylesheet
- Return new CSS stylesheet that only contains rules that are actively being used by the HTML
I wanted to have a filter for django-compressor
that would purge unused CSS as part of the compress
step when deploying for coltrane
apps. After dealing with a manual process and attempting to integrate https://purgecss.com and https://github.com/uncss/uncss I thought "this couldn't be that hard to do in Python".
Which is always the thought at the beginning of every side project... 😅
Probably not. RefreshCSS
only inspects HTML templates, so if CSS classes are being changed client-side then refreshcss
will not know about it.
Currently no, although that is a possibility in the future. PRs appreciated. 😉
Yes! That was a primary reason I built my own solution. 😅 Jinja might also be possible to support with some small tweaks, although it is currently untested.
Maybe. 🤷
Thanks for trying RefreshCSS
out! Please make a PR (pull request) with a small test that replicates the bug or, if that is not possible, create a new discussion.
- treeshake: I unfortunately could not get this to work on my local environment.
- cssutils: This unfortunately seemed to choke on more modern CSS when I tested on Bulma 1.0.
- css-optomizer
This project is supported by GitHub Sponsors and Digital Ocean.
Tobias Bölz 💻 📖 |