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.

372 lines
12 KiB

4 years ago
  1. [![NPM version](https://img.shields.io/npm/v/csso.svg)](https://www.npmjs.com/package/csso)
  2. [![Build Status](https://travis-ci.org/css/csso.svg?branch=master)](https://travis-ci.org/css/csso)
  3. [![Coverage Status](https://coveralls.io/repos/github/css/csso/badge.svg?branch=master)](https://coveralls.io/github/css/csso?branch=master)
  4. [![NPM Downloads](https://img.shields.io/npm/dm/csso.svg)](https://www.npmjs.com/package/csso)
  5. [![Twitter](https://img.shields.io/badge/Twitter-@cssoptimizer-blue.svg)](https://twitter.com/cssoptimizer)
  6. CSSO (CSS Optimizer) is a CSS minifier. It performs three sort of transformations: cleaning (removing redundant), compression (replacement for shorter form) and restructuring (merge of declarations, rulesets and so on). As a result your CSS becomes much smaller.
  7. [![Originated by Yandex](https://cdn.rawgit.com/css/csso/8d1b89211ac425909f735e7d5df87ee16c2feec6/docs/yandex.svg)](https://www.yandex.com/)
  8. [![Sponsored by Avito](https://cdn.rawgit.com/css/csso/8d1b89211ac425909f735e7d5df87ee16c2feec6/docs/avito.svg)](https://www.avito.ru/)
  9. ## Ready to use
  10. - [Web interface](http://css.github.io/csso/csso.html)
  11. - [csso-cli](https://github.com/css/csso-cli) – command line interface
  12. - [gulp-csso](https://github.com/ben-eb/gulp-csso) – `Gulp` plugin
  13. - [grunt-csso](https://github.com/t32k/grunt-csso) – `Grunt` plugin
  14. - [broccoli-csso](https://github.com/sindresorhus/broccoli-csso) – `Broccoli` plugin
  15. - [postcss-csso](https://github.com/lahmatiy/postcss-csso) – `PostCSS` plugin
  16. - [csso-loader](https://github.com/sandark7/csso-loader) – `webpack` loader
  17. - [csso-webpack-plugin](https://github.com/zoobestik/csso-webpack-plugin) – `webpack` plugin
  18. - [CSSO Visual Studio Code plugin](https://marketplace.visualstudio.com/items?itemName=Aneryu.csso)
  19. ## Install
  20. ```
  21. npm install csso
  22. ```
  23. ## API
  24. <!-- TOC depthfrom:3 -->
  25. - [minify(source[, options])](#minifysource-options)
  26. - [minifyBlock(source[, options])](#minifyblocksource-options)
  27. - [syntax.compress(ast[, options])](#syntaxcompressast-options)
  28. - [Source maps](#source-maps)
  29. - [Usage data](#usage-data)
  30. - [White list filtering](#white-list-filtering)
  31. - [Black list filtering](#black-list-filtering)
  32. - [Scopes](#scopes)
  33. <!-- /TOC -->
  34. Basic usage:
  35. ```js
  36. var csso = require('csso');
  37. var minifiedCss = csso.minify('.test { color: #ff0000; }').css;
  38. console.log(minifiedCss);
  39. // .test{color:red}
  40. ```
  41. CSSO is based on [CSSTree](https://github.com/csstree/csstree) to parse CSS into AST, AST traversal and to generate AST back to CSS. All `CSSTree` API is available behind `syntax` field. You may minify CSS step by step:
  42. ```js
  43. var csso = require('csso');
  44. var ast = csso.syntax.parse('.test { color: #ff0000; }');
  45. var compressedAst = csso.syntax.compress(ast).ast;
  46. var minifiedCss = csso.syntax.generate(compressedAst);
  47. console.log(minifiedCss);
  48. // .test{color:red}
  49. ```
  50. > Warning: CSSO uses early versions of CSSTree that still in active development. CSSO doesn't guarantee API behind `syntax` field or AST format will not change in future releases of CSSO, since it's subject to change in CSSTree. Be careful with CSSO updates if you use `syntax` API until this warning removal.
  51. ### minify(source[, options])
  52. Minify `source` CSS passed as `String`.
  53. ```js
  54. var result = csso.minify('.test { color: #ff0000; }', {
  55. restructure: false, // don't change CSS structure, i.e. don't merge declarations, rulesets etc
  56. debug: true // show additional debug information:
  57. // true or number from 1 to 3 (greater number - more details)
  58. });
  59. console.log(result.css);
  60. // > .test{color:red}
  61. ```
  62. Returns an object with properties:
  63. - css `String` – resulting CSS
  64. - map `Object` – instance of [`SourceMapGenerator`](https://github.com/mozilla/source-map#sourcemapgenerator) or `null`
  65. Options:
  66. - sourceMap
  67. Type: `Boolean`
  68. Default: `false`
  69. Generate a source map when `true`.
  70. - filename
  71. Type: `String`
  72. Default: `'<unknown>'`
  73. Filename of input CSS, uses for source map generation.
  74. - debug
  75. Type: `Boolean`
  76. Default: `false`
  77. Output debug information to `stderr`.
  78. - beforeCompress
  79. Type: `function(ast, options)` or `Array<function(ast, options)>` or `null`
  80. Default: `null`
  81. Called right after parse is run.
  82. - afterCompress
  83. Type: `function(compressResult, options)` or `Array<function(compressResult, options)>` or `null`
  84. Default: `null`
  85. Called right after [`syntax.compress()`](#syntaxcompressast-options) is run.
  86. - Other options are the same as for [`syntax.compress()`](#syntaxcompressast-options) function.
  87. ### minifyBlock(source[, options])
  88. The same as `minify()` but for list of declarations. Usually it's a `style` attribute value.
  89. ```js
  90. var result = csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000');
  91. console.log(result.css);
  92. // > color:red
  93. ```
  94. ### syntax.compress(ast[, options])
  95. Does the main task – compress an AST. This is CSSO's extension in CSSTree syntax API.
  96. > NOTE: `syntax.compress()` performs AST compression by transforming input AST by default (since AST cloning is expensive and needed in rare cases). Use `clone` option with truthy value in case you want to keep input AST untouched.
  97. Returns an object with properties:
  98. - ast `Object` – resulting AST
  99. Options:
  100. - restructure
  101. Type: `Boolean`
  102. Default: `true`
  103. Disable or enable a structure optimisations.
  104. - forceMediaMerge
  105. Type: `Boolean`
  106. Default: `false`
  107. Enables merging of `@media` rules with the same media query by splitted by other rules. The optimisation is unsafe in general, but should work fine in most cases. Use it on your own risk.
  108. - clone
  109. Type: `Boolean`
  110. Default: `false`
  111. Transform a copy of input AST if `true`. Useful in case of AST reuse.
  112. - comments
  113. Type: `String` or `Boolean`
  114. Default: `true`
  115. Specify what comments to leave:
  116. - `'exclamation'` or `true` – leave all exclamation comments (i.e. `/*! .. */`)
  117. - `'first-exclamation'` – remove every comment except first one
  118. - `false` – remove all comments
  119. - usage
  120. Type: `Object` or `null`
  121. Default: `null`
  122. Usage data for advanced optimisations (see [Usage data](#usage-data) for details)
  123. - logger
  124. Type: `Function` or `null`
  125. Default: `null`
  126. Function to track every step of transformation.
  127. ### Source maps
  128. To get a source map set `true` for `sourceMap` option. Additianaly `filename` option can be passed to specify source file. When `sourceMap` option is `true`, `map` field of result object will contain a [`SourceMapGenerator`](https://github.com/mozilla/source-map#sourcemapgenerator) instance. This object can be mixed with another source map or translated to string.
  129. ```js
  130. var csso = require('csso');
  131. var css = fs.readFileSync('path/to/my.css', 'utf8');
  132. var result = csso.minify(css, {
  133. filename: 'path/to/my.css', // will be added to source map as reference to source file
  134. sourceMap: true // generate source map
  135. });
  136. console.log(result);
  137. // { css: '...minified...', map: SourceMapGenerator {} }
  138. console.log(result.map.toString());
  139. // '{ .. source map content .. }'
  140. ```
  141. Example of generating source map with respect of source map from input CSS:
  142. ```js
  143. var require('source-map');
  144. var csso = require('csso');
  145. var inputFile = 'path/to/my.css';
  146. var input = fs.readFileSync(inputFile, 'utf8');
  147. var inputMap = input.match(/\/\*# sourceMappingURL=(\S+)\s*\*\/\s*$/);
  148. var output = csso.minify(input, {
  149. filename: inputFile,
  150. sourceMap: true
  151. });
  152. // apply input source map to output
  153. if (inputMap) {
  154. output.map.applySourceMap(
  155. new SourceMapConsumer(inputMap[1]),
  156. inputFile
  157. )
  158. }
  159. // result CSS with source map
  160. console.log(
  161. output.css +
  162. '/*# sourceMappingURL=data:application/json;base64,' +
  163. new Buffer(output.map.toString()).toString('base64') +
  164. ' */'
  165. );
  166. ```
  167. ### Usage data
  168. `CSSO` can use data about how `CSS` is used in a markup for better compression. File with this data (`JSON`) can be set using `usage` option. Usage data may contain following sections:
  169. - `blacklist` – a set of black lists (see [Black list filtering](#black-list-filtering))
  170. - `tags` – white list of tags
  171. - `ids` – white list of ids
  172. - `classes` – white list of classes
  173. - `scopes` – groups of classes which never used with classes from other groups on the same element
  174. All sections are optional. Value of `tags`, `ids` and `classes` should be an array of a string, value of `scopes` should be an array of arrays of strings. Other values are ignoring.
  175. #### White list filtering
  176. `tags`, `ids` and `classes` are using on clean stage to filter selectors that contain something not in the lists. Selectors are filtering only by those kind of simple selector which white list is specified. For example, if only `tags` list is specified then type selectors are checking, and if all type selectors in selector present in list or selector has no any type selector it isn't filter.
  177. > `ids` and `classes` are case sensitive, `tags` – is not.
  178. Input CSS:
  179. ```css
  180. * { color: green; }
  181. ul, ol, li { color: blue; }
  182. UL.foo, span.bar { color: red; }
  183. ```
  184. Usage data:
  185. ```json
  186. {
  187. "tags": ["ul", "LI"]
  188. }
  189. ```
  190. Resulting CSS:
  191. ```css
  192. *{color:green}ul,li{color:blue}ul.foo{color:red}
  193. ```
  194. Filtering performs for nested selectors too. `:not()` pseudos content is ignoring since the result of matching is unpredictable. Example for the same usage data as above:
  195. ```css
  196. :nth-child(2n of ul, ol) { color: red }
  197. :nth-child(3n + 1 of img) { color: yellow }
  198. :not(div, ol, ul) { color: green }
  199. :has(:matches(ul, ol), ul, ol) { color: blue }
  200. ```
  201. Turns into:
  202. ```css
  203. :nth-child(2n of ul){color:red}:not(div,ol,ul){color:green}:has(:matches(ul),ul){color:blue}
  204. ```
  205. #### Black list filtering
  206. Black list filtering performs the same as white list filtering, but filters things that mentioned in the lists. `blacklist` can contain the lists `tags`, `ids` and `classes`.
  207. Black list has a higher priority, so when something mentioned in the white list and in the black list then white list occurrence is ignoring. The `:not()` pseudos content ignoring as well.
  208. ```css
  209. * { color: green; }
  210. ul, ol, li { color: blue; }
  211. UL.foo, li.bar { color: red; }
  212. ```
  213. Usage data:
  214. ```json
  215. {
  216. "blacklist": {
  217. "tags": ["ul"]
  218. },
  219. "tags": ["ul", "LI"]
  220. }
  221. ```
  222. Resulting CSS:
  223. ```css
  224. *{color:green}li{color:blue}li.bar{color:red}
  225. ```
  226. #### Scopes
  227. Scopes is designed for CSS scope isolation solutions such as [css-modules](https://github.com/css-modules/css-modules). Scopes are similar to namespaces and define lists of class names that exclusively used on some markup. This information allows the optimizer to move rules more agressive. Since it assumes selectors from different scopes don't match for the same element. This can improve rule merging.
  228. Suppose we have a file:
  229. ```css
  230. .module1-foo { color: red; }
  231. .module1-bar { font-size: 1.5em; background: yellow; }
  232. .module2-baz { color: red; }
  233. .module2-qux { font-size: 1.5em; background: yellow; width: 50px; }
  234. ```
  235. It can be assumed that first two rules are never used with the second two on the same markup. But we can't say that for sure without a markup review. The optimizer doesn't know it either and will perform safe transformations only. The result will be the same as input but with no spaces and some semicolons:
  236. ```css
  237. .module1-foo{color:red}.module1-bar{font-size:1.5em;background:#ff0}.module2-baz{color:red}.module2-qux{font-size:1.5em;background:#ff0;width:50px}
  238. ```
  239. With usage data `CSSO` can produce better output. If follow usage data is provided:
  240. ```json
  241. {
  242. "scopes": [
  243. ["module1-foo", "module1-bar"],
  244. ["module2-baz", "module2-qux"]
  245. ]
  246. }
  247. ```
  248. The result will be (29 bytes extra saving):
  249. ```css
  250. .module1-foo,.module2-baz{color:red}.module1-bar,.module2-qux{font-size:1.5em;background:#ff0}.module2-qux{width:50px}
  251. ```
  252. If class name isn't mentioned in the `scopes` it belongs to default scope. `scopes` data doesn't affect `classes` whitelist. If class name mentioned in `scopes` but missed in `classes` (both sections are specified) it will be filtered.
  253. Note that class name can't be set for several scopes. Also a selector can't have class names from different scopes. In both cases an exception will thrown.
  254. Currently the optimizer doesn't care about changing order safety for out-of-bounds selectors (i.e. selectors that match to elements without class name, e.g. `.scope div` or `.scope ~ :last-child`). It assumes that scoped CSS modules doesn't relay on it's order. It may be fix in future if to be an issue.