Micro-Purify
This is a zero-dependencies fork of purify-css.
Micro-purify is a function that takes content (HTML/JS/PHP/etc) and CSS, and returns only the used CSS.
Micro-Purify does not modify the original CSS files. You can write to a new file, like minification.
If your application is using a CSS framework, this is especially useful as many selectors are often unused.
Potential reduction
- Bootstrap file: ~140k
- App using ~40% of selectors.
- Minified: ~117k
- Purified + Minified: ~35k
Usage
Standalone
Installation
npm i -D micro-purify
const purify = let content = ""let css = ""let options = output: "filepath/output.css"
How it works
Used selector detection
Statically analyzes your code to pick up which selectors are used.
But will it catch all of the cases?
Let's start off simple.
button-active
Detecting the use of: <!-- html --><!-- class directly on element -->click
// javascript// Anytime your class name is together in your files, it will find it.;
Now let's get crazy.
button-active
Detecting the use of: // Can detect if class is split.var half = 'button-';;// Can detect if class is joined.var dynamicClass = 'button' 'active';;// Can detect various more ways, including all Javascript frameworks.// A React example.var classes =;return<button className=classes>Submit</button>;;
Examples
Example with source strings
var content = '<button class="button-active"> Login </button>';var css = '.button-active { color: green; } .unused-class { display: block; }'; console;
logs out:
.button-active { color: green; }
glob file patterns + writing to a file
Example withvar content = '**/src/js/*.js' '**/src/html/*.html';var css = '**/src/css/*.css'; var options = // Will write purified CSS to this file. output: './dist/purified.css'; ;
glob file patterns and source strings
Example with bothvar content = '**/src/js/*.js' '**/src/html/*.html';var css = '.button-active { color: green; } .unused-class { display: block; }'; var options = output: './dist/purified.css'; ;
API in depth
// Three possible arguments.;
content
argument
The Array
or String
Type: Array
of glob file patterns to the files to search through for used classes (HTML, JS, PHP, ERB, Templates, anything that uses CSS selectors).
String
of content to look at for used classes.
css
argument
The Array
or String
Type: Array
of glob file patterns to the CSS files you want to filter.
String
of CSS to purify.
options
argument
The (optional) Object
Type: Properties of options object:
whitelist
Array of selectors to always leave in. Ex.['button-active', '*modal*']
this will leave any selector that includesmodal
in it and selectors that matchbutton-active
. (wrapping the string with *'s, leaves all selectors that include it)