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.

764 lines
34 KiB

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