- Notifications
You must be signed in to change notification settings - Fork187
CSS minifier with structural optimizations
License
css/csso
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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.
npm install csso
import{minify}from'csso';// CommonJS is also supported// const { minify } = require('csso');constminifiedCss=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 withcsso
as global
<scriptsrc="node_modules/csso/dist/csso.js"></script><script>csso.minify('.example { color: green }');</script>
dist/csso.esm.js
– minified ES module
<scripttype="module">import{minify}from'node_modules/csso/dist/csso.esm.js'minify('.example { color: green }');</script>
One of CDN services likeunpkg
orjsDelivr
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:
<!-- ESM --><scripttype="module">import*ascsstreefrom'https://cdn.jsdelivr.net/npm/csso';import*ascsstreefrom'https://unpkg.com/csso';</script><!-- IIFE with an export to global --><scriptsrc="https://cdn.jsdelivr.net/npm/csso/dist/csso.js"></script><scriptsrc="https://unpkg.com/csso/dist/csso.js"></script>
CSSO is based onCSSTree to parse CSS into AST, AST traversal and to generate AST back to CSS. AllCSSTree
API is available behindsyntax
field extended withcompress()
method. You may minify CSS step by step:
import{syntax}from'csso';constast=syntax.parse('.test { color: #ff0000; }');constcompressedAst=syntax.compress(ast).ast;constminifiedCss=syntax.generate(compressedAst);console.log(minifiedCss);// .test{color:red}
Also syntax can be imported usingcsso/syntax
entry point:
import{parse,compress,generate}from'csso/syntax';constast=parse('.test { color: #ff0000; }');constcompressedAst=compress(ast).ast;constminifiedCss=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 onsyntax
API, a better option might be to use CSSTree directly.
- Web interface
- csso-cli – command line interface
- gulp-csso –
Gulp
plugin - grunt-csso –
Grunt
plugin - broccoli-csso –
Broccoli
plugin - postcss-csso –
PostCSS
plugin - csso-loader –
webpack
loader - csso-webpack-plugin –
webpack
plugin - CSSO Visual Studio Code plugin
- vscode-csso - Visual Studio Code plugin
- atom-csso - Atom plugin
- Sublime-csso - Sublime plugin
- minify(source[, options])
- minifyBlock(source[, options])
- syntax.compress(ast[, options])
- Source maps
- Usage data
Minifysource
CSS passed asString
.
constresult=csso.minify('.test { color: #ff0000; }',{restructure:false,// don't change CSS structure, i.e. don't merge declarations, rulesets etcdebug: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 ofSourceMapGenerator
ornull
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)
orArray<function(ast, options)>
ornull
Default:null
Called right after parse is run.
afterCompress
Type:
function(compressResult, options)
orArray<function(compressResult, options)>
ornull
Default:null
Called right after
syntax.compress()
is run.Other options are the same as for
syntax.compress()
function.
The same asminify()
but for list of declarations. Usually it's astyle
attribute value.
constresult=csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000');console.log(result.css);// > color:red
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). Useclone
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
orBoolean
Default:true
Specify what comments to leave:
'exclamation'
ortrue
– leave all exclamation comments (i.e./*! .. */
)'first-exclamation'
– remove every comment except first onefalse
– remove all comments
usage
Type:
Object
ornull
Default:null
Usage data for advanced optimisations (seeUsage data for details)
logger
Type:
Function
ornull
Default:null
Function to track every step of transformation.
To get a source map settrue
forsourceMap
option. Additianalyfilename
option can be passed to specify source file. WhensourceMap
option istrue
,map
field of result object will contain aSourceMapGenerator
instance. This object can be mixed with another source map or translated to string.
constcsso=require('csso');constcss=fs.readFileSync('path/to/my.css','utf8');constresult=csso.minify(css,{filename:'path/to/my.css',// will be added to source map as reference to source filesourceMap: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:
import{SourceMapConsumer}from'source-map';import*ascssofrom'csso';constinputFile='path/to/my.css';constinput=fs.readFileSync(inputFile,'utf8');constinputMap=input.match(/\/\*#sourceMappingURL=(\S+)\s*\*\/\s*$/);constoutput=csso.minify(input,{filename:inputFile,sourceMap:true});// apply input source map to outputif(inputMap){output.map.applySourceMap(newSourceMapConsumer(inputMap[1]),inputFile)}// result CSS with source mapconsole.log(output.css+'/*# sourceMappingURL=data:application/json;base64,'+Buffer.from(output.map.toString()).toString('base64')+' */');
CSSO
can use data about howCSS
is used in a markup for better compression. File with this data (JSON
) can be set usingusage
option. Usage data may contain following sections:
blacklist
– a set of black lists (seeBlack list filtering)tags
– white list of tagsids
– white list of idsclasses
– white list of classesscopes
– groups of classes which never used with classes from other groups on the same element
All sections are optional. Value oftags
,ids
andclasses
should be an array of a string, value ofscopes
should be an array of arrays of strings. Other values are ignoring.
tags
,ids
andclasses
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 onlytags
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
andclasses
are case sensitive,tags
– is not.
Input CSS:
* {color: green; }ul,ol,li {color: blue; }UL.foo,span.bar {color: red; }
Usage data:
{"tags": ["ul","LI"]}
Resulting 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:
:nth-child(2n oful,ol) {color: red }:nth-child(3n + 1 ofimg) {color: yellow }:not(div,ol,ul) {color: green }:has(:matches(ul,ol),ul,ol) {color: blue }
Turns into:
:nth-child(2n oful){color:red}:not(div,ol,ul){color:green}:has(:matches(ul),ul){color:blue}
Black list filtering performs the same as white list filtering, but filters things that mentioned in the lists.blacklist
can contain the liststags
,ids
andclasses
.
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.
* {color: green; }ul,ol,li {color: blue; }UL.foo,li.bar {color: red; }
Usage data:
{"blacklist": {"tags": ["ul"] },"tags": ["ul","LI"]}
Resulting CSS:
*{color:green}li{color:blue}li.bar{color:red}
Scopes is designed for CSS scope isolation solutions such ascss-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:
.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:
.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 dataCSSO
can produce better output. If follow usage data is provided:
{"scopes": [ ["module1-foo","module1-bar"], ["module2-baz","module2-qux"] ]}
The result will be (29 bytes extra saving):
.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 thescopes
it belongs to default scope.scopes
data doesn't affectclasses
whitelist. If class name mentioned inscopes
but missed inclasses
(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.
About
CSS minifier with structural optimizations