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