CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-purgecss

Remove unused css selectors

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

css-variables.mddocs/

CSS Variables Management

CSS custom properties (variables) dependency tracking and unused variable removal functionality.

Capabilities

VariablesStructure Class

Main class for managing CSS variables tracking, dependency analysis, and removal of unused variables.

/**
 * Management class for CSS variables tracking and removal
 */
class VariablesStructure {
  /** Map of variable names to their declaration nodes */
  nodes: Map<string, VariableNode[]>;
  /** Set of variables that are used in the CSS */
  usedVariables: Set<string>;
  /** Safelist patterns for protecting specific variables */
  safelist: StringRegExpArray;
}

Variable Declaration Management

Methods for tracking CSS variable declarations and their relationships.

/**
 * Add a CSS variable declaration to the tracking structure
 * @param declaration - PostCSS declaration node for the CSS variable
 */
addVariable(declaration: postcss.Declaration): void;

/**
 * Track variable usage within other variable declarations
 * @param declaration - PostCSS declaration containing variable usage
 * @param matchedVariables - Iterator of regex matches for var() references
 */
addVariableUsage(
  declaration: postcss.Declaration,
  matchedVariables: IterableIterator<RegExpMatchArray>
): void;

/**
 * Track variable usage in CSS properties (non-variable declarations)
 * @param matchedVariables - Iterator of regex matches for var() references
 */
addVariableUsageInProperties(
  matchedVariables: IterableIterator<RegExpMatchArray>
): void;

Usage Tracking and Removal

Methods for marking variables as used and removing unused variables.

/**
 * Mark a variable and all its dependencies as used
 * @param variableName - Name of the CSS variable to mark as used
 */
setAsUsed(variableName: string): void;

/**
 * Remove all unused CSS variables from the stylesheet
 * Analyzes dependency chain and preserves variables that are directly or indirectly used
 */
removeUnused(): void;

/**
 * Check if a CSS variable is protected by the safelist
 * @param variable - CSS variable name to check
 * @returns True if variable is safelisted
 */
isVariablesSafelisted(variable: string): boolean;

Usage Examples:

import { PurgeCSS, VariablesStructure } from "purgecss";

// Enable CSS variables tracking
const results = await new PurgeCSS().purge({
  content: ['src/**/*.html', 'src/**/*.js'],
  css: ['styles/*.css'],
  variables: true,  // Enable variables analysis
  safelist: {
    variables: ['--primary-color', /^--theme-/]  // Protect specific variables
  }
});

// Direct usage of VariablesStructure
const purgeCSS = new PurgeCSS();
const variablesStruct = purgeCSS.variablesStructure;

// Variables will be automatically tracked during CSS processing
await purgeCSS.purge({
  content: ['index.html'],
  css: ['styles.css'],
  variables: true
});

// Manually remove unused variables
purgeCSS.removeUnusedCSSVariables();

VariableNode Class

Individual node representing a CSS variable declaration with dependency tracking.

/**
 * Node representing a CSS variable declaration
 */
class VariableNode {
  /** Child variable nodes that this variable depends on */
  nodes: VariableNode[];
  /** PostCSS declaration node containing the variable definition */
  value: postcss.Declaration;
  /** Flag indicating whether this variable is used */
  isUsed: boolean;
  
  /**
   * Create a new variable node
   * @param declaration - PostCSS declaration for the CSS variable
   */
  constructor(declaration: postcss.Declaration);
}

Variable Analysis Process

Dependency Chain Analysis

PurgeCSS analyzes CSS variables for complex dependency relationships:

  1. Variable Declarations: Tracks all --variable-name: value; declarations
  2. Variable Usage: Identifies var(--variable-name) references in properties
  3. Variable Dependencies: Maps variables that reference other variables
  4. Transitive Dependencies: Marks variables as used if they're referenced by used variables

Example CSS Analysis:

:root {
  --primary-color: #007bff;      /* Root variable */
  --secondary-color: #6c757d;    /* Root variable */
  --button-bg: var(--primary-color);  /* Depends on --primary-color */
  --unused-var: #ff0000;         /* Will be removed if unused */
}

.btn {
  background: var(--button-bg);  /* Uses --button-bg, marks it and --primary-color as used */
}

Usage Detection Patterns

The variables system detects usage through regex pattern matching:

// Pattern used to detect var() usage
const usedVariablesMatchesInDeclaration = value.matchAll(/var\((.+?)[,)]/g);

This pattern captures:

  • var(--color) - Simple variable reference
  • var(--color, #fff) - Variable with fallback value
  • var(--prefix-color) - Variables with prefixes/namespaces

Advanced Variable Features

Safelist Integration

Variables can be protected from removal using the safelist system:

const results = await new PurgeCSS().purge({
  content: ['index.html'],
  css: ['styles.css'],
  variables: true,
  safelist: {
    variables: [
      '--theme-primary',           // Exact match
      '--theme-secondary',         // Exact match
      /^--component-/,            // Regex pattern for component variables
      /--state$/                  // Regex pattern for state variables
    ]
  }
});

Complex Dependency Chains

The system handles complex variable dependency chains:

:root {
  --base-color: #007bff;
  --light-color: color-mix(in srgb, var(--base-color) 80%, white);
  --button-color: var(--light-color);
  --hover-color: color-mix(in srgb, var(--button-color) 90%, black);
}

.btn:hover {
  background: var(--hover-color);  /* Marks entire chain as used */
}

When --hover-color is used, the system marks all variables in the dependency chain as used: --hover-color--button-color--light-color--base-color.

Integration with PurgeCSS Options

Variables analysis integrates with the main PurgeCSS workflow:

interface UserDefinedOptions {
  /** Enable unused CSS variables removal */
  variables?: boolean;
  /** Safelist configuration including variables */
  safelist?: {
    variables?: StringRegExpArray;
  };
}

The variables feature is disabled by default and must be explicitly enabled through the variables: true option.

Install with Tessl CLI

npx tessl i tessl/npm-purgecss

docs

configuration.md

content-extraction.md

core-purging.md

css-variables.md

index.md

safelist-configuration.md

tile.json