CSS optimization library that removes unused CSS selectors from stylesheets
npx @tessl/cli install tessl/npm-purify-css@1.2.0PurifyCSS is a CSS optimization library that removes unused CSS selectors from stylesheets by analyzing HTML, JavaScript, and other content files. It intelligently detects which CSS selectors are actually used in your application and eliminates the unused ones, dramatically reducing file sizes while maintaining all necessary styles.
npm install purify-cssnpm install -g purify-cssES modules:
import purify from "purify-css";CommonJS:
const purify = require("purify-css");const purify = require("purify-css");
// Basic usage with strings
const content = '<button class="button-active">Login</button>';
const css = '.button-active { color: green; } .unused-class { display: block; }';
const purifiedCSS = purify(content, css);
// Result: ".button-active { color: green; }"
// Usage with file patterns
const contentFiles = ['src/**/*.js', 'src/**/*.html'];
const cssFiles = ['src/css/*.css'];
const options = {
output: './dist/purified.css',
minify: true,
info: true
};
purify(contentFiles, cssFiles, options);PurifyCSS operates through several key components:
rework library to parse CSS into an Abstract Syntax Tree (AST) for precise selector manipulationclean-cssThe core functionality that removes unused CSS selectors by analyzing content files and preserving only the selectors that are detected in use.
/**
* Purify CSS by removing unused selectors based on content analysis
* @param {string|string[]} searchThrough - Content to analyze (file patterns or source strings)
* @param {string|string[]} css - CSS to purify (file patterns or source strings)
* @param {PurifyOptions} [options] - Configuration options
* @param {function} [callback] - Optional callback receiving purified CSS
* @returns {string|undefined} - Purified CSS string (if no callback) or undefined (if callback provided)
*/
function purify(searchThrough, css, options, callback);
interface PurifyOptions {
/** File path to write purified CSS output (default: false) */
output?: string | false;
/** Enable CSS minification using clean-css (default: false) */
minify?: boolean;
/** Log size reduction statistics to console (default: false) */
info?: boolean;
/** Log rejected selectors to console (default: false) */
rejected?: boolean;
/** Array of selectors to always preserve (supports wildcards) (default: []) */
whitelist?: string[];
/** Options to pass to clean-css minifier (default: {}) */
cleanCssOptions?: object;
}Content Input Formats:
['src/**/*.js', 'src/**/*.html'])CSS Input Formats:
['src/css/*.css'])Usage Examples:
const purify = require("purify-css");
// Example 1: Direct strings
const htmlContent = '<button class="btn-primary">Click me</button>';
const cssContent = '.btn-primary { color: blue; } .unused { display: none; }';
const result = purify(htmlContent, cssContent);
// Example 2: File patterns with options
const contentPatterns = ['src/**/*.{js,html,php}'];
const cssPatterns = ['assets/css/*.css'];
const options = {
output: 'dist/purified.css',
minify: true,
info: true,
rejected: true,
whitelist: ['*modal*', 'dynamic-class']
};
purify(contentPatterns, cssPatterns, options);
// Example 3: With callback
purify(contentPatterns, cssPatterns, (purifiedCSS) => {
console.log('Purified CSS length:', purifiedCSS.length);
});
// Example 4: Callback with options
purify(contentPatterns, cssPatterns, options, (purifiedCSS) => {
// Process the purified CSS
console.log('Processing complete');
});PurifyCSS supports preserving specific selectors through whitelisting, with support for exact matches and wildcard patterns.
Whitelist Patterns:
'button-active' - Preserves any selector containing 'button-active''*modal*' - Preserves any selector containing 'modal' anywhere in the name'body', 'html' - Always preserved by defaultconst options = {
whitelist: [
'button-active', // Exact match
'*modal*', // Wildcard - keeps any selector with 'modal'
'*tooltip*', // Wildcard - keeps any selector with 'tooltip'
'js-required' // Exact match - often used for JavaScript hooks
]
};Command-line interface for CSS purification with file input/output support.
# Basic usage
purifycss <css-files> <content-files> [options]
# Options:
# -m, --min Minify CSS (boolean, default: false)
# -o, --out Output file path (string)
# -i, --info Show reduction statistics (boolean, default: false)
# -r, --rejected Show rejected selectors (boolean, default: false)
# -w, --whitelist Whitelist selectors (array, default: [])
# -h, --help Show help
# -v, --version Show versionCLI Usage Examples:
# Basic purification
purifycss src/css/main.css src/index.html
# Multiple files with output
purifycss "src/css/*.css" "src/**/*.{html,js}" --out dist/purified.css
# With minification and info
purifycss src/style.css src/app.js --min --info --out build/style.min.css
# With whitelist and rejected selector logging
purifycss src/style.css src/app.js --whitelist "*modal*" "dynamic-class" --rejectedPurifyCSS uses advanced selector detection that can identify CSS class usage in various forms:
Direct Usage:
<div class="button-active">Click me</div>Dynamic Construction:
// Split selectors
var half = 'button-';
$(button).addClass(half + 'active');
// Joined arrays
var dynamicClass = ['button', 'active'].join('-');
$(button).addClass(dynamicClass);
// Framework patterns (React example)
var classes = classNames({
'button-active': this.state.buttonActive
});Content Processing:
/**
* Configuration options for CSS purification
*/
interface PurifyOptions {
/** File path to write purified CSS to, or false to return as string */
output: string | false;
/** Enable CSS minification using clean-css */
minify: boolean;
/** Log information about file size reduction */
info: boolean;
/** Log the CSS selectors that were removed */
rejected: boolean;
/** Array of selectors to always preserve (supports wildcard patterns) */
whitelist: string[];
/** Options object passed to clean-css for minification */
cleanCssOptions: object;
}
/**
* Content input type - can be direct strings or file pattern arrays
*/
type ContentInput = string | string[];
/**
* CSS input type - can be direct CSS strings or file pattern arrays
*/
type CSSInput = string | string[];
/**
* Callback function receiving the purified CSS result
*/
type PurifyCallback = (purifiedCSS: string) => void;PurifyCSS handles various error conditions gracefully:
Common error scenarios:
// File doesn't exist - logs warning but continues
purify(['nonexistent.js'], ['style.css']);
// Invalid CSS - parsing errors handled gracefully
const invalidCSS = '.broken { color: }';
purify('<div class="test">content</div>', invalidCSS);
// Invalid glob pattern - skipped with warning
purify(['src/**/*.{invalid'], ['style.css']);