or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-purify-css

CSS optimization library that removes unused CSS selectors from stylesheets

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/purify-css@1.2.x

To install, run

npx @tessl/cli install tessl/npm-purify-css@1.2.0

index.mddocs/

PurifyCSS

PurifyCSS 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.

Package Information

  • Package Name: purify-css
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install purify-css
  • CLI Installation: npm install -g purify-css

Core Imports

ES modules:

import purify from "purify-css";

CommonJS:

const purify = require("purify-css");

Basic Usage

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);

Architecture

PurifyCSS operates through several key components:

  • Content Analysis: Scans content files using glob patterns or direct strings to identify class names, IDs, and element selectors in use
  • CSS Parsing: Uses the rework library to parse CSS into an Abstract Syntax Tree (AST) for precise selector manipulation
  • Selector Matching: Employs intelligent word-based matching that can detect dynamically constructed class names and split selectors
  • Tree Walking: Processes CSS rules recursively, including media queries and nested structures
  • Output Generation: Generates clean CSS with optional minification using clean-css

Capabilities

CSS Purification

The 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:

  • String: Direct content to analyze for selector usage
  • Array of strings: File patterns using glob syntax (e.g., ['src/**/*.js', 'src/**/*.html'])
  • Mixed: Can combine file paths and glob patterns in the same array

CSS Input Formats:

  • String: Direct CSS source code to purify
  • Array of strings: CSS file patterns using glob syntax (e.g., ['src/css/*.css'])
  • Mixed: Can combine file paths and glob patterns in the same array

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');
});

Whitelist Support

PurifyCSS supports preserving specific selectors through whitelisting, with support for exact matches and wildcard patterns.

Whitelist Patterns:

  • Exact match: 'button-active' - Preserves any selector containing 'button-active'
  • Wildcard match: '*modal*' - Preserves any selector containing 'modal' anywhere in the name
  • Element selectors: 'body', 'html' - Always preserved by default
const 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
  ]
};

CLI Interface

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 version

CLI 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" --rejected

Intelligent Selector Detection

PurifyCSS 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:

  • Scans all content through regex patterns to identify potential class names
  • Handles JavaScript minification and compression for more accurate detection
  • Supports multiple programming languages and template systems
  • Automatically includes 'html' and 'body' selectors

Types

/**
 * 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;

Error Handling

PurifyCSS handles various error conditions gracefully:

  • File read errors: Logged as warnings but don't stop execution
  • Invalid JavaScript: Falls back to uncompressed analysis if content compression fails
  • CSS parsing errors: Handled by the underlying rework library
  • Glob pattern errors: Invalid patterns are skipped with warnings
  • Permission errors: File access issues are reported but don't crash the process

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']);