You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

987 lines
40 KiB

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