UNPKG

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