UNPKG

12.5 kBMarkdownView Raw
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
7CSSO (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.
8
9[![Originated by Yandex](https://cdn.rawgit.com/css/csso/8d1b89211ac425909f735e7d5df87ee16c2feec6/docs/yandex.svg)](https://www.yandex.com/)
10[![Sponsored by Avito](https://cdn.rawgit.com/css/csso/8d1b89211ac425909f735e7d5df87ee16c2feec6/docs/avito.svg)](https://www.avito.ru/)
11
12## Ready to use
13
14- [Web interface](http://css.github.io/csso/csso.html)
15- [csso-cli](https://github.com/css/csso-cli) – command line interface
16- [gulp-csso](https://github.com/ben-eb/gulp-csso) – `Gulp` plugin
17- [grunt-csso](https://github.com/t32k/grunt-csso) – `Grunt` plugin
18- [broccoli-csso](https://github.com/sindresorhus/broccoli-csso) – `Broccoli` plugin
19- [postcss-csso](https://github.com/lahmatiy/postcss-csso) – `PostCSS` plugin
20- [csso-loader](https://github.com/sandark7/csso-loader) – `webpack` loader
21- [csso-webpack-plugin](https://github.com/zoobestik/csso-webpack-plugin) – `webpack` plugin
22- [CSSO Visual Studio Code plugin](https://marketplace.visualstudio.com/items?itemName=Aneryu.csso)
23
24## Install
25
26```
27npm install csso
28```
29
30## API
31
32<!-- TOC depthfrom:3 -->
33
34- [minify(source[, options])](#minifysource-options)
35- [minifyBlock(source[, options])](#minifyblocksource-options)
36- [syntax.compress(ast[, options])](#syntaxcompressast-options)
37- [Source maps](#source-maps)
38- [Usage data](#usage-data)
39 - [White list filtering](#white-list-filtering)
40 - [Black list filtering](#black-list-filtering)
41 - [Scopes](#scopes)
42
43<!-- /TOC -->
44
45Basic usage:
46
47```js
48var csso = require('csso');
49
50var minifiedCss = csso.minify('.test { color: #ff0000; }').css;
51
52console.log(minifiedCss);
53// .test{color:red}
54```
55
56CSSO 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:
57
58```js
59var csso = require('csso');
60var ast = csso.syntax.parse('.test { color: #ff0000; }');
61var compressedAst = csso.syntax.compress(ast).ast;
62var minifiedCss = csso.syntax.generate(compressedAst);
63
64console.log(minifiedCss);
65// .test{color:red}
66```
67
68> 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.
69
70### minify(source[, options])
71
72Minify `source` CSS passed as `String`.
73
74```js
75var result = csso.minify('.test { color: #ff0000; }', {
76 restructure: false, // don't change CSS structure, i.e. don't merge declarations, rulesets etc
77 debug: true // show additional debug information:
78 // true or number from 1 to 3 (greater number - more details)
79});
80
81console.log(result.css);
82// > .test{color:red}
83```
84
85Returns an object with properties:
86
87- css `String` – resulting CSS
88- map `Object` – instance of [`SourceMapGenerator`](https://github.com/mozilla/source-map#sourcemapgenerator) or `null`
89
90Options:
91
92- sourceMap
93
94 Type: `Boolean`
95 Default: `false`
96
97 Generate a source map when `true`.
98
99- filename
100
101 Type: `String`
102 Default: `'<unknown>'`
103
104 Filename of input CSS, uses for source map generation.
105
106- debug
107
108 Type: `Boolean`
109 Default: `false`
110
111 Output debug information to `stderr`.
112
113- beforeCompress
114
115 Type: `function(ast, options)` or `Array<function(ast, options)>` or `null`
116 Default: `null`
117
118 Called right after parse is run.
119
120- afterCompress
121
122 Type: `function(compressResult, options)` or `Array<function(compressResult, options)>` or `null`
123 Default: `null`
124
125 Called right after [`syntax.compress()`](#syntaxcompressast-options) is run.
126
127- Other options are the same as for [`syntax.compress()`](#syntaxcompressast-options) function.
128
129### minifyBlock(source[, options])
130
131The same as `minify()` but for list of declarations. Usually it's a `style` attribute value.
132
133```js
134var result = csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000');
135
136console.log(result.css);
137// > color:red
138```
139
140### syntax.compress(ast[, options])
141
142Does the main task – compress an AST. This is CSSO's extension in CSSTree syntax API.
143
144> 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.
145
146Returns an object with properties:
147
148- ast `Object` – resulting AST
149
150Options:
151
152- restructure
153
154 Type: `Boolean`
155 Default: `true`
156
157 Disable or enable a structure optimisations.
158
159- forceMediaMerge
160
161 Type: `Boolean`
162 Default: `false`
163
164 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.
165
166- clone
167
168 Type: `Boolean`
169 Default: `false`
170
171 Transform a copy of input AST if `true`. Useful in case of AST reuse.
172
173- comments
174
175 Type: `String` or `Boolean`
176 Default: `true`
177
178 Specify what comments to leave:
179
180 - `'exclamation'` or `true` – leave all exclamation comments (i.e. `/*! .. */`)
181 - `'first-exclamation'` – remove every comment except first one
182 - `false` – remove all comments
183
184- usage
185
186 Type: `Object` or `null`
187 Default: `null`
188
189 Usage data for advanced optimisations (see [Usage data](#usage-data) for details)
190
191- logger
192
193 Type: `Function` or `null`
194 Default: `null`
195
196 Function to track every step of transformation.
197
198### Source maps
199
200To 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.
201
202```js
203var csso = require('csso');
204var css = fs.readFileSync('path/to/my.css', 'utf8');
205var result = csso.minify(css, {
206 filename: 'path/to/my.css', // will be added to source map as reference to source file
207 sourceMap: true // generate source map
208});
209
210console.log(result);
211// { css: '...minified...', map: SourceMapGenerator {} }
212
213console.log(result.map.toString());
214// '{ .. source map content .. }'
215```
216
217Example of generating source map with respect of source map from input CSS:
218
219```js
220var require('source-map');
221var csso = require('csso');
222var inputFile = 'path/to/my.css';
223var input = fs.readFileSync(inputFile, 'utf8');
224var inputMap = input.match(/\/\*# sourceMappingURL=(\S+)\s*\*\/\s*$/);
225var output = csso.minify(input, {
226 filename: inputFile,
227 sourceMap: true
228});
229
230// apply input source map to output
231if (inputMap) {
232 output.map.applySourceMap(
233 new SourceMapConsumer(inputMap[1]),
234 inputFile
235 )
236}
237
238// result CSS with source map
239console.log(
240 output.css +
241 '/*# sourceMappingURL=data:application/json;base64,' +
242 new Buffer(output.map.toString()).toString('base64') +
243 ' */'
244);
245```
246
247### Usage data
248
249`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:
250
251- `blacklist` – a set of black lists (see [Black list filtering](#black-list-filtering))
252- `tags` – white list of tags
253- `ids` – white list of ids
254- `classes` – white list of classes
255- `scopes` – groups of classes which never used with classes from other groups on the same element
256
257All 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.
258
259#### White list filtering
260
261`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.
262
263> `ids` and `classes` are case sensitive, `tags` – is not.
264
265Input CSS:
266
267```css
268* { color: green; }
269ul, ol, li { color: blue; }
270UL.foo, span.bar { color: red; }
271```
272
273Usage data:
274
275```json
276{
277 "tags": ["ul", "LI"]
278}
279```
280
281Resulting CSS:
282
283```css
284*{color:green}ul,li{color:blue}ul.foo{color:red}
285```
286
287Filtering 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:
288
289```css
290:nth-child(2n of ul, ol) { color: red }
291:nth-child(3n + 1 of img) { color: yellow }
292:not(div, ol, ul) { color: green }
293:has(:matches(ul, ol), ul, ol) { color: blue }
294```
295
296Turns into:
297
298```css
299:nth-child(2n of ul){color:red}:not(div,ol,ul){color:green}:has(:matches(ul),ul){color:blue}
300```
301
302#### Black list filtering
303
304Black 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`.
305
306Black 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.
307
308```css
309* { color: green; }
310ul, ol, li { color: blue; }
311UL.foo, li.bar { color: red; }
312```
313
314Usage data:
315
316```json
317{
318 "blacklist": {
319 "tags": ["ul"]
320 },
321 "tags": ["ul", "LI"]
322}
323```
324
325Resulting CSS:
326
327```css
328*{color:green}li{color:blue}li.bar{color:red}
329```
330
331#### Scopes
332
333Scopes 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.
334
335Suppose we have a file:
336
337```css
338.module1-foo { color: red; }
339.module1-bar { font-size: 1.5em; background: yellow; }
340
341.module2-baz { color: red; }
342.module2-qux { font-size: 1.5em; background: yellow; width: 50px; }
343```
344
345It 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:
346
347```css
348.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}
349```
350
351With usage data `CSSO` can produce better output. If follow usage data is provided:
352
353```json
354{
355 "scopes": [
356 ["module1-foo", "module1-bar"],
357 ["module2-baz", "module2-qux"]
358 ]
359}
360```
361
362The result will be (29 bytes extra saving):
363
364```css
365.module1-foo,.module2-baz{color:red}.module1-bar,.module2-qux{font-size:1.5em;background:#ff0}.module2-qux{width:50px}
366```
367
368If 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.
369
370Note 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.
371
372Currently 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.