UNPKG

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