UNPKG

37.8 kBMarkdownView Raw
1<h1 align="center">
2 <br/>
3 <img src="https://cdn.rawgit.com/jakubpawlowicz/clean-css/master/logo.v2.svg" alt="clean-css logo" width="525px"/>
4 <br/>
5 <br/>
6</h1>
7
8[![npm version](https://img.shields.io/npm/v/clean-css.svg?style=flat)](https://www.npmjs.com/package/clean-css)
9[![Build Status](https://img.shields.io/github/workflow/status/jakubpawlowicz/clean-css/Tests/master)](https://github.com/jakubpawlowicz/clean-css/actions?query=workflow%3ATests+branch%3Amaster)
10[![PPC Linux Build Status](https://img.shields.io/travis/jakubpawlowicz/clean-css/master.svg?style=flat&label=PPC%20Linux%20build)](https://travis-ci.org/jakubpawlowicz/clean-css)
11[![Dependency Status](https://img.shields.io/david/jakubpawlowicz/clean-css.svg?style=flat)](https://david-dm.org/jakubpawlowicz/clean-css)
12[![npm Downloads](https://img.shields.io/npm/dm/clean-css.svg)](https://npmcharts.com/compare/clean-css?minimal=true)
13
14clean-css is a fast and efficient CSS optimizer for [Node.js](http://nodejs.org/) platform and [any modern browser](https://jakubpawlowicz.github.io/clean-css).
15
16According to [tests](http://goalsmashers.github.io/css-minification-benchmark/) it is one of the best available.
17
18**Table of Contents**
19
20- [Node.js version support](#nodejs-version-support)
21- [Install](#install)
22- [Use](#use)
23 * [What's new in version 5.0](#whats-new-in-version-50)
24 * [What's new in version 4.2](#whats-new-in-version-42)
25 * [What's new in version 4.1](#whats-new-in-version-41)
26 * [Important: 4.0 breaking changes](#important-40-breaking-changes)
27 * [Constructor options](#constructor-options)
28 * [Compatibility modes](#compatibility-modes)
29 * [Fetch option](#fetch-option)
30 * [Formatting options](#formatting-options)
31 * [Inlining options](#inlining-options)
32 * [Optimization levels](#optimization-levels)
33 + [Level 0 optimizations](#level-0-optimizations)
34 + [Level 1 optimizations](#level-1-optimizations)
35 + [Level 2 optimizations](#level-2-optimizations)
36 * [Plugins](#plugins)
37 * [Minify method](#minify-method)
38 * [Promise interface](#promise-interface)
39 * [CLI utility](#cli-utility)
40- [FAQ](#faq)
41 * [How to optimize multiple files?](#how-to-optimize-multiple-files)
42 * [How to process multiple files without concatenating them into one output file?](#how-to-process-multiple-files-without-concatenating-them-into-one-output-file)
43 * [How to process remote `@import`s correctly?](#how-to-process-remote-imports-correctly)
44 * [How to apply arbitrary transformations to CSS properties?](#how-to-apply-arbitrary-transformations-to-css-properties)
45 * [How to specify a custom rounding precision?](#how-to-specify-a-custom-rounding-precision)
46 * [How to keep a CSS fragment intact?](#how-to-keep-a-css-fragment-intact)
47 * [How to preserve a comment block?](#how-to-preserve-a-comment-block)
48 * [How to rebase relative image URLs?](#how-to-rebase-relative-image-urls)
49 * [How to work with source maps?](#how-to-work-with-source-maps)
50 * [How to apply level 1 & 2 optimizations at the same time?](#how-to-apply-level-1--2-optimizations-at-the-same-time)
51 * [What level 2 optimizations do?](#what-level-2-optimizations-do)
52 * [How to use clean-css with build tools?](#how-to-use-clean-css-with-build-tools)
53 * [How to use clean-css from web browser?](#how-to-use-clean-css-from-web-browser)
54- [Contributing](#contributing)
55 * [How to get started?](#how-to-get-started)
56- [Acknowledgments](#acknowledgments)
57- [License](#license)
58
59# Node.js version support
60
61clean-css requires Node.js 6.0+ (tested on Linux, OS X, and Windows)
62
63# Install
64
65```
66npm install --save-dev clean-css
67```
68
69# Use
70
71```js
72var CleanCSS = require('clean-css');
73var input = 'a{font-weight:bold;}';
74var options = { /* options */ };
75var output = new CleanCSS(options).minify(input);
76```
77
78## What's new in version 5.0
79
80clean-css 5.0 will introduce some breaking changes:
81
82* Node.js 6.x and 8.x are officially no longer supported;
83* `transform` callback in level-1 optimizations is removed in favor of new [plugins](#plugins) interface;
84* changes default Internet Explorer compatibility from 10+ to >11, to revert the old default use `{ compatibility: 'ie10' }` flag;
85* changes default `rebase` option from `true` to `false` so URLs are not rebased by default. Please note that if you set `rebaseTo` option it still counts as setting `rebase: true` to preserve some of the backward compatibility.
86
87And on the new features side of things:
88
89* format options now accepts numerical values for all breaks, which will allow you to have more control over output formatting, e.g. `format: {breaks: {afterComment: 2}}` means clean-css will add two line breaks after each comment
90* a new `batch` option (defaults to `false`) is added, when set to `true` it will process all inputs, given either as an array or a hash, without concatenating them.
91
92## What's new in version 4.2
93
94clean-css 4.2 introduces the following changes / features:
95
96* Adds `process` method for compatibility with optimize-css-assets-webpack-plugin;
97* new `transition` property optimizer;
98* preserves any CSS content between `/* clean-css ignore:start */` and `/* clean-css ignore:end */` comments;
99* allows filtering based on selector in `transform` callback, see [example](#how-to-apply-arbitrary-transformations-to-css-properties);
100* adds configurable line breaks via `format: { breakWith: 'lf' }` option.
101
102## What's new in version 4.1
103
104clean-css 4.1 introduces the following changes / features:
105
106* `inline: false` as an alias to `inline: ['none']`;
107* `multiplePseudoMerging` compatibility flag controlling merging of rules with multiple pseudo classes / elements;
108* `removeEmpty` flag in level 1 optimizations controlling removal of rules and nested blocks;
109* `removeEmpty` flag in level 2 optimizations controlling removal of rules and nested blocks;
110* `compatibility: { selectors: { mergeLimit: <number> } }` flag in compatibility settings controlling maximum number of selectors in a single rule;
111* `minify` method improved signature accepting a list of hashes for a predictable traversal;
112* `selectorsSortingMethod` level 1 optimization allows `false` or `'none'` for disabling selector sorting;
113* `fetch` option controlling a function for handling remote requests;
114* new `font` shorthand and `font-*` longhand optimizers;
115* removal of `optimizeFont` flag in level 1 optimizations due to new `font` shorthand optimizer;
116* `skipProperties` flag in level 2 optimizations controlling which properties won't be optimized;
117* new `animation` shorthand and `animation-*` longhand optimizers;
118* `removeUnusedAtRules` level 2 optimization controlling removal of unused `@counter-style`, `@font-face`, `@keyframes`, and `@namespace` at rules;
119* the [web interface](https://jakubpawlowicz.github.io/clean-css) gets an improved settings panel with "reset to defaults", instant option changes, and settings being persisted across sessions.
120
121## Important: 4.0 breaking changes
122
123clean-css 4.0 introduces some breaking changes:
124
125* API and CLI interfaces are split, so API stays in this repository while CLI moves to [clean-css-cli](https://github.com/jakubpawlowicz/clean-css-cli);
126* `root`, `relativeTo`, and `target` options are replaced by a single `rebaseTo` option - this means that rebasing URLs and import inlining is much simpler but may not be (YMMV) as powerful as in 3.x;
127* `debug` option is gone as stats are always provided in output object under `stats` property;
128* `roundingPrecision` is disabled by default;
129* `roundingPrecision` applies to **all** units now, not only `px` as in 3.x;
130* `processImport` and `processImportFrom` are merged into `inline` option which defaults to `local`. Remote `@import` rules are **NOT** inlined by default anymore;
131* splits `inliner: { request: ..., timeout: ... }` option into `inlineRequest` and `inlineTimeout` options;
132* remote resources without a protocol, e.g. `//fonts.googleapis.com/css?family=Domine:700`, are not inlined anymore;
133* changes default Internet Explorer compatibility from 9+ to 10+, to revert the old default use `{ compatibility: 'ie9' }` flag;
134* renames `keepSpecialComments` to `specialComments`;
135* moves `roundingPrecision` and `specialComments` to level 1 optimizations options, see examples;
136* moves `mediaMerging`, `restructuring`, `semanticMerging`, and `shorthandCompacting` to level 2 optimizations options, see examples below;
137* renames `shorthandCompacting` option to `mergeIntoShorthands`;
138* level 1 optimizations are the new default, up to 3.x it was level 2;
139* `keepBreaks` option is replaced with `{ format: 'keep-breaks' }` to ease transition;
140* `sourceMap` option has to be a boolean from now on - to specify an input source map pass it a 2nd argument to `minify` method or via a hash instead;
141* `aggressiveMerging` option is removed as aggressive merging is replaced by smarter override merging.
142
143## Constructor options
144
145clean-css constructor accepts a hash as a parameter with the following options available:
146
147* `compatibility` - controls compatibility mode used; defaults to `ie10+`; see [compatibility modes](#compatibility-modes) for examples;
148* `fetch` - controls a function for handling remote requests; see [fetch option](#fetch-option) for examples (since 4.1.0);
149* `format` - controls output CSS formatting; defaults to `false`; see [formatting options](#formatting-options) for examples;
150* `inline` - controls `@import` inlining rules; defaults to `'local'`; see [inlining options](#inlining-options) for examples;
151* `inlineRequest` - controls extra options for inlining remote `@import` rules, can be any of [HTTP(S) request options](https://nodejs.org/api/http.html#http_http_request_options_callback);
152* `inlineTimeout` - controls number of milliseconds after which inlining a remote `@import` fails; defaults to 5000;
153* `level` - controls optimization level used; defaults to `1`; see [optimization levels](#optimization-levels) for examples;
154* `rebase` - controls URL rebasing; defaults to `false`;
155* `rebaseTo` - controls a directory to which all URLs are rebased, most likely the directory under which the output file will live; defaults to the current directory;
156* `returnPromise` - controls whether `minify` method returns a Promise object or not; defaults to `false`; see [promise interface](#promise-interface) for examples;
157* `sourceMap` - controls whether an output source map is built; defaults to `false`;
158* `sourceMapInlineSources` - controls embedding sources inside a source map's `sourcesContent` field; defaults to false.
159
160## Compatibility modes
161
162There is a certain number of compatibility mode shortcuts, namely:
163
164* `new CleanCSS({ compatibility: '*' })` (default) - Internet Explorer 10+ compatibility mode
165* `new CleanCSS({ compatibility: 'ie9' })` - Internet Explorer 9+ compatibility mode
166* `new CleanCSS({ compatibility: 'ie8' })` - Internet Explorer 8+ compatibility mode
167* `new CleanCSS({ compatibility: 'ie7' })` - Internet Explorer 7+ compatibility mode
168
169Each of these modes is an alias to a [fine grained configuration](https://github.com/jakubpawlowicz/clean-css/blob/master/lib/options/compatibility.js), with the following options available:
170
171```js
172new CleanCSS({
173 compatibility: {
174 colors: {
175 hexAlpha: false, // controls 4- and 8-character hex color support
176 opacity: true // controls `rgba()` / `hsla()` color support
177 },
178 properties: {
179 backgroundClipMerging: true, // controls background-clip merging into shorthand
180 backgroundOriginMerging: true, // controls background-origin merging into shorthand
181 backgroundSizeMerging: true, // controls background-size merging into shorthand
182 colors: true, // controls color optimizations
183 ieBangHack: false, // controls keeping IE bang hack
184 ieFilters: false, // controls keeping IE `filter` / `-ms-filter`
185 iePrefixHack: false, // controls keeping IE prefix hack
186 ieSuffixHack: false, // controls keeping IE suffix hack
187 merging: true, // controls property merging based on understandability
188 shorterLengthUnits: false, // controls shortening pixel units into `pc`, `pt`, or `in` units
189 spaceAfterClosingBrace: true, // controls keeping space after closing brace - `url() no-repeat` into `url()no-repeat`
190 urlQuotes: true, // controls keeping quoting inside `url()`
191 zeroUnits: true // controls removal of units `0` value
192 },
193 selectors: {
194 adjacentSpace: false, // controls extra space before `nav` element
195 ie7Hack: true, // controls removal of IE7 selector hacks, e.g. `*+html...`
196 mergeablePseudoClasses: [':active', ...], // controls a whitelist of mergeable pseudo classes
197 mergeablePseudoElements: ['::after', ...], // controls a whitelist of mergeable pseudo elements
198 mergeLimit: 8191, // controls maximum number of selectors in a single rule (since 4.1.0)
199 multiplePseudoMerging: true // controls merging of rules with multiple pseudo classes / elements (since 4.1.0)
200 },
201 units: {
202 ch: true, // controls treating `ch` as a supported unit
203 in: true, // controls treating `in` as a supported unit
204 pc: true, // controls treating `pc` as a supported unit
205 pt: true, // controls treating `pt` as a supported unit
206 rem: true, // controls treating `rem` as a supported unit
207 vh: true, // controls treating `vh` as a supported unit
208 vm: true, // controls treating `vm` as a supported unit
209 vmax: true, // controls treating `vmax` as a supported unit
210 vmin: true // controls treating `vmin` as a supported unit
211 }
212 }
213})
214```
215
216You can also use a string when setting a compatibility mode, e.g.
217
218```js
219new CleanCSS({
220 compatibility: 'ie9,-properties.merging' // sets compatibility to IE9 mode with disabled property merging
221})
222```
223
224## Fetch option
225
226The `fetch` option accepts a function which handles remote resource fetching, e.g.
227
228```js
229var request = require('request');
230var source = '@import url(http://example.com/path/to/stylesheet.css);';
231new CleanCSS({
232 fetch: function (uri, inlineRequest, inlineTimeout, callback) {
233 request(uri, function (error, response, body) {
234 if (error) {
235 callback(error, null);
236 } else if (response && response.statusCode != 200) {
237 callback(response.statusCode, null);
238 } else {
239 callback(null, body);
240 }
241 });
242 }
243}).minify(source);
244```
245
246This option provides a convenient way of overriding the default fetching logic if it doesn't support a particular feature, say CONNECT proxies.
247
248Unless given, the default [loadRemoteResource](https://github.com/jakubpawlowicz/clean-css/blob/master/lib/reader/load-remote-resource.js) logic is used.
249
250## Formatting options
251
252By default output CSS is formatted without any whitespace unless a `format` option is given.
253First of all there are two shorthands:
254
255```js
256new CleanCSS({
257 format: 'beautify' // formats output in a really nice way
258})
259```
260
261and
262
263```js
264new CleanCSS({
265 format: 'keep-breaks' // formats output the default way but adds line breaks for improved readability
266})
267```
268
269however `format` option also accept a fine-grained set of options:
270
271```js
272new CleanCSS({
273 format: {
274 breaks: { // controls where to insert breaks
275 afterAtRule: false, // controls if a line break comes after an at-rule; e.g. `@charset`; defaults to `false`
276 afterBlockBegins: false, // controls if a line break comes after a block begins; e.g. `@media`; defaults to `false`
277 afterBlockEnds: false, // controls if a line break comes after a block ends, defaults to `false`
278 afterComment: false, // controls if a line break comes after a comment; defaults to `false`
279 afterProperty: false, // controls if a line break comes after a property; defaults to `false`
280 afterRuleBegins: false, // controls if a line break comes after a rule begins; defaults to `false`
281 afterRuleEnds: false, // controls if a line break comes after a rule ends; defaults to `false`
282 beforeBlockEnds: false, // controls if a line break comes before a block ends; defaults to `false`
283 betweenSelectors: false // controls if a line break comes between selectors; defaults to `false`
284 },
285 breakWith: '\n', // controls the new line character, can be `'\r\n'` or `'\n'` (aliased as `'windows'` and `'unix'` or `'crlf'` and `'lf'`); defaults to system one, so former on Windows and latter on Unix
286 indentBy: 0, // controls number of characters to indent with; defaults to `0`
287 indentWith: 'space', // controls a character to indent with, can be `'space'` or `'tab'`; defaults to `'space'`
288 spaces: { // controls where to insert spaces
289 aroundSelectorRelation: false, // controls if spaces come around selector relations; e.g. `div > a`; defaults to `false`
290 beforeBlockBegins: false, // controls if a space comes before a block begins; e.g. `.block {`; defaults to `false`
291 beforeValue: false // controls if a space comes before a value; e.g. `width: 1rem`; defaults to `false`
292 },
293 wrapAt: false, // controls maximum line length; defaults to `false`
294 semicolonAfterLastProperty: false // controls removing trailing semicolons in rule; defaults to `false` - means remove
295 }
296})
297```
298
299Also since clean-css 5.0 you can use numerical values for all line breaks, which will repeat a line break that many times, e.g:
300
301```js
302 new CleanCSS({
303 format: {
304 breaks: {
305 afterAtRule: 2,
306 afterBlockBegins: 1, // 1 is synonymous with `true`
307 afterBlockEnds: 2,
308 afterComment: 1,
309 afterProperty: 1,
310 afterRuleBegins: 1,
311 afterRuleEnds: 1,
312 beforeBlockEnds: 1,
313 betweenSelectors: 0 // 0 is synonymous with `false`
314 }
315 }
316 })
317```
318
319which will add nicer spacing between at rules and blocks.
320
321## Inlining options
322
323`inline` option whitelists which `@import` rules will be processed, e.g.
324
325```js
326new CleanCSS({
327 inline: ['local'] // default; enables local inlining only
328})
329```
330
331```js
332new CleanCSS({
333 inline: ['none'] // disables all inlining
334})
335```
336
337```js
338// introduced in clean-css 4.1.0
339
340new CleanCSS({
341 inline: false // disables all inlining (alias to `['none']`)
342})
343```
344
345```js
346new CleanCSS({
347 inline: ['all'] // enables all inlining, same as ['local', 'remote']
348})
349```
350
351```js
352new CleanCSS({
353 inline: ['local', 'mydomain.example.com'] // enables local inlining plus given remote source
354})
355```
356
357```js
358new CleanCSS({
359 inline: ['local', 'remote', '!fonts.googleapis.com'] // enables all inlining but from given remote source
360})
361```
362
363## Optimization levels
364
365The `level` option can be either `0`, `1` (default), or `2`, e.g.
366
367```js
368new CleanCSS({
369 level: 2
370})
371```
372
373or a fine-grained configuration given via a hash.
374
375Please note that level 1 optimization options are generally safe while level 2 optimizations should be safe for most users.
376
377### Level 0 optimizations
378
379Level 0 optimizations simply means "no optimizations". Use it when you'd like to inline imports and / or rebase URLs but skip everything else.
380
381### Level 1 optimizations
382
383Level 1 optimizations (default) operate on single properties only, e.g. can remove units when not required, turn rgb colors to a shorter hex representation, remove comments, etc
384
385Here is a full list of available options:
386
387```js
388new CleanCSS({
389 level: {
390 1: {
391 cleanupCharsets: true, // controls `@charset` moving to the front of a stylesheet; defaults to `true`
392 normalizeUrls: true, // controls URL normalization; defaults to `true`
393 optimizeBackground: true, // controls `background` property optimizations; defaults to `true`
394 optimizeBorderRadius: true, // controls `border-radius` property optimizations; defaults to `true`
395 optimizeFilter: true, // controls `filter` property optimizations; defaults to `true`
396 optimizeFont: true, // controls `font` property optimizations; defaults to `true`
397 optimizeFontWeight: true, // controls `font-weight` property optimizations; defaults to `true`
398 optimizeOutline: true, // controls `outline` property optimizations; defaults to `true`
399 removeEmpty: true, // controls removing empty rules and nested blocks; defaults to `true`
400 removeNegativePaddings: true, // controls removing negative paddings; defaults to `true`
401 removeQuotes: true, // controls removing quotes when unnecessary; defaults to `true`
402 removeWhitespace: true, // controls removing unused whitespace; defaults to `true`
403 replaceMultipleZeros: true, // contols removing redundant zeros; defaults to `true`
404 replaceTimeUnits: true, // controls replacing time units with shorter values; defaults to `true`
405 replaceZeroUnits: true, // controls replacing zero values with units; defaults to `true`
406 roundingPrecision: false, // rounds pixel values to `N` decimal places; `false` disables rounding; defaults to `false`
407 selectorsSortingMethod: 'standard', // denotes selector sorting method; can be `'natural'` or `'standard'`, `'none'`, or false (the last two since 4.1.0); defaults to `'standard'`
408 specialComments: 'all', // denotes a number of /*! ... */ comments preserved; defaults to `all`
409 tidyAtRules: true, // controls at-rules (e.g. `@charset`, `@import`) optimizing; defaults to `true`
410 tidyBlockScopes: true, // controls block scopes (e.g. `@media`) optimizing; defaults to `true`
411 tidySelectors: true, // controls selectors optimizing; defaults to `true`
412 }
413 }
414});
415```
416
417There is an `all` shortcut for toggling all options at the same time, e.g.
418
419```js
420new CleanCSS({
421 level: {
422 1: {
423 all: false, // set all values to `false`
424 tidySelectors: true // turns on optimizing selectors
425 }
426 }
427});
428```
429
430### Level 2 optimizations
431
432Level 2 optimizations operate at rules or multiple properties level, e.g. can remove duplicate rules, remove properties redefined further down a stylesheet, or restructure rules by moving them around.
433
434Please note that if level 2 optimizations are turned on then, unless explicitely disabled, level 1 optimizations are applied as well.
435
436Here is a full list of available options:
437
438```js
439new CleanCSS({
440 level: {
441 2: {
442 mergeAdjacentRules: true, // controls adjacent rules merging; defaults to true
443 mergeIntoShorthands: true, // controls merging properties into shorthands; defaults to true
444 mergeMedia: true, // controls `@media` merging; defaults to true
445 mergeNonAdjacentRules: true, // controls non-adjacent rule merging; defaults to true
446 mergeSemantically: false, // controls semantic merging; defaults to false
447 overrideProperties: true, // controls property overriding based on understandability; defaults to true
448 removeEmpty: true, // controls removing empty rules and nested blocks; defaults to `true`
449 reduceNonAdjacentRules: true, // controls non-adjacent rule reducing; defaults to true
450 removeDuplicateFontRules: true, // controls duplicate `@font-face` removing; defaults to true
451 removeDuplicateMediaBlocks: true, // controls duplicate `@media` removing; defaults to true
452 removeDuplicateRules: true, // controls duplicate rules removing; defaults to true
453 removeUnusedAtRules: false, // controls unused at rule removing; defaults to false (available since 4.1.0)
454 restructureRules: false, // controls rule restructuring; defaults to false
455 skipProperties: [] // controls which properties won't be optimized, defaults to `[]` which means all will be optimized (since 4.1.0)
456 }
457 }
458});
459```
460
461There is an `all` shortcut for toggling all options at the same time, e.g.
462
463```js
464new CleanCSS({
465 level: {
466 2: {
467 all: false, // sets all values to `false`
468 removeDuplicateRules: true // turns on removing duplicate rules
469 }
470 }
471});
472```
473
474## Plugins
475
476In clean-css version 5 and above you can define plugins which run alongside level 1 and level 2 optimizations, e.g.
477
478```js
479var myPlugin = {
480 level1: {
481 property: function removeRepeatedBackgroundRepeat(_rule, property, _options) {
482 // So `background-repeat:no-repeat no-repeat` becomes `background-repeat:no-repeat`
483 if (property.name == 'background-repeat' && property.value.length == 2 && property.value[0][1] == property.value[1][1]) {
484 property.value.pop();
485 property.dirty = true;
486 }
487 }
488 }
489}
490
491new CleanCSS({plugins: [myPlugin]})
492
493```
494
495Search `test\module-test.js` for `plugins` or check out `lib/optimizer/level-1/property-optimizers` and `lib/optimizer/level-1/value-optimizers` for more examples.
496
497__Important__: To rewrite your old `transform` as a plugin, check out [this commit](https://github.com/jakubpawlowicz/clean-css/commit/b6ddc523267fc42cf0f6bd1626a79cad97319e17#diff-a71ef45f934725cdb25860dc0b606bcd59e3acee9788cd6df4f9d05339e8a153).
498
499## Minify method
500
501Once configured clean-css provides a `minify` method to optimize a given CSS, e.g.
502
503```js
504var output = new CleanCSS(options).minify(source);
505```
506
507The output of the `minify` method is a hash with following fields:
508
509```js
510console.log(output.styles); // optimized output CSS as a string
511console.log(output.sourceMap); // output source map if requested with `sourceMap` option
512console.log(output.errors); // a list of errors raised
513console.log(output.warnings); // a list of warnings raised
514console.log(output.stats.originalSize); // original content size after import inlining
515console.log(output.stats.minifiedSize); // optimized content size
516console.log(output.stats.timeSpent); // time spent on optimizations in milliseconds
517console.log(output.stats.efficiency); // `(originalSize - minifiedSize) / originalSize`, e.g. 0.25 if size is reduced from 100 bytes to 75 bytes
518```
519
520The `minify` method also accepts an input source map, e.g.
521
522```js
523var output = new CleanCSS(options).minify(source, inputSourceMap);
524```
525
526or a callback invoked when optimizations are finished, e.g.
527
528```js
529new CleanCSS(options).minify(source, function (error, output) {
530 // `output` is the same as in the synchronous call above
531});
532```
533
534## Promise interface
535
536If you prefer clean-css to return a Promise object then you need to explicitely ask for it, e.g.
537
538```js
539new CleanCSS({ returnPromise: true })
540 .minify(source)
541 .then(function (output) { console.log(output.styles); })
542 .catch(function (error) { // deal with errors });
543```
544
545## CLI utility
546
547Clean-css has an associated command line utility that can be installed separately using `npm install clean-css-cli`. For more detailed information, please visit https://github.com/jakubpawlowicz/clean-css-cli.
548
549# FAQ
550
551## How to optimize multiple files?
552
553It can be done either by passing an array of paths, or, when sources are already available, a hash or an array of hashes:
554
555```js
556new CleanCSS().minify(['path/to/file/one', 'path/to/file/two']);
557```
558
559```js
560new CleanCSS().minify({
561 'path/to/file/one': {
562 styles: 'contents of file one'
563 },
564 'path/to/file/two': {
565 styles: 'contents of file two'
566 }
567});
568```
569
570```js
571new CleanCSS().minify([
572 {'path/to/file/one': {styles: 'contents of file one'}},
573 {'path/to/file/two': {styles: 'contents of file two'}}
574]);
575```
576
577Passing an array of hashes allows you to explicitly specify the order in which the input files are concatenated. Whereas when you use a single hash the order is determined by the [traversal order of object properties](http://2ality.com/2015/10/property-traversal-order-es6.html) - available since 4.1.0.
578
579Important note - any `@import` rules already present in the hash will be resolved in memory.
580
581## How to process multiple files without concatenating them into one output file?
582
583Since clean-css 5.0 you can, when passing an array of paths, hash, or array of hashes (see above), ask clean-css not to join styles into one output, but instead return stylesheets optimized one by one, e.g.
584
585```js
586var output = new CleanCSS({ batch: true }).minify(['path/to/file/one', 'path/to/file/two']);
587var outputOfFile1 = output['path/to/file/one'].styles // all other fields, like errors, warnings, or stats are there too
588var outputOfFile2 = output['path/to/file/two'].styles
589```
590
591## How to process remote `@import`s correctly?
592
593In order to inline remote `@import` statements you need to provide a callback to minify method as fetching remote assets is an asynchronous operation, e.g.:
594
595```js
596var source = '@import url(http://example.com/path/to/remote/styles);';
597new CleanCSS({ inline: ['remote'] }).minify(source, function (error, output) {
598 // output.styles
599});
600```
601
602If you don't provide a callback, then remote `@import`s will be left as is.
603
604## How to apply arbitrary transformations to CSS properties?
605
606Please see [plugins](#plugins).
607
608## How to specify a custom rounding precision?
609
610The level 1 `roundingPrecision` optimization option accept a string with per-unit rounding precision settings, e.g.
611
612```js
613new CleanCSS({
614 level: {
615 1: {
616 roundingPrecision: 'all=3,px=5'
617 }
618 }
619}).minify(source)
620```
621
622which sets all units rounding precision to 3 digits except `px` unit precision of 5 digits.
623
624## How to optimize a stylesheet with custom `rpx` units?
625
626Since `rpx` is a non standard unit (see [#1074](https://github.com/jakubpawlowicz/clean-css/issues/1074)), it will be dropped by default as an invalid value.
627
628However you can treat `rpx` units as regular ones:
629
630```js
631new CleanCSS({
632 compatibility: {
633 customUnits: {
634 rpx: true
635 }
636 }
637}).minify(source)
638```
639
640## How to keep a CSS fragment intact?
641
642Note: available since 4.2.0.
643
644Wrap the CSS fragment in special comments which instruct clean-css to preserve it, e.g.
645
646```css
647.block-1 {
648 color: red
649}
650/* clean-css ignore:start */
651.block-special {
652 color: transparent
653}
654/* clean-css ignore:end */
655.block-2 {
656 margin: 0
657}
658```
659
660Optimizing this CSS will result in the following output:
661
662```css
663.block-1{color:red}
664.block-special {
665 color: transparent
666}
667.block-2{margin:0}
668```
669
670## How to preserve a comment block?
671
672Use the `/*!` notation instead of the standard one `/*`:
673
674```css
675/*!
676 Important comments included in optimized output.
677*/
678```
679
680## How to rebase relative image URLs?
681
682clean-css will handle it automatically for you in the following cases:
683
684* when full paths to input files are passed in as options;
685* when correct paths are passed in via a hash;
686* when `rebaseTo` is used with any of above two.
687
688## How to work with source maps?
689
690To generate a source map, use `sourceMap: true` option, e.g.:
691
692```js
693new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory })
694 .minify(source, function (error, output) {
695 // access output.sourceMap for SourceMapGenerator object
696 // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details
697});
698```
699
700You can also pass an input source map directly as a 2nd argument to `minify` method:
701
702```js
703new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory })
704 .minify(source, inputSourceMap, function (error, output) {
705 // access output.sourceMap to access SourceMapGenerator object
706 // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details
707});
708```
709
710or even multiple input source maps at once:
711
712```js
713new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }).minify({
714 'path/to/source/1': {
715 styles: '...styles...',
716 sourceMap: '...source-map...'
717 },
718 'path/to/source/2': {
719 styles: '...styles...',
720 sourceMap: '...source-map...'
721 }
722}, function (error, output) {
723 // access output.sourceMap as above
724});
725```
726
727## How to apply level 1 & 2 optimizations at the same time?
728
729Using the hash configuration specifying both optimization levels, e.g.
730
731```js
732new CleanCSS({
733 level: {
734 1: {
735 all: true,
736 normalizeUrls: false
737 },
738 2: {
739 restructureRules: true
740 }
741 }
742})
743```
744
745will apply level 1 optimizations, except url normalization, and default level 2 optimizations with rule restructuring.
746
747## What level 2 optimizations do?
748
749All level 2 optimizations are dispatched [here](https://github.com/jakubpawlowicz/clean-css/blob/master/lib/optimizer/level-2/optimize.js#L67), and this is what they do:
750
751* `recursivelyOptimizeBlocks` - does all the following operations on a nested block, like `@media` or `@keyframe`;
752* `recursivelyOptimizeProperties` - optimizes properties in rulesets and flat at-rules, like @font-face, by splitting them into components (e.g. `margin` into `margin-(bottom|left|right|top)`), optimizing, and restoring them back. You may want to use `mergeIntoShorthands` option to control whether you want to turn multiple components into shorthands;
753* `removeDuplicates` - gets rid of duplicate rulesets with exactly the same set of properties, e.g. when including a Sass / Less partial twice for no good reason;
754* `mergeAdjacent` - merges adjacent rulesets with the same selector or rules;
755* `reduceNonAdjacent` - identifies which properties are overridden in same-selector non-adjacent rulesets, and removes them;
756* `mergeNonAdjacentBySelector` - identifies same-selector non-adjacent rulesets which can be moved (!) to be merged, requires all intermediate rulesets to not redefine the moved properties, or if redefined to have the same value;
757* `mergeNonAdjacentByBody` - same as the one above but for same-selector non-adjacent rulesets;
758* `restructure` - tries to reorganize different-selector different-rules rulesets so they take less space, e.g. `.one{padding:0}.two{margin:0}.one{margin-bottom:3px}` into `.two{margin:0}.one{padding:0;margin-bottom:3px}`;
759* `removeDuplicateFontAtRules` - removes duplicated `@font-face` rules;
760* `removeDuplicateMediaQueries` - removes duplicated `@media` nested blocks;
761* `mergeMediaQueries` - merges non-adjacent `@media` at-rules by the same rules as `mergeNonAdjacentBy*` above;
762
763## How to use clean-css with build tools?
764
765There is a number of 3rd party plugins to popular build tools:
766
767* [Broccoli](https://github.com/broccolijs/broccoli#broccoli): [broccoli-clean-css](https://github.com/shinnn/broccoli-clean-css)
768* [Brunch](http://brunch.io/): [clean-css-brunch](https://github.com/brunch/clean-css-brunch)
769* [Grunt](http://gruntjs.com): [grunt-contrib-cssmin](https://github.com/gruntjs/grunt-contrib-cssmin)
770* [Gulp](http://gulpjs.com/): [gulp-clean-css](https://github.com/scniro/gulp-clean-css)
771* [Gulp](http://gulpjs.com/): [using vinyl-map as a wrapper - courtesy of @sogko](https://github.com/jakubpawlowicz/clean-css/issues/342)
772* [component-builder2](https://github.com/component/builder2.js): [builder-clean-css](https://github.com/poying/builder-clean-css)
773* [Metalsmith](http://metalsmith.io): [metalsmith-clean-css](https://github.com/aymericbeaumet/metalsmith-clean-css)
774* [Lasso](https://github.com/lasso-js/lasso): [lasso-clean-css](https://github.com/yomed/lasso-clean-css)
775* [Start](https://github.com/start-runner/start): [start-clean-css](https://github.com/start-runner/clean-css)
776
777## How to use clean-css from web browser?
778
779* https://jakubpawlowicz.github.io/clean-css/ (official web interface)
780* http://refresh-sf.com/
781* http://adamburgess.github.io/clean-css-online/
782
783# Contributing
784
785See [CONTRIBUTING.md](https://github.com/jakubpawlowicz/clean-css/blob/master/CONTRIBUTING.md).
786
787## How to get started?
788
789First clone the sources:
790
791```bash
792git clone git@github.com:jakubpawlowicz/clean-css.git
793```
794
795then install dependencies:
796
797```bash
798cd clean-css
799npm install
800```
801
802then use any of the following commands to verify your copy:
803
804```bash
805npm run bench # for clean-css benchmarks (see [test/bench.js](https://github.com/jakubpawlowicz/clean-css/blob/master/test/bench.js) for details)
806npm run browserify # to create the browser-ready clean-css version
807npm run check # to lint JS sources with [JSHint](https://github.com/jshint/jshint/)
808npm test # to run all tests
809```
810
811# Acknowledgments
812
813Sorted alphabetically by GitHub handle:
814
815* [@abarre](https://github.com/abarre) (Anthony Barre) for improvements to `@import` processing;
816* [@alexlamsl](https://github.com/alexlamsl) (Alex Lam S.L.) for testing early clean-css 4 versions, reporting bugs, and suggesting numerous improvements.
817* [@altschuler](https://github.com/altschuler) (Simon Altschuler) for fixing `@import` processing inside comments;
818* [@ben-eb](https://github.com/ben-eb) (Ben Briggs) for sharing ideas about CSS optimizations;
819* [@davisjam](https://github.com/davisjam) (Jamie Davis) for disclosing ReDOS vulnerabilities;
820* [@facelessuser](https://github.com/facelessuser) (Isaac) for pointing out a flaw in clean-css' stateless mode;
821* [@grandrath](https://github.com/grandrath) (Martin Grandrath) for improving `minify` method source traversal in ES6;
822* [@jmalonzo](https://github.com/jmalonzo) (Jan Michael Alonzo) for a patch removing node.js' old `sys` package;
823* [@lukeapage](https://github.com/lukeapage) (Luke Page) for suggestions and testing the source maps feature;
824 Plus everyone else involved in [#125](https://github.com/jakubpawlowicz/clean-css/issues/125) for pushing it forward;
825* [@madwizard-thomas](https://github.com/madwizard-thomas) for sharing ideas about `@import` inlining and URL rebasing.
826* [@ngyikp](https://github.com/ngyikp) (Ng Yik Phang) for testing early clean-css 4 versions, reporting bugs, and suggesting numerous improvements.
827* [@wagenet](https://github.com/wagenet) (Peter Wagenet) for suggesting improvements to `@import` inlining behavior;
828* [@venemo](https://github.com/venemo) (Timur Kristóf) for an outstanding contribution of advanced property optimizer for 2.2 release;
829* [@vvo](https://github.com/vvo) (Vincent Voyer) for a patch with better empty element regex and for inspiring us to do many performance improvements in 0.4 release;
830* [@xhmikosr](https://github.com/xhmikosr) for suggesting new features, like option to remove special comments and strip out URLs quotation, and pointing out numerous improvements like JSHint, media queries, etc.
831
832# License
833
834clean-css is released under the [MIT License](https://github.com/jakubpawlowicz/clean-css/blob/master/LICENSE).