0
# CSS Variables Management
1
2
CSS custom properties (variables) dependency tracking and unused variable removal functionality.
3
4
## Capabilities
5
6
### VariablesStructure Class
7
8
Main class for managing CSS variables tracking, dependency analysis, and removal of unused variables.
9
10
```typescript { .api }
11
/**
12
* Management class for CSS variables tracking and removal
13
*/
14
class VariablesStructure {
15
/** Map of variable names to their declaration nodes */
16
nodes: Map<string, VariableNode[]>;
17
/** Set of variables that are used in the CSS */
18
usedVariables: Set<string>;
19
/** Safelist patterns for protecting specific variables */
20
safelist: StringRegExpArray;
21
}
22
```
23
24
### Variable Declaration Management
25
26
Methods for tracking CSS variable declarations and their relationships.
27
28
```typescript { .api }
29
/**
30
* Add a CSS variable declaration to the tracking structure
31
* @param declaration - PostCSS declaration node for the CSS variable
32
*/
33
addVariable(declaration: postcss.Declaration): void;
34
35
/**
36
* Track variable usage within other variable declarations
37
* @param declaration - PostCSS declaration containing variable usage
38
* @param matchedVariables - Iterator of regex matches for var() references
39
*/
40
addVariableUsage(
41
declaration: postcss.Declaration,
42
matchedVariables: IterableIterator<RegExpMatchArray>
43
): void;
44
45
/**
46
* Track variable usage in CSS properties (non-variable declarations)
47
* @param matchedVariables - Iterator of regex matches for var() references
48
*/
49
addVariableUsageInProperties(
50
matchedVariables: IterableIterator<RegExpMatchArray>
51
): void;
52
```
53
54
### Usage Tracking and Removal
55
56
Methods for marking variables as used and removing unused variables.
57
58
```typescript { .api }
59
/**
60
* Mark a variable and all its dependencies as used
61
* @param variableName - Name of the CSS variable to mark as used
62
*/
63
setAsUsed(variableName: string): void;
64
65
/**
66
* Remove all unused CSS variables from the stylesheet
67
* Analyzes dependency chain and preserves variables that are directly or indirectly used
68
*/
69
removeUnused(): void;
70
71
/**
72
* Check if a CSS variable is protected by the safelist
73
* @param variable - CSS variable name to check
74
* @returns True if variable is safelisted
75
*/
76
isVariablesSafelisted(variable: string): boolean;
77
```
78
79
**Usage Examples:**
80
81
```typescript
82
import { PurgeCSS, VariablesStructure } from "purgecss";
83
84
// Enable CSS variables tracking
85
const results = await new PurgeCSS().purge({
86
content: ['src/**/*.html', 'src/**/*.js'],
87
css: ['styles/*.css'],
88
variables: true, // Enable variables analysis
89
safelist: {
90
variables: ['--primary-color', /^--theme-/] // Protect specific variables
91
}
92
});
93
94
// Direct usage of VariablesStructure
95
const purgeCSS = new PurgeCSS();
96
const variablesStruct = purgeCSS.variablesStructure;
97
98
// Variables will be automatically tracked during CSS processing
99
await purgeCSS.purge({
100
content: ['index.html'],
101
css: ['styles.css'],
102
variables: true
103
});
104
105
// Manually remove unused variables
106
purgeCSS.removeUnusedCSSVariables();
107
```
108
109
## VariableNode Class
110
111
Individual node representing a CSS variable declaration with dependency tracking.
112
113
```typescript { .api }
114
/**
115
* Node representing a CSS variable declaration
116
*/
117
class VariableNode {
118
/** Child variable nodes that this variable depends on */
119
nodes: VariableNode[];
120
/** PostCSS declaration node containing the variable definition */
121
value: postcss.Declaration;
122
/** Flag indicating whether this variable is used */
123
isUsed: boolean;
124
125
/**
126
* Create a new variable node
127
* @param declaration - PostCSS declaration for the CSS variable
128
*/
129
constructor(declaration: postcss.Declaration);
130
}
131
```
132
133
## Variable Analysis Process
134
135
### Dependency Chain Analysis
136
137
PurgeCSS analyzes CSS variables for complex dependency relationships:
138
139
1. **Variable Declarations**: Tracks all `--variable-name: value;` declarations
140
2. **Variable Usage**: Identifies `var(--variable-name)` references in properties
141
3. **Variable Dependencies**: Maps variables that reference other variables
142
4. **Transitive Dependencies**: Marks variables as used if they're referenced by used variables
143
144
**Example CSS Analysis:**
145
146
```css
147
:root {
148
--primary-color: #007bff; /* Root variable */
149
--secondary-color: #6c757d; /* Root variable */
150
--button-bg: var(--primary-color); /* Depends on --primary-color */
151
--unused-var: #ff0000; /* Will be removed if unused */
152
}
153
154
.btn {
155
background: var(--button-bg); /* Uses --button-bg, marks it and --primary-color as used */
156
}
157
```
158
159
### Usage Detection Patterns
160
161
The variables system detects usage through regex pattern matching:
162
163
```typescript
164
// Pattern used to detect var() usage
165
const usedVariablesMatchesInDeclaration = value.matchAll(/var\((.+?)[,)]/g);
166
```
167
168
This pattern captures:
169
- `var(--color)` - Simple variable reference
170
- `var(--color, #fff)` - Variable with fallback value
171
- `var(--prefix-color)` - Variables with prefixes/namespaces
172
173
## Advanced Variable Features
174
175
### Safelist Integration
176
177
Variables can be protected from removal using the safelist system:
178
179
```typescript
180
const results = await new PurgeCSS().purge({
181
content: ['index.html'],
182
css: ['styles.css'],
183
variables: true,
184
safelist: {
185
variables: [
186
'--theme-primary', // Exact match
187
'--theme-secondary', // Exact match
188
/^--component-/, // Regex pattern for component variables
189
/--state$/ // Regex pattern for state variables
190
]
191
}
192
});
193
```
194
195
### Complex Dependency Chains
196
197
The system handles complex variable dependency chains:
198
199
```css
200
:root {
201
--base-color: #007bff;
202
--light-color: color-mix(in srgb, var(--base-color) 80%, white);
203
--button-color: var(--light-color);
204
--hover-color: color-mix(in srgb, var(--button-color) 90%, black);
205
}
206
207
.btn:hover {
208
background: var(--hover-color); /* Marks entire chain as used */
209
}
210
```
211
212
When `--hover-color` is used, the system marks all variables in the dependency chain as used: `--hover-color` → `--button-color` → `--light-color` → `--base-color`.
213
214
### Integration with PurgeCSS Options
215
216
Variables analysis integrates with the main PurgeCSS workflow:
217
218
```typescript
219
interface UserDefinedOptions {
220
/** Enable unused CSS variables removal */
221
variables?: boolean;
222
/** Safelist configuration including variables */
223
safelist?: {
224
variables?: StringRegExpArray;
225
};
226
}
227
```
228
229
The variables feature is disabled by default and must be explicitly enabled through the `variables: true` option.