Gathering detailed insights and metrics for clean-css
Gathering detailed insights and metrics for clean-css
Gathering detailed insights and metrics for clean-css
Gathering detailed insights and metrics for clean-css
Fast and efficient CSS optimizer for node.js and the Web
npm install clean-css
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
4,167 Stars
1,781 Commits
323 Forks
74 Watching
65 Branches
95 Contributors
Updated on 22 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-2.5%
3,051,552
Compared to previous day
Last week
3.3%
16,041,310
Compared to previous week
Last month
11.3%
66,632,967
Compared to previous month
Last year
-8%
765,154,222
Compared to previous year
1
clean-css is a fast and efficient CSS optimizer for Node.js platform and any modern browser.
According to tests it is one of the best available.
IMPORTANT: clean-css is now in a maintenance mode. PRs are still welcome, and I will try do an occasional bugfix release.
Table of Contents
@import
s correctly?clean-css requires Node.js 10.0+ (tested on Linux, OS X, and Windows)
npm install --save-dev clean-css
1var CleanCSS = require('clean-css'); 2var input = 'a{font-weight:bold;}'; 3var options = { /* options */ }; 4var output = new CleanCSS(options).minify(input);
clean-css 5.3 introduces one new feature:
variableValueOptimizers
option, which accepts a list of value optimizers or a list of their names, e.g. variableValueOptimizers: ['color', 'fraction']
.clean-css 5.0 introduced some breaking changes:
transform
callback in level-1 optimizations is removed in favor of new plugins interface;{ compatibility: 'ie10' }
flag;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.And on the new features side of things:
format: {breaks: {afterComment: 2}}
means clean-css will add two line breaks after each commentbatch
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.clean-css 4.2 introduces the following changes / features:
process
method for compatibility with optimize-css-assets-webpack-plugin;transition
property optimizer;/* clean-css ignore:start */
and /* clean-css ignore:end */
comments;transform
callback, see example;format: { breakWith: 'lf' }
option.clean-css 4.1 introduces the following changes / features:
inline: false
as an alias to inline: ['none']
;multiplePseudoMerging
compatibility flag controlling merging of rules with multiple pseudo classes / elements;removeEmpty
flag in level 1 optimizations controlling removal of rules and nested blocks;removeEmpty
flag in level 2 optimizations controlling removal of rules and nested blocks;compatibility: { selectors: { mergeLimit: <number> } }
flag in compatibility settings controlling maximum number of selectors in a single rule;minify
method improved signature accepting a list of hashes for a predictable traversal;selectorsSortingMethod
level 1 optimization allows false
or 'none'
for disabling selector sorting;fetch
option controlling a function for handling remote requests;font
shorthand and font-*
longhand optimizers;optimizeFont
flag in level 1 optimizations due to new font
shorthand optimizer;skipProperties
flag in level 2 optimizations controlling which properties won't be optimized;animation
shorthand and animation-*
longhand optimizers;removeUnusedAtRules
level 2 optimization controlling removal of unused @counter-style
, @font-face
, @keyframes
, and @namespace
at rules;clean-css 4.0 introduces some breaking changes:
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;debug
option is gone as stats are always provided in output object under stats
property;roundingPrecision
is disabled by default;roundingPrecision
applies to all units now, not only px
as in 3.x;processImport
and processImportFrom
are merged into inline
option which defaults to local
. Remote @import
rules are NOT inlined by default anymore;inliner: { request: ..., timeout: ... }
option into inlineRequest
and inlineTimeout
options;//fonts.googleapis.com/css?family=Domine:700
, are not inlined anymore;{ compatibility: 'ie9' }
flag;keepSpecialComments
to specialComments
;roundingPrecision
and specialComments
to level 1 optimizations options, see examples;mediaMerging
, restructuring
, semanticMerging
, and shorthandCompacting
to level 2 optimizations options, see examples below;shorthandCompacting
option to mergeIntoShorthands
;keepBreaks
option is replaced with { format: 'keep-breaks' }
to ease transition;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;aggressiveMerging
option is removed as aggressive merging is replaced by smarter override merging.clean-css constructor accepts a hash as a parameter with the following options available:
compatibility
- controls compatibility mode used; defaults to ie10+
; see compatibility modes for examples;fetch
- controls a function for handling remote requests; see fetch option for examples (since 4.1.0);format
- controls output CSS formatting; defaults to false
; see formatting options for examples;inline
- controls @import
inlining rules; defaults to 'local'
; see inlining options for examples;inlineRequest
- controls extra options for inlining remote @import
rules, can be any of HTTP(S) request options;inlineTimeout
- controls number of milliseconds after which inlining a remote @import
fails; defaults to 5000;level
- controls optimization level used; defaults to 1
; see optimization levels for examples;rebase
- controls URL rebasing; defaults to false
;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;returnPromise
- controls whether minify
method returns a Promise object or not; defaults to false
; see promise interface for examples;sourceMap
- controls whether an output source map is built; defaults to false
;sourceMapInlineSources
- controls embedding sources inside a source map's sourcesContent
field; defaults to false.There is a certain number of compatibility mode shortcuts, namely:
new CleanCSS({ compatibility: '*' })
(default) - Internet Explorer 10+ compatibility modenew CleanCSS({ compatibility: 'ie9' })
- Internet Explorer 9+ compatibility modenew CleanCSS({ compatibility: 'ie8' })
- Internet Explorer 8+ compatibility modenew CleanCSS({ compatibility: 'ie7' })
- Internet Explorer 7+ compatibility modeEach of these modes is an alias to a fine grained configuration, with the following options available:
1new CleanCSS({ 2 compatibility: { 3 colors: { 4 hexAlpha: false, // controls 4- and 8-character hex color support 5 opacity: true // controls `rgba()` / `hsla()` color support 6 }, 7 properties: { 8 backgroundClipMerging: true, // controls background-clip merging into shorthand 9 backgroundOriginMerging: true, // controls background-origin merging into shorthand 10 backgroundSizeMerging: true, // controls background-size merging into shorthand 11 colors: true, // controls color optimizations 12 ieBangHack: false, // controls keeping IE bang hack 13 ieFilters: false, // controls keeping IE `filter` / `-ms-filter` 14 iePrefixHack: false, // controls keeping IE prefix hack 15 ieSuffixHack: false, // controls keeping IE suffix hack 16 merging: true, // controls property merging based on understandability 17 shorterLengthUnits: false, // controls shortening pixel units into `pc`, `pt`, or `in` units 18 spaceAfterClosingBrace: true, // controls keeping space after closing brace - `url() no-repeat` into `url()no-repeat` 19 urlQuotes: true, // controls keeping quoting inside `url()` 20 zeroUnits: true // controls removal of units `0` value 21 }, 22 selectors: { 23 adjacentSpace: false, // controls extra space before `nav` element 24 ie7Hack: true, // controls removal of IE7 selector hacks, e.g. `*+html...` 25 mergeablePseudoClasses: [':active', ...], // controls a whitelist of mergeable pseudo classes 26 mergeablePseudoElements: ['::after', ...], // controls a whitelist of mergeable pseudo elements 27 mergeLimit: 8191, // controls maximum number of selectors in a single rule (since 4.1.0) 28 multiplePseudoMerging: true // controls merging of rules with multiple pseudo classes / elements (since 4.1.0) 29 }, 30 units: { 31 ch: true, // controls treating `ch` as a supported unit 32 in: true, // controls treating `in` as a supported unit 33 pc: true, // controls treating `pc` as a supported unit 34 pt: true, // controls treating `pt` as a supported unit 35 rem: true, // controls treating `rem` as a supported unit 36 vh: true, // controls treating `vh` as a supported unit 37 vm: true, // controls treating `vm` as a supported unit 38 vmax: true, // controls treating `vmax` as a supported unit 39 vmin: true // controls treating `vmin` as a supported unit 40 } 41 } 42})
You can also use a string when setting a compatibility mode, e.g.
1new CleanCSS({
2 compatibility: 'ie9,-properties.merging' // sets compatibility to IE9 mode with disabled property merging
3})
The fetch
option accepts a function which handles remote resource fetching, e.g.
1var request = require('request'); 2var source = '@import url(http://example.com/path/to/stylesheet.css);'; 3new CleanCSS({ 4 fetch: function (uri, inlineRequest, inlineTimeout, callback) { 5 request(uri, function (error, response, body) { 6 if (error) { 7 callback(error, null); 8 } else if (response && response.statusCode != 200) { 9 callback(response.statusCode, null); 10 } else { 11 callback(null, body); 12 } 13 }); 14 } 15}).minify(source);
This option provides a convenient way of overriding the default fetching logic if it doesn't support a particular feature, say CONNECT proxies.
Unless given, the default loadRemoteResource logic is used.
By default output CSS is formatted without any whitespace unless a format
option is given.
First of all there are two shorthands:
1new CleanCSS({
2 format: 'beautify' // formats output in a really nice way
3})
and
1new CleanCSS({
2 format: 'keep-breaks' // formats output the default way but adds line breaks for improved readability
3})
however format
option also accept a fine-grained set of options:
1new CleanCSS({
2 format: {
3 breaks: { // controls where to insert breaks
4 afterAtRule: false, // controls if a line break comes after an at-rule; e.g. `@charset`; defaults to `false`
5 afterBlockBegins: false, // controls if a line break comes after a block begins; e.g. `@media`; defaults to `false`
6 afterBlockEnds: false, // controls if a line break comes after a block ends, defaults to `false`
7 afterComment: false, // controls if a line break comes after a comment; defaults to `false`
8 afterProperty: false, // controls if a line break comes after a property; defaults to `false`
9 afterRuleBegins: false, // controls if a line break comes after a rule begins; defaults to `false`
10 afterRuleEnds: false, // controls if a line break comes after a rule ends; defaults to `false`
11 beforeBlockEnds: false, // controls if a line break comes before a block ends; defaults to `false`
12 betweenSelectors: false // controls if a line break comes between selectors; defaults to `false`
13 },
14 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
15 indentBy: 0, // controls number of characters to indent with; defaults to `0`
16 indentWith: 'space', // controls a character to indent with, can be `'space'` or `'tab'`; defaults to `'space'`
17 spaces: { // controls where to insert spaces
18 aroundSelectorRelation: false, // controls if spaces come around selector relations; e.g. `div > a`; defaults to `false`
19 beforeBlockBegins: false, // controls if a space comes before a block begins; e.g. `.block {`; defaults to `false`
20 beforeValue: false // controls if a space comes before a value; e.g. `width: 1rem`; defaults to `false`
21 },
22 wrapAt: false, // controls maximum line length; defaults to `false`
23 semicolonAfterLastProperty: false // controls removing trailing semicolons in rule; defaults to `false` - means remove
24 }
25})
Also 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:
1 new CleanCSS({
2 format: {
3 breaks: {
4 afterAtRule: 2,
5 afterBlockBegins: 1, // 1 is synonymous with `true`
6 afterBlockEnds: 2,
7 afterComment: 1,
8 afterProperty: 1,
9 afterRuleBegins: 1,
10 afterRuleEnds: 1,
11 beforeBlockEnds: 1,
12 betweenSelectors: 0 // 0 is synonymous with `false`
13 }
14 }
15 })
which will add nicer spacing between at rules and blocks.
inline
option whitelists which @import
rules will be processed, e.g.
1new CleanCSS({
2 inline: ['local'] // default; enables local inlining only
3})
1new CleanCSS({
2 inline: ['none'] // disables all inlining
3})
1// introduced in clean-css 4.1.0
2
3new CleanCSS({
4 inline: false // disables all inlining (alias to `['none']`)
5})
1new CleanCSS({
2 inline: ['all'] // enables all inlining, same as ['local', 'remote']
3})
1new CleanCSS({
2 inline: ['local', 'mydomain.example.com'] // enables local inlining plus given remote source
3})
1new CleanCSS({
2 inline: ['local', 'remote', '!fonts.googleapis.com'] // enables all inlining but from given remote source
3})
The level
option can be either 0
, 1
(default), or 2
, e.g.
1new CleanCSS({
2 level: 2
3})
or a fine-grained configuration given via a hash.
Please note that level 1 optimization options are generally safe while level 2 optimizations should be safe for most users.
Level 0 optimizations simply means "no optimizations". Use it when you'd like to inline imports and / or rebase URLs but skip everything else.
Level 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
Here is a full list of available options:
1new CleanCSS({
2 level: {
3 1: {
4 cleanupCharsets: true, // controls `@charset` moving to the front of a stylesheet; defaults to `true`
5 normalizeUrls: true, // controls URL normalization; defaults to `true`
6 optimizeBackground: true, // controls `background` property optimizations; defaults to `true`
7 optimizeBorderRadius: true, // controls `border-radius` property optimizations; defaults to `true`
8 optimizeFilter: true, // controls `filter` property optimizations; defaults to `true`
9 optimizeFont: true, // controls `font` property optimizations; defaults to `true`
10 optimizeFontWeight: true, // controls `font-weight` property optimizations; defaults to `true`
11 optimizeOutline: true, // controls `outline` property optimizations; defaults to `true`
12 removeEmpty: true, // controls removing empty rules and nested blocks; defaults to `true`
13 removeNegativePaddings: true, // controls removing negative paddings; defaults to `true`
14 removeQuotes: true, // controls removing quotes when unnecessary; defaults to `true`
15 removeWhitespace: true, // controls removing unused whitespace; defaults to `true`
16 replaceMultipleZeros: true, // controls removing redundant zeros; defaults to `true`
17 replaceTimeUnits: true, // controls replacing time units with shorter values; defaults to `true`
18 replaceZeroUnits: true, // controls replacing zero values with units; defaults to `true`
19 roundingPrecision: false, // rounds pixel values to `N` decimal places; `false` disables rounding; defaults to `false`
20 selectorsSortingMethod: 'standard', // denotes selector sorting method; can be `'natural'` or `'standard'`, `'none'`, or false (the last two since 4.1.0); defaults to `'standard'`
21 specialComments: 'all', // denotes a number of /*! ... */ comments preserved; defaults to `all`
22 tidyAtRules: true, // controls at-rules (e.g. `@charset`, `@import`) optimizing; defaults to `true`
23 tidyBlockScopes: true, // controls block scopes (e.g. `@media`) optimizing; defaults to `true`
24 tidySelectors: true, // controls selectors optimizing; defaults to `true`,
25 variableValueOptimizers: [] // controls value optimizers which are applied to variables
26 }
27 }
28});
There is an all
shortcut for toggling all options at the same time, e.g.
1new CleanCSS({
2 level: {
3 1: {
4 all: false, // set all values to `false`
5 tidySelectors: true // turns on optimizing selectors
6 }
7 }
8});
Level 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.
Please note that if level 2 optimizations are turned on then, unless explicitely disabled, level 1 optimizations are applied as well.
Here is a full list of available options:
1new CleanCSS({
2 level: {
3 2: {
4 mergeAdjacentRules: true, // controls adjacent rules merging; defaults to true
5 mergeIntoShorthands: true, // controls merging properties into shorthands; defaults to true
6 mergeMedia: true, // controls `@media` merging; defaults to true
7 mergeNonAdjacentRules: true, // controls non-adjacent rule merging; defaults to true
8 mergeSemantically: false, // controls semantic merging; defaults to false
9 overrideProperties: true, // controls property overriding based on understandability; defaults to true
10 removeEmpty: true, // controls removing empty rules and nested blocks; defaults to `true`
11 reduceNonAdjacentRules: true, // controls non-adjacent rule reducing; defaults to true
12 removeDuplicateFontRules: true, // controls duplicate `@font-face` removing; defaults to true
13 removeDuplicateMediaBlocks: true, // controls duplicate `@media` removing; defaults to true
14 removeDuplicateRules: true, // controls duplicate rules removing; defaults to true
15 removeUnusedAtRules: false, // controls unused at rule removing; defaults to false (available since 4.1.0)
16 restructureRules: false, // controls rule restructuring; defaults to false
17 skipProperties: [] // controls which properties won't be optimized, defaults to `[]` which means all will be optimized (since 4.1.0)
18 }
19 }
20});
There is an all
shortcut for toggling all options at the same time, e.g.
1new CleanCSS({
2 level: {
3 2: {
4 all: false, // sets all values to `false`
5 removeDuplicateRules: true // turns on removing duplicate rules
6 }
7 }
8});
In clean-css version 5 and above you can define plugins which run alongside level 1 and level 2 optimizations, e.g.
1var myPlugin = { 2 level1: { 3 property: function removeRepeatedBackgroundRepeat(_rule, property, _options) { 4 // So `background-repeat:no-repeat no-repeat` becomes `background-repeat:no-repeat` 5 if (property.name == 'background-repeat' && property.value.length == 2 && property.value[0][1] == property.value[1][1]) { 6 property.value.pop(); 7 property.dirty = true; 8 } 9 } 10 } 11} 12 13new CleanCSS({plugins: [myPlugin]}) 14
Search 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.
Important: To rewrite your old transform
as a plugin, check out this commit.
Once configured clean-css provides a minify
method to optimize a given CSS, e.g.
1var output = new CleanCSS(options).minify(source);
The output of the minify
method is a hash with following fields:
1console.log(output.styles); // optimized output CSS as a string 2console.log(output.sourceMap); // output source map if requested with `sourceMap` option 3console.log(output.errors); // a list of errors raised 4console.log(output.warnings); // a list of warnings raised 5console.log(output.stats.originalSize); // original content size after import inlining 6console.log(output.stats.minifiedSize); // optimized content size 7console.log(output.stats.timeSpent); // time spent on optimizations in milliseconds 8console.log(output.stats.efficiency); // `(originalSize - minifiedSize) / originalSize`, e.g. 0.25 if size is reduced from 100 bytes to 75 bytes
Example: Minifying a CSS string:
1const CleanCSS = require("clean-css"); 2 3const output = new CleanCSS().minify(` 4 5 a { 6 color: blue; 7 } 8 div { 9 margin: 5px 10 } 11 12`); 13 14console.log(output); 15 16// Log: 17{ 18 styles: 'a{color:#00f}div{margin:5px}', 19 stats: { 20 efficiency: 0.6704545454545454, 21 minifiedSize: 29, 22 originalSize: 88, 23 timeSpent: 6 24 }, 25 errors: [], 26 inlinedStylesheets: [], 27 warnings: [] 28}
The minify
method also accepts an input source map, e.g.
1var output = new CleanCSS(options).minify(source, inputSourceMap);
or a callback invoked when optimizations are finished, e.g.
1new CleanCSS(options).minify(source, function (error, output) { 2 // `output` is the same as in the synchronous call above 3});
To optimize a single file, without reading it first, pass a path to it to minify
method as follows:
1var output = new CleanCSS(options).minify(['path/to/file.css'])
(if you won't enclose the path in an array, it will be treated as a CSS source instead).
There are several ways to optimize multiple files at the same time, see How to optimize multiple files?.
If you prefer clean-css to return a Promise object then you need to explicitely ask for it, e.g.
1new CleanCSS({ returnPromise: true }) 2 .minify(source) 3 .then(function (output) { console.log(output.styles); }) 4 .catch(function (error) { // deal with errors });
Clean-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.
It can be done either by passing an array of paths, or, when sources are already available, a hash or an array of hashes:
1new CleanCSS().minify(['path/to/file/one', 'path/to/file/two']);
1new CleanCSS().minify({ 2 'path/to/file/one': { 3 styles: 'contents of file one' 4 }, 5 'path/to/file/two': { 6 styles: 'contents of file two' 7 } 8});
1new CleanCSS().minify([ 2 {'path/to/file/one': {styles: 'contents of file one'}}, 3 {'path/to/file/two': {styles: 'contents of file two'}} 4]);
Passing 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 - available since 4.1.0.
Important note - any @import
rules already present in the hash will be resolved in memory.
Since 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.
1var output = new CleanCSS({ batch: true }).minify(['path/to/file/one', 'path/to/file/two']); 2var outputOfFile1 = output['path/to/file/one'].styles // all other fields, like errors, warnings, or stats are there too 3var outputOfFile2 = output['path/to/file/two'].styles
@import
s correctly?In 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.:
1var source = '@import url(http://example.com/path/to/remote/styles);'; 2new CleanCSS({ inline: ['remote'] }).minify(source, function (error, output) { 3 // output.styles 4});
If you don't provide a callback, then remote @import
s will be left as is.
Please see plugins.
The level 1 roundingPrecision
optimization option accept a string with per-unit rounding precision settings, e.g.
1new CleanCSS({ 2 level: { 3 1: { 4 roundingPrecision: 'all=3,px=5' 5 } 6 } 7}).minify(source)
which sets all units rounding precision to 3 digits except px
unit precision of 5 digits.
rpx
units?Since rpx
is a non standard unit (see #1074), it will be dropped by default as an invalid value.
However you can treat rpx
units as regular ones:
1new CleanCSS({ 2 compatibility: { 3 customUnits: { 4 rpx: true 5 } 6 } 7}).minify(source)
Note: available since 4.2.0.
Wrap the CSS fragment in special comments which instruct clean-css to preserve it, e.g.
1.block-1 { 2 color: red 3} 4/* clean-css ignore:start */ 5.block-special { 6 color: transparent 7} 8/* clean-css ignore:end */ 9.block-2 { 10 margin: 0 11}
Optimizing this CSS will result in the following output:
1.block-1{color:red} 2.block-special { 3 color: transparent 4} 5.block-2{margin:0}
Use the /*!
notation instead of the standard one /*
:
1/*! 2 Important comments included in optimized output. 3*/
clean-css will handle it automatically for you in the following cases:
rebaseTo
is used with any of above two.To generate a source map, use sourceMap: true
option, e.g.:
1new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }) 2 .minify(source, function (error, output) { 3 // access output.sourceMap for SourceMapGenerator object 4 // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details 5});
You can also pass an input source map directly as a 2nd argument to minify
method:
1new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }) 2 .minify(source, inputSourceMap, function (error, output) { 3 // access output.sourceMap to access SourceMapGenerator object 4 // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details 5});
or even multiple input source maps at once:
1new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }).minify({ 2 'path/to/source/1': { 3 styles: '...styles...', 4 sourceMap: '...source-map...' 5 }, 6 'path/to/source/2': { 7 styles: '...styles...', 8 sourceMap: '...source-map...' 9 } 10}, function (error, output) { 11 // access output.sourceMap as above 12});
Using the hash configuration specifying both optimization levels, e.g.
1new CleanCSS({ 2 level: { 3 1: { 4 all: true, 5 normalizeUrls: false 6 }, 7 2: { 8 restructureRules: true 9 } 10 } 11})
will apply level 1 optimizations, except url normalization, and default level 2 optimizations with rule restructuring.
All level 2 optimizations are dispatched here, and this is what they do:
recursivelyOptimizeBlocks
- does all the following operations on a nested block, like @media
or @keyframe
;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;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;mergeAdjacent
- merges adjacent rulesets with the same selector or rules;reduceNonAdjacent
- identifies which properties are overridden in same-selector non-adjacent rulesets, and removes them;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;mergeNonAdjacentByBody
- same as the one above but for same-selector non-adjacent rulesets;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}
;removeDuplicateFontAtRules
- removes duplicated @font-face
rules;removeDuplicateMediaQueries
- removes duplicated @media
nested blocks;mergeMediaQueries
- merges non-adjacent @media
at-rules by the same rules as mergeNonAdjacentBy*
above;If 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.
Example: Minify invalid CSS, resulting in two warnings:
1const CleanCSS = require("clean-css"); 2 3const output = new CleanCSS().minify(` 4 5 a { 6 -notarealproperty-: 5px; 7 color: 8 } 9 div { 10 margin: 5px 11 } 12 13`); 14 15console.log(output); 16 17// Log: 18{ 19 styles: 'div{margin:5px}', 20 stats: { 21 efficiency: 0.8695652173913043, 22 minifiedSize: 15, 23 originalSize: 115, 24 timeSpent: 1 25 }, 26 errors: [], 27 inlinedStylesheets: [], 28 warnings: [ 29 "Invalid property name '-notarealproperty-' at 4:8. Ignoring.", 30 "Empty property 'color' at 5:8. Ignoring." 31 ] 32}
Example: Minify invalid CSS, resulting in one error:
1const CleanCSS = require("clean-css"); 2 3const output = new CleanCSS().minify(` 4 5 @import "idontexist.css"; 6 a { 7 color: blue; 8 } 9 div { 10 margin: 5px 11 } 12 13`); 14 15console.log(output); 16 17// Log: 18{ 19 styles: 'a{color:#00f}div{margin:5px}', 20 stats: { 21 efficiency: 0.7627118644067796, 22 minifiedSize: 28, 23 originalSize: 118, 24 timeSpent: 2 25 }, 26 errors: [ 27 'Ignoring local @import of "idontexist.css" as resource is missing.' 28 ], 29 inlinedStylesheets: [], 30 warnings: [] 31}
An example of how you can include clean-css in gulp
1const { src, dest, series } = require('gulp'); 2const CleanCSS = require('clean-css'); 3const concat = require('gulp-concat'); 4 5function css() { 6 const options = { 7 compatibility: '*', // (default) - Internet Explorer 10+ compatibility mode 8 inline: ['all'], // enables all inlining, same as ['local', 'remote'] 9 level: 2 // Optimization levels. The level option can be either 0, 1 (default), or 2, e.g. 10 // Please note that level 1 optimization options are generally safe while level 2 optimizations should be safe for most users. 11 }; 12 13 return src('app/**/*.css') 14 .pipe(concat('style.min.css')) 15 .on('data', function(file) { 16 const bufferFile = new CleanCSS(options).minify(file.contents) 17 return file.contents = Buffer.from(bufferFile.styles) 18 }) 19 .pipe(dest('build')) 20} 21exports.css = series(css)
There is a number of 3rd party plugins to popular build tools:
See CONTRIBUTING.md.
First clone the sources:
1git clone git@github.com:clean-css/clean-css.git
then install dependencies:
1cd clean-css 2npm install
then use any of the following commands to verify your copy:
1npm run bench # for clean-css benchmarks (see [test/bench.js](https://github.com/clean-css/clean-css/blob/master/test/bench.js) for details) 2npm run browserify # to create the browser-ready clean-css version 3npm run check # to lint JS sources with [JSHint](https://github.com/jshint/jshint/) 4npm test # to run all tests
Sorted alphabetically by GitHub handle:
@import
processing;@import
processing inside comments;minify
method source traversal in ES6;sys
package;@import
inlining and URL rebasing.@import
inlining behavior;clean-css is released under the MIT License.
The latest stable version of the package.
Stable Version
1
0/10
Summary
Regular Expression Denial of Service in clean-css
Affected Versions
< 4.1.11
Patched Versions
4.1.11
No security vulnerabilities found.