0
# CSSnano
1
2
A modular minifier, built on top of the PostCSS ecosystem. CSSnano takes CSS and compresses it through a configurable preset system, allowing you to choose the level of optimization that suits your needs.
3
4
## Package Information
5
6
- **Package Name**: cssnano
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install cssnano`
10
11
## Core Imports
12
13
```javascript
14
const cssnano = require('cssnano');
15
```
16
17
For ES modules:
18
19
```javascript
20
import cssnano from 'cssnano';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const postcss = require('postcss');
27
const cssnano = require('cssnano');
28
29
// Basic usage with default preset
30
postcss([cssnano()])
31
.process(css, { from: undefined })
32
.then(result => {
33
console.log(result.css);
34
});
35
36
// With specific preset
37
postcss([cssnano({ preset: 'default' })])
38
.process(css, { from: undefined })
39
.then(result => {
40
console.log(result.css);
41
});
42
43
// With custom configuration
44
postcss([cssnano({
45
preset: ['default', {
46
discardComments: {
47
removeAll: true,
48
},
49
}]
50
})])
51
.process(css, { from: undefined })
52
.then(result => {
53
console.log(result.css);
54
});
55
```
56
57
## Architecture
58
59
CSSnano is built around a modular architecture with three key concepts:
60
61
- **Plugin Creator**: The main cssnano function that creates PostCSS processors
62
- **Presets**: Collections of optimization plugins configured for different use cases
63
- **Individual Plugins**: Specific optimization transforms (postcss-minify-*, postcss-normalize-*, etc.)
64
65
The preset system allows loading cssnano in different configurations:
66
- **Default preset**: Safe transforms with minimal assumptions
67
- **Advanced preset**: More aggressive optimizations that may require specific browser support
68
- **Lite preset**: Minimal optimizations focusing on whitespace and comments
69
70
## Capabilities
71
72
### Plugin Creator Function
73
74
Creates a PostCSS processor with the specified configuration options.
75
76
```javascript { .api }
77
/**
78
* Creates a PostCSS processor with cssnano optimizations
79
* @param {Options} options - Configuration options
80
* @returns {import('postcss').Processor} PostCSS processor instance
81
*/
82
function cssnano(options?: Options): import('postcss').Processor;
83
```
84
85
### Configuration Options
86
87
```javascript { .api }
88
interface Options {
89
/** Preset configuration - can be string, array, function, or object */
90
preset?: string | [string, any] | Function | { plugins: any[] };
91
/** Additional plugins to include */
92
plugins?: Array<string | Function | [string | Function, any]>;
93
/** Path to configuration file */
94
configFile?: string;
95
}
96
```
97
98
### Built-in Presets
99
100
CSSnano includes three built-in presets:
101
102
#### Default Preset
103
104
Safe optimizations that make minimal assumptions about your CSS.
105
106
```javascript { .api }
107
/**
108
* Default preset with safe optimizations
109
* @param {DefaultPresetOptions} options - Preset configuration
110
* @returns {{ plugins: Array<[Function, any]> }} Plugin configuration
111
*/
112
function defaultPreset(options?: DefaultPresetOptions): { plugins: Array<[Function, any]> };
113
114
interface DefaultPresetOptions {
115
/** CSS declaration sorting options */
116
cssDeclarationSorter?: false | { keepOverrides?: boolean };
117
/** Comment removal options */
118
discardComments?: false | { removeAll?: boolean; remove?: Function };
119
/** Initial value reduction options */
120
reduceInitial?: false | any;
121
/** Gradient minification options */
122
minifyGradients?: false | any;
123
/** SVG optimization options */
124
svgo?: false | { plugins?: any[] };
125
/** Transform reduction options */
126
reduceTransforms?: false | any;
127
/** Value conversion options */
128
convertValues?: false | { length?: boolean };
129
/** Calc() optimization options */
130
calc?: false | any;
131
/** Color minification options */
132
colormin?: false | any;
133
/** Ordered values optimization */
134
orderedValues?: false | any;
135
/** Selector minification options */
136
minifySelectors?: false | { sort?: boolean };
137
/** Parameter minification options */
138
minifyParams?: false | any;
139
/** Charset normalization options */
140
normalizeCharset?: false | { add?: boolean };
141
/** Font value minification options */
142
minifyFontValues?: false | {
143
removeAfterKeyword?: boolean;
144
removeDuplicates?: boolean;
145
removeQuotes?: boolean | Function;
146
};
147
/** URL normalization options */
148
normalizeUrl?: false | any;
149
/** Longhand merging options */
150
mergeLonghand?: false | any;
151
/** Duplicate removal options */
152
discardDuplicates?: false | any;
153
/** Overridden rule removal options */
154
discardOverridden?: false | any;
155
/** Repeat style normalization options */
156
normalizeRepeatStyle?: false | any;
157
/** Rule merging options */
158
mergeRules?: false | any;
159
/** Empty rule removal options */
160
discardEmpty?: false | any;
161
/** Selector deduplication options */
162
uniqueSelectors?: false | any;
163
/** String normalization options */
164
normalizeString?: false | any;
165
/** Position normalization options */
166
normalizePositions?: false | any;
167
/** Whitespace normalization options */
168
normalizeWhitespace?: false | any;
169
/** Unicode normalization options */
170
normalizeUnicode?: false | any;
171
/** Display value normalization options */
172
normalizeDisplayValues?: false | any;
173
/** Timing function normalization options */
174
normalizeTimingFunctions?: false | any;
175
/** Browserslist override */
176
overrideBrowserslist?: string | string[];
177
}
178
```
179
180
#### Advanced Preset
181
182
More aggressive optimizations that may break CSS in some cases.
183
184
```javascript { .api }
185
/**
186
* Advanced preset with aggressive optimizations
187
* @param {AdvancedPresetOptions} options - Preset configuration
188
* @returns {{ plugins: Array<[Function, any]> }} Plugin configuration
189
*/
190
function advancedPreset(options?: AdvancedPresetOptions): { plugins: Array<[Function, any]> };
191
192
interface AdvancedPresetOptions extends DefaultPresetOptions {
193
/** Autoprefixer options */
194
autoprefixer?: {
195
add?: boolean;
196
overrideBrowserslist?: string | string[];
197
};
198
/** Unused rule discarding options */
199
discardUnused?: false | any;
200
/** Identifier merging options */
201
mergeIdents?: false | any;
202
/** Identifier reduction options */
203
reduceIdents?: false | any;
204
/** Z-index optimization options */
205
zindex?: false | any;
206
}
207
```
208
209
#### Lite Preset
210
211
Minimal optimizations focusing on whitespace and comments.
212
213
```javascript { .api }
214
/**
215
* Lite preset with minimal optimizations
216
* @param {LitePresetOptions} options - Preset configuration
217
* @returns {{ plugins: Array<[Function, any]> }} Plugin configuration
218
*/
219
function litePreset(options?: LitePresetOptions): { plugins: Array<[Function, any]> };
220
221
interface LitePresetOptions {
222
/** Comment removal options */
223
discardComments?: false | { removeAll?: boolean };
224
/** Whitespace normalization options */
225
normalizeWhitespace?: false | any;
226
/** Empty rule removal options */
227
discardEmpty?: false | any;
228
/** Raw cache options */
229
rawCache?: false | any;
230
}
231
```
232
233
### Configuration Loading
234
235
CSSnano supports multiple configuration methods:
236
237
```javascript { .api }
238
/**
239
* Configuration loading priority:
240
* 1. Direct options parameter
241
* 2. External configuration file
242
* 3. Default preset
243
*
244
* Supported configuration files:
245
* - package.json (cssnano property)
246
* - .cssnanorc
247
* - .cssnanorc.json
248
* - .cssnanorc.js
249
* - cssnano.config.js
250
*/
251
```
252
253
### PostCSS Integration
254
255
```javascript { .api }
256
// Plugin has postcss flag for PostCSS compatibility
257
cssnano.postcss = true;
258
```
259
260
**Common Integration Patterns**:
261
262
```javascript
263
// With PostCSS CLI
264
module.exports = {
265
plugins: [
266
require('cssnano')({
267
preset: ['default', {
268
discardComments: {
269
removeAll: true,
270
},
271
}]
272
})
273
]
274
};
275
276
// With webpack postcss-loader
277
module.exports = {
278
module: {
279
rules: [{
280
test: /\.css$/,
281
use: [
282
'style-loader',
283
'css-loader',
284
{
285
loader: 'postcss-loader',
286
options: {
287
plugins: [
288
require('cssnano')({ preset: 'advanced' })
289
]
290
}
291
}
292
]
293
}]
294
}
295
};
296
297
// With Gulp
298
const gulp = require('gulp');
299
const postcss = require('gulp-postcss');
300
301
gulp.task('css', () => {
302
return gulp.src('src/*.css')
303
.pipe(postcss([
304
require('cssnano')({
305
preset: ['default', {
306
minifyFontValues: {
307
removeAfterKeyword: true
308
}
309
}]
310
})
311
]))
312
.pipe(gulp.dest('dist/'));
313
});
314
315
// Programmatic usage
316
const postcss = require('postcss');
317
const cssnano = require('cssnano');
318
const fs = require('fs');
319
320
const css = fs.readFileSync('input.css', 'utf8');
321
322
postcss([cssnano()])
323
.process(css, { from: 'input.css', to: 'output.css' })
324
.then(result => {
325
fs.writeFileSync('output.css', result.css);
326
if (result.map) {
327
fs.writeFileSync('output.css.map', result.map.toString());
328
}
329
});
330
```
331
332
## Error Handling
333
334
CSSnano safely handles:
335
- Invalid CSS syntax - passes through unchanged
336
- Unsupported CSS features - skips optimization
337
- Configuration errors - throws descriptive error messages
338
- Plugin loading failures - reports missing dependencies
339
340
Common errors:
341
- `Cannot load preset "${name}"` - Invalid preset name or missing dependency
342
- Configuration validation errors for invalid options
343
344
## Optimization Overview
345
346
CSSnano performs various optimizations including:
347
348
1. **Whitespace & Comments**: Remove unnecessary whitespace and comments
349
2. **Values**: Minify colors, fonts, gradients, and other CSS values
350
3. **Selectors**: Deduplicate and optimize CSS selectors
351
4. **Rules**: Merge compatible rules and remove duplicates
352
5. **Properties**: Merge longhand properties and remove overridden declarations
353
6. **Advanced**: Identifier reduction, z-index optimization (advanced preset only)
354
355
**Input Example**:
356
```css
357
/* This is a comment */
358
h1 {
359
font-weight: bold;
360
font-family: "Helvetica Neue", Arial, sans-serif;
361
color: #ff0000;
362
margin: 10px 10px 10px 10px;
363
}
364
365
h1 {
366
padding: 0px;
367
}
368
```
369
370
**Output (default preset)**:
371
```css
372
h1{font-weight:700;font-family:Helvetica Neue,Arial,sans-serif;color:red;margin:10px;padding:0}
373
```