source: imaps-frontend/node_modules/clean-css/README.md@ 79a0317

main
Last change on this file since 79a0317 was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 3 days ago

F4 Finalna Verzija

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