Remove unused css selectors
npx @tessl/cli install tessl/npm-purgecss@7.0.00
# PurgeCSS
1
2
PurgeCSS is a comprehensive CSS optimization library and command-line tool that analyzes content files (HTML, JavaScript, etc.) and CSS files to identify and remove unused CSS selectors, significantly reducing bundle sizes. It features a powerful selector matching engine using PostCSS, customizable extractors for different file types, safelist functionality to protect specific selectors from removal, and extensive integration options through plugins for popular build tools.
3
4
## Package Information
5
6
- **Package Name**: purgecss
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install purgecss`
10
11
## Core Imports
12
13
```typescript
14
import {
15
PurgeCSS,
16
defaultOptions,
17
standardizeSafelist,
18
setOptions,
19
mergeExtractorSelectors,
20
ExtractorResultSets,
21
VariablesStructure,
22
VariableNode
23
} from "purgecss";
24
```
25
26
For CommonJS:
27
28
```javascript
29
const {
30
PurgeCSS,
31
defaultOptions,
32
standardizeSafelist,
33
setOptions,
34
mergeExtractorSelectors,
35
ExtractorResultSets,
36
VariablesStructure,
37
VariableNode
38
} = require("purgecss");
39
```
40
41
## Basic Usage
42
43
```typescript
44
import { PurgeCSS } from "purgecss";
45
46
// Basic CSS purging
47
const purgeCSSResults = await new PurgeCSS().purge({
48
content: ['index.html', '**/*.js', '**/*.html', '**/*.vue'],
49
css: ['css/app.css']
50
});
51
52
console.log(purgeCSSResults[0].css); // Purged CSS
53
54
// Advanced usage with safelist
55
const results = await new PurgeCSS().purge({
56
content: ['src/**/*.html', 'src/**/*.js'],
57
css: ['styles/*.css'],
58
safelist: ['btn', 'btn-primary', /^modal-/],
59
variables: true,
60
keyframes: true,
61
fontFace: true
62
});
63
```
64
65
## Architecture
66
67
PurgeCSS is built around several key components:
68
69
- **PurgeCSS Class**: Main API providing purge operations and selector extraction
70
- **Content Extractors**: Pluggable system for extracting selectors from different file types (HTML, Pug, JSX, etc.)
71
- **PostCSS Integration**: Uses PostCSS for CSS parsing and manipulation with selector parsing via postcss-selector-parser
72
- **Selector Matching Engine**: Advanced matching logic supporting complex CSS selectors, pseudo-classes, and attribute selectors
73
- **Safelist System**: Flexible safelist patterns (standard, deep, greedy) for protecting selectors from removal
74
- **Variables Tracking**: CSS custom properties dependency analysis and unused variable removal
75
- **CLI Interface**: Complete command-line tool with all programmatic options available
76
77
## Capabilities
78
79
### Core CSS Purging
80
81
Main PurgeCSS class providing comprehensive CSS optimization functionality with selector extraction, matching, and removal operations.
82
83
```typescript { .api }
84
class PurgeCSS {
85
purge(userOptions?: UserDefinedOptions | string): Promise<ResultPurge[]>;
86
extractSelectorsFromFiles(files: string[], extractors: Extractors[]): Promise<ExtractorResultSets>;
87
extractSelectorsFromString(content: RawContent[], extractors: Extractors[]): Promise<ExtractorResultSets>;
88
}
89
90
interface UserDefinedOptions {
91
content: Array<string | RawContent>;
92
css: Array<string | RawCSS>;
93
defaultExtractor?: ExtractorFunction;
94
extractors?: Array<Extractors>;
95
fontFace?: boolean;
96
keyframes?: boolean;
97
variables?: boolean;
98
rejected?: boolean;
99
rejectedCss?: boolean;
100
sourceMap?: boolean | (postcss.SourceMapOptions & { to?: string });
101
safelist?: UserDefinedSafelist;
102
blocklist?: StringRegExpArray;
103
skippedContentGlobs?: Array<string>;
104
dynamicAttributes?: string[];
105
}
106
107
interface ResultPurge {
108
css: string;
109
sourceMap?: string;
110
rejectedCss?: string;
111
file?: string;
112
rejected?: string[];
113
}
114
```
115
116
[Core Purging API](./core-purging.md)
117
118
### Content Extraction System
119
120
Flexible extractor system for analyzing different file types and extracting CSS selectors from content files.
121
122
```typescript { .api }
123
type ExtractorFunction<T = string> = (content: T) => ExtractorResult;
124
125
type ExtractorResult = ExtractorResultDetailed | string[];
126
127
interface ExtractorResultDetailed {
128
attributes: {
129
names: string[];
130
values: string[];
131
};
132
classes: string[];
133
ids: string[];
134
tags: string[];
135
undetermined: string[];
136
}
137
138
interface Extractors {
139
extensions: string[];
140
extractor: ExtractorFunction;
141
}
142
143
class ExtractorResultSets {
144
constructor(er: ExtractorResult);
145
merge(that: ExtractorResult | ExtractorResultSets): this;
146
hasClass(name: string): boolean;
147
hasId(id: string): boolean;
148
hasTag(tag: string): boolean;
149
hasAttrName(name: string): boolean;
150
hasAttrValue(value: string): boolean;
151
}
152
```
153
154
[Content Extraction](./content-extraction.md)
155
156
### Safelist and Filtering
157
158
Advanced safelist system with multiple patterns for protecting selectors from removal, plus blocklist functionality.
159
160
```typescript { .api }
161
type UserDefinedSafelist = StringRegExpArray | ComplexSafelist;
162
163
interface ComplexSafelist {
164
standard?: StringRegExpArray;
165
deep?: RegExp[];
166
greedy?: RegExp[];
167
variables?: StringRegExpArray;
168
keyframes?: StringRegExpArray;
169
}
170
171
type StringRegExpArray = Array<RegExp | string>;
172
173
function standardizeSafelist(userDefinedSafelist?: UserDefinedSafelist): Required<ComplexSafelist>;
174
```
175
176
[Safelist Configuration](./safelist-configuration.md)
177
178
### CSS Variables Management
179
180
CSS custom properties (variables) dependency tracking and unused variable removal functionality.
181
182
```typescript { .api }
183
class VariablesStructure {
184
nodes: Map<string, VariableNode[]>;
185
usedVariables: Set<string>;
186
safelist: StringRegExpArray;
187
188
addVariable(declaration: postcss.Declaration): void;
189
addVariableUsage(declaration: postcss.Declaration, matchedVariables: IterableIterator<RegExpMatchArray>): void;
190
removeUnused(): void;
191
isVariablesSafelisted(variable: string): boolean;
192
}
193
194
class VariableNode {
195
nodes: VariableNode[];
196
value: postcss.Declaration;
197
isUsed: boolean;
198
199
constructor(declaration: postcss.Declaration);
200
}
201
```
202
203
[CSS Variables](./css-variables.md)
204
205
### Configuration and Utilities
206
207
Configuration management, default options, and utility functions for PurgeCSS operations.
208
209
```typescript { .api }
210
const defaultOptions: Options;
211
212
function setOptions(configFile?: string): Promise<Options>;
213
function standardizeSafelist(userDefinedSafelist?: UserDefinedSafelist): Required<ComplexSafelist>;
214
function mergeExtractorSelectors(...extractors: (ExtractorResultDetailed | ExtractorResultSets)[]): ExtractorResultSets;
215
```
216
217
[Configuration](./configuration.md)
218
219
## Content Types
220
221
```typescript { .api }
222
interface RawContent<T = string> {
223
extension: string;
224
raw: T;
225
}
226
227
interface RawCSS {
228
raw: string;
229
name?: string;
230
}
231
```
232
233
## PostCSS Integration
234
235
```typescript { .api }
236
type PostCSSRoot = postcss.Root;
237
```