b153d9daa3b27ddebcef495ed1c262307c970f7dee2e9bd272633118de6d0b737b26dbd0d143a343010452c1078716c9bcfc592449335283f3bd2fa9c70c1b 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. ## Usage
  10. ```
  11. npm install -g csso
  12. ```
  13. Or try out CSSO [right in your browser](http://css.github.io/csso/csso.html) (web interface).
  14. ### Runners
  15. - Gulp: [gulp-csso](https://github.com/ben-eb/gulp-csso)
  16. - Grunt: [grunt-csso](https://github.com/t32k/grunt-csso)
  17. - Broccoli: [broccoli-csso](https://github.com/sindresorhus/broccoli-csso)
  18. - PostCSS: [postcss-csso](https://github.com/lahmatiy/postcss-csso)
  19. - Webpack: [csso-loader](https://github.com/sandark7/csso-loader)
  20. ### Command line
  21. ```
  22. csso [input] [output] [options]
  23. Options:
  24. --comments <value> Comments to keep: exclamation (default), first-exclamation or none
  25. --debug [level] Output intermediate state of CSS during compression
  26. -h, --help Output usage information
  27. -i, --input <filename> Input file
  28. --input-map <source> Input source map: none, auto (default) or <filename>
  29. -m, --map <destination> Generate source map: none (default), inline, file or <filename>
  30. -o, --output <filename> Output file (result outputs to stdout if not set)
  31. --restructure-off Turns structure minimization off
  32. --stat Output statistics in stderr
  33. -u, --usage <filenane> Usage data file
  34. -v, --version Output version
  35. ```
  36. Some examples:
  37. ```
  38. > csso in.css
  39. ...output result in stdout...
  40. > csso in.css --output out.css
  41. > echo '.test { color: #ff0000; }' | csso
  42. .test{color:red}
  43. > cat source1.css source2.css | csso | gzip -9 -c > production.css.gz
  44. ```
  45. ### Source maps
  46. Source map doesn't generate by default. To generate map use `--map` CLI option, that can be:
  47. - `none` (default) – don't generate source map
  48. - `inline` – add source map into result CSS (via `/*# sourceMappingURL=application/json;base64,... */`)
  49. - `file` – write source map into file with same name as output file, but with `.map` extension (in this case `--output` option is required)
  50. - any other values treat as filename for generated source map
  51. Examples:
  52. ```
  53. > csso my.css --map inline
  54. > csso my.css --output my.min.css --map file
  55. > csso my.css --output my.min.css --map maps/my.min.map
  56. ```
  57. Use `--input-map` option to specify input source map if needed. Possible values for option:
  58. - `auto` (default) - attempt to fetch input source map by follow steps:
  59. - try to fetch inline map from input
  60. - try to fetch source map filename from input and read its content
  61. - (when `--input` is specified) check file with same name as input file but with `.map` extension exists and read its content
  62. - `none` - don't use input source map; actually it's using to disable `auto`-fetching
  63. - any other values treat as filename for input source map
  64. Generally you shouldn't care about input source map since defaults behaviour (`auto`) covers most use cases.
  65. > NOTE: Input source map is using only if output source map is generating.
  66. ### Usage data
  67. `CSSO` can use data about how `CSS` is using for better compression. File with this data (`JSON` format) can be set using `--usage` option. Usage data may contain follow sections:
  68. - `tags` – white list of tags
  69. - `ids` – white list of ids
  70. - `classes` – white list of classes
  71. - `scopes` – groups of classes which never used with classes from other groups on single element
  72. All sections are optional. Value of `tags`, `ids` and `classes` should be array of strings, value of `scopes` should be an array of arrays of strings. Other values are ignoring.
  73. #### Selector filtering
  74. `tags`, `ids` and `classes` are using on clean stage to filter selectors that contains something that not in list. 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 selector hasn't any type selector (or even any type selector) it isn't filter.
  75. > `ids` and `classes` names are case sensitive, `tags` – is not.
  76. Input CSS:
  77. ```css
  78. * { color: green; }
  79. ul, ol, li { color: blue; }
  80. UL.foo, span.bar { color: red; }
  81. ```
  82. Usage data:
  83. ```json
  84. {
  85. "tags": ["ul", "LI"]
  86. }
  87. ```
  88. Result CSS:
  89. ```css
  90. *{color:green}ul,li{color:blue}ul.foo{color:red}
  91. ```
  92. #### Scopes
  93. 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 defines lists of class names that exclusively used on some markup. This information allows the optimizer to move rulesets more agressive. Since it assumes selectors from different scopes can't to be matched on the same element. That leads to better ruleset merging.
  94. Suppose we have a file:
  95. ```css
  96. .module1-foo { color: red; }
  97. .module1-bar { font-size: 1.5em; background: yellow; }
  98. .module2-baz { color: red; }
  99. .module2-qux { font-size: 1.5em; background: yellow; width: 50px; }
  100. ```
  101. It can be assumed that first two rules never used with second two on the same markup. But we can't know that for sure without markup. The optimizer doesn't know it eather and will perform safe transformations only. The result will be the same as input but with no spaces and some semicolons:
  102. ```css
  103. .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}
  104. ```
  105. But with usage data `CSSO` can get better output. If follow usage data is provided:
  106. ```json
  107. {
  108. "scopes": [
  109. ["module1-foo", "module1-bar"],
  110. ["module2-baz", "module2-qux"]
  111. ]
  112. }
  113. ```
  114. New result (29 bytes extra saving):
  115. ```css
  116. .module1-foo,.module2-baz{color:red}.module1-bar,.module2-qux{font-size:1.5em;background:#ff0}.module2-qux{width:50px}
  117. ```
  118. If class name doesn't specified in `scopes` it belongs to default "scope". `scopes` doesn't affect `classes`. If class name presents in `scopes` but missed in `classes` (both sections specified) it will be filtered.
  119. Note that class name can't be specified in several scopes. Also selector can't has classes from different scopes. In both cases an exception throws.
  120. Currently the optimizer doesn't care about out-of-bounds selectors order changing safety (i.e. selectors that may be matched to elements with no class name of scope, e.g. `.scope div` or `.scope ~ :last-child`) since assumes scoped CSS modules doesn't relay on it's order. It may be fix in future if to be an issue.
  121. ### API
  122. ```js
  123. var csso = require('csso');
  124. var compressedCss = csso.minify('.test { color: #ff0000; }').css;
  125. console.log(compressedCss);
  126. // .test{color:red}
  127. ```
  128. You may minify CSS by yourself step by step:
  129. ```js
  130. var ast = csso.parse('.test { color: #ff0000; }');
  131. var compressResult = csso.compress(ast);
  132. var compressedCss = csso.translate(compressResult.ast);
  133. console.log(compressedCss);
  134. // .test{color:red}
  135. ```
  136. Working with source maps:
  137. ```js
  138. var css = fs.readFileSync('path/to/my.css', 'utf8');
  139. var result = csso.minify(css, {
  140. filename: 'path/to/my.css', // will be added to source map as reference to source file
  141. sourceMap: true // generate source map
  142. });
  143. console.log(result);
  144. // { css: '...minified...', map: SourceMapGenerator {} }
  145. console.log(result.map.toString());
  146. // '{ .. source map content .. }'
  147. ```
  148. #### minify(source[, options])
  149. Minify `source` CSS passed as `String`.
  150. Options:
  151. - sourceMap `Boolean` - generate source map if `true`
  152. - filename `String` - filename of input, uses for source map
  153. - debug `Boolean` - output debug information to `stderr`
  154. - beforeCompress `function|array<function>` - called right after parse is run. Callbacks arguments are `ast, options`.
  155. - afterCompress `function|array<function>` - called right after compress is run. Callbacks arguments are `compressResult, options`.
  156. - other options are the same as for `compress()`
  157. Returns an object with properties:
  158. - css `String` – resulting CSS
  159. - map `Object` – instance of `SourceMapGenerator` or `null`
  160. ```js
  161. var result = csso.minify('.test { color: #ff0000; }', {
  162. restructure: false, // don't change CSS structure, i.e. don't merge declarations, rulesets etc
  163. debug: true // show additional debug information:
  164. // true or number from 1 to 3 (greater number - more details)
  165. });
  166. console.log(result.css);
  167. // > .test{color:red}
  168. ```
  169. #### minifyBlock(source[, options])
  170. The same as `minify()` but for style block. Usualy it's a `style` attribute content.
  171. ```js
  172. var result = csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000').css;
  173. console.log(result.css);
  174. // > color:red
  175. ```
  176. #### parse(source[, options])
  177. Parse CSS to AST.
  178. > NOTE: Currenly parser omit redundant separators, spaces and comments (except exclamation comments, i.e. `/*! comment */`) on AST build, since those things are removing by compressor anyway.
  179. Options:
  180. - context `String` – parsing context, useful when some part of CSS is parsing (see below)
  181. - positions `Boolean` – should AST contains node position or not, store data in `info` property of nodes (`false` by default)
  182. - filename `String` – filename of source that adds to info when `positions` is true, uses for source map generation (`<unknown>` by default)
  183. - line `Number` – initial line number, useful when parse fragment of CSS to compute correct positions
  184. - column `Number` – initial column number, useful when parse fragment of CSS to compute correct positions
  185. Contexts:
  186. - `stylesheet` (default) – regular stylesheet, should be suitable in most cases
  187. - `atrule` – at-rule (e.g. `@media screen, print { ... }`)
  188. - `atruleExpression` – at-rule expression (`screen, print` for example above)
  189. - `ruleset` – rule (e.g. `.foo, .bar:hover { color: red; border: 1px solid black; }`)
  190. - `selector` – selector group (`.foo, .bar:hover` for ruleset example)
  191. - `simpleSelector` – selector (`.foo` or `.bar:hover` for ruleset example)
  192. - `block` – block content w/o curly braces (`color: red; border: 1px solid black;` for ruleset example)
  193. - `declaration` – declaration (`color: red` or `border: 1px solid black` for ruleset example)
  194. - `value` – declaration value (`red` or `1px solid black` for ruleset example)
  195. ```js
  196. // simple parsing with no options
  197. var ast = csso.parse('.example { color: red }');
  198. // parse with options
  199. var ast = csso.parse('.foo.bar', {
  200. context: 'simpleSelector',
  201. positions: true
  202. });
  203. ```
  204. #### compress(ast[, options])
  205. Does the main task – compress AST.
  206. > NOTE: `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.
  207. Options:
  208. - restructure `Boolean` – do the structure optimisations or not (`true` by default)
  209. - clone `Boolean` - transform a copy of input AST if `true`, useful in case of AST reuse (`false` by default)
  210. - comments `String` or `Boolean` – specify what comments to left
  211. - `'exclamation'` or `true` (default) – left all exclamation comments (i.e. `/*! .. */`)
  212. - `'first-exclamation'` – remove every comments except first one
  213. - `false` – remove every comments
  214. - usage `Object` - usage data for advanced optimisations (see [Usage data](#usage-data) for details)
  215. - logger `Function` - function to track every step of transformations
  216. #### clone(ast)
  217. Make an AST node deep copy.
  218. ```js
  219. var orig = csso.parse('.test { color: red }');
  220. var copy = csso.clone(orig);
  221. csso.walk(copy, function(node) {
  222. if (node.type === 'Class') {
  223. node.name = 'replaced';
  224. }
  225. });
  226. console.log(csso.translate(orig));
  227. // .test{color:red}
  228. console.log(csso.translate(copy));
  229. // .replaced{color:red}
  230. ```
  231. #### translate(ast)
  232. Converts AST to string.
  233. ```js
  234. var ast = csso.parse('.test { color: red }');
  235. console.log(csso.translate(ast));
  236. // > .test{color:red}
  237. ```
  238. #### translateWithSourceMap(ast)
  239. The same as `translate()` but also generates source map (nodes should contain positions in `info` property).
  240. ```js
  241. var ast = csso.parse('.test { color: red }', {
  242. filename: 'my.css',
  243. positions: true
  244. });
  245. console.log(csso.translateWithSourceMap(ast));
  246. // { css: '.test{color:red}', map: SourceMapGenerator {} }
  247. ```
  248. #### walk(ast, handler)
  249. Visit all nodes of AST and call handler for each one. `handler` receives three arguments:
  250. - node – current AST node
  251. - item – node wrapper when node is a list member; this wrapper contains references to `prev` and `next` nodes in list
  252. - list – reference to list when node is a list member; it's useful for operations on list like `remove()` or `insert()`
  253. Context for handler an object, that contains references to some parent nodes:
  254. - root – refers to `ast` or root node
  255. - stylesheet – refers to closest `StyleSheet` node, it may be a top-level or at-rule block stylesheet
  256. - atruleExpression – refers to `AtruleExpression` node if current node inside at-rule expression
  257. - ruleset – refers to `Ruleset` node if current node inside a ruleset
  258. - selector – refers to `Selector` node if current node inside a selector
  259. - declaration – refers to `Declaration` node if current node inside a declaration
  260. - function – refers to closest `Function` or `FunctionalPseudo` node if current node inside one of them
  261. ```js
  262. // collect all urls in declarations
  263. var csso = require('./lib/index.js');
  264. var urls = [];
  265. var ast = csso.parse(`
  266. @import url(import.css);
  267. .foo { background: url('foo.jpg'); }
  268. .bar { background-image: url(bar.png); }
  269. `);
  270. csso.walk(ast, function(node) {
  271. if (this.declaration !== null && node.type === 'Url') {
  272. var value = node.value;
  273. if (value.type === 'Raw') {
  274. urls.push(value.value);
  275. } else {
  276. urls.push(value.value.substr(1, value.value.length - 2));
  277. }
  278. }
  279. });
  280. console.log(urls);
  281. // [ 'foo.jpg', 'bar.png' ]
  282. ```
  283. #### walkRules(ast, handler)
  284. Same as `walk()` but visits `Ruleset` and `Atrule` nodes only.
  285. #### walkRulesRight(ast, handler)
  286. Same as `walkRules()` but visits nodes in reverse order (from last to first).
  287. ## More reading
  288. - [Debugging](docs/debugging.md)
  289. ## License
  290. MIT