0
# CSS Minification
1
2
Advanced CSS minification with support for multiple backends and automatic base64 image inlining for optimized web assets.
3
4
## Capabilities
5
6
### CSS Minifier Function
7
8
Minifies CSS data using configurable CSS minifiers with automatic image inlining.
9
10
```javascript { .api }
11
/**
12
* Minifies CSS data using configurable CSS minifiers
13
* @param data - CSS source code to minify
14
* @param userOptions - Configuration options for CSS and image processing
15
* @returns Promise resolving to minified CSS code
16
*/
17
function minify.css(data: string, userOptions?: MinifyOptions): Promise<string>;
18
19
interface MinifyOptions {
20
css?: {
21
type?: 'lightningcss' | 'clean-css';
22
'clean-css'?: CleanCSSOptions;
23
};
24
img?: {
25
maxSize?: number; // Default: 102400 (100KB)
26
};
27
}
28
```
29
30
**Usage Examples:**
31
32
```javascript
33
import { minify } from "minify";
34
35
// Default minification using lightningcss
36
const css = `
37
body {
38
color: '#FFFFFF';
39
margin: 0px;
40
}
41
`;
42
const minified = await minify.css(css);
43
// Result: "body{color:\"#FFFFFF\";margin:0}"
44
45
// Using clean-css
46
const cleanResult = await minify.css(css, {
47
css: {
48
type: 'clean-css',
49
'clean-css': {
50
level: 2,
51
compatibility: '*'
52
}
53
}
54
});
55
56
// With image inlining options
57
const withImages = await minify.css(cssWithImages, {
58
css: {
59
type: 'clean-css'
60
},
61
img: {
62
maxSize: 50000 // 50KB limit for base64 inlining
63
}
64
});
65
```
66
67
## CSS Minifier Backends
68
69
### LightningCSS (Default)
70
71
Modern, fast CSS minifier written in Rust with excellent performance.
72
73
```javascript { .api }
74
// LightningCSS uses internal configuration
75
// No direct options exposure in minify package
76
interface LightningCSSMinification {
77
minify: true; // Always enabled
78
// Internal optimization settings managed automatically
79
}
80
```
81
82
**Usage:**
83
84
```javascript
85
// Default behavior - no options needed
86
const result = await minify.css(cssCode);
87
88
// Explicit selection
89
const result = await minify.css(cssCode, {
90
css: {
91
type: 'lightningcss'
92
}
93
});
94
```
95
96
### Clean-CSS
97
98
Feature-rich CSS minifier with extensive configuration options and compatibility settings.
99
100
```javascript { .api }
101
interface CleanCSSOptions {
102
level?: number | object; // Optimization level (0, 1, 2)
103
compatibility?: string | object; // Browser compatibility settings
104
format?: string | object; // Output formatting options
105
inline?: string[]; // Files to inline
106
rebase?: boolean; // URL rebasing
107
specialComments?: string | number; // Special comment handling
108
sourceMap?: boolean; // Source map generation
109
110
// Level-specific options
111
level?: {
112
1?: {
113
cleanupCharsets?: boolean;
114
normalizeUrls?: boolean;
115
optimizeBackground?: boolean;
116
optimizeBorderRadius?: boolean;
117
optimizeFilter?: boolean;
118
optimizeFont?: boolean;
119
optimizeFontWeight?: boolean;
120
optimizeOutline?: boolean;
121
removeEmpty?: boolean;
122
removeNegativePaddings?: boolean;
123
removeQuotes?: boolean;
124
removeWhitespace?: boolean;
125
replaceMultipleZeros?: boolean;
126
replaceTimeUnits?: boolean;
127
replaceZeroUnits?: boolean;
128
roundingPrecision?: boolean | number;
129
selectorsSortingMethod?: string;
130
specialComments?: string | number;
131
tidyAtRules?: boolean;
132
tidyBlockScopes?: boolean;
133
tidySelectors?: boolean;
134
};
135
2?: {
136
mergeAdjacentRules?: boolean;
137
mergeIntoShorthands?: boolean;
138
mergeMedia?: boolean;
139
mergeNonAdjacentRules?: boolean;
140
mergeSemantically?: boolean;
141
overrideProperties?: boolean;
142
removeEmpty?: boolean;
143
reduceNonAdjacentRules?: boolean;
144
removeDuplicateFontRules?: boolean;
145
removeDuplicateMediaBlocks?: boolean;
146
removeDuplicateRules?: boolean;
147
removeUnusedAtRules?: boolean;
148
restructureRules?: boolean;
149
skipProperties?: string[];
150
};
151
};
152
}
153
```
154
155
**Usage:**
156
157
```javascript
158
const result = await minify.css(cssCode, {
159
css: {
160
type: 'clean-css',
161
'clean-css': {
162
level: {
163
1: {
164
specialComments: 0, // Remove all comments
165
removeWhitespace: true
166
},
167
2: {
168
mergeAdjacentRules: true,
169
removeEmpty: true,
170
removeDuplicateRules: true
171
}
172
},
173
compatibility: {
174
properties: {
175
colors: false, // Disable color optimizations
176
ieFilters: true // Keep IE filters
177
}
178
}
179
}
180
}
181
});
182
```
183
184
## Image Inlining
185
186
Automatic base64 image inlining for CSS assets to reduce HTTP requests.
187
188
```javascript { .api }
189
interface ImageInliningOptions {
190
maxSize?: number; // Maximum file size for inlining (bytes)
191
}
192
193
// Default options
194
const defaultImageOptions = {
195
maxSize: 102400 // 100KB
196
};
197
```
198
199
**Image Inlining Process:**
200
201
1. Parses CSS for `url()` references to images
202
2. Checks image file size against `maxSize` threshold
203
3. Converts eligible images to base64 data URIs
204
4. Replaces original URLs with inline data URIs
205
206
**Usage:**
207
208
```javascript
209
// CSS with image references
210
const cssWithImages = `
211
.header {
212
background-image: url('logo.png');
213
}
214
.icon {
215
background: url('../icons/star.svg');
216
}
217
`;
218
219
// Configure image inlining
220
const result = await minify.css(cssWithImages, {
221
img: {
222
maxSize: 50000 // 50KB limit
223
}
224
});
225
226
// Result includes inlined images:
227
// .header{background-image:url(data:image/png;base64,iVBORw0K...)}
228
```
229
230
## File-based CSS Processing
231
232
When processing CSS files (not just strings), automatic image inlining is applied.
233
234
```javascript
235
// File processing automatically includes image inlining
236
const minifiedCSS = await minify('./styles.css', {
237
css: {
238
type: 'clean-css'
239
},
240
img: {
241
maxSize: 25000 // 25KB limit for images
242
}
243
});
244
```
245
246
## Error Handling
247
248
CSS minification handles various error conditions:
249
250
- **Invalid CSS**: Syntax errors in CSS are caught and reported
251
- **Missing Data**: Throws assertion error if data parameter is empty
252
- **Clean-CSS Errors**: Validation and processing errors from clean-css are propagated
253
- **Image Processing Errors**: File access and conversion errors for image inlining
254
- **Configuration Errors**: Invalid options are validated and reported
255
256
**Error Examples:**
257
258
```javascript
259
// Empty data validation
260
try {
261
await minify.css("");
262
} catch (error) {
263
console.log(error); // AssertionError
264
}
265
266
// Clean-CSS specific errors
267
try {
268
await minify.css('@import "missing.css";', {
269
css: { type: 'clean-css' }
270
});
271
} catch (error) {
272
console.log(error); // 'Ignoring local @import of "missing.css" as resource is missing.'
273
}
274
275
// Image processing errors
276
try {
277
await minify.css('.bg { background: url("nonexistent.png"); }');
278
} catch (error) {
279
console.log(error.message); // File access error
280
}
281
```