Csso
CSS minifier with structural optimizations
Install / Use
/learn @css/CssoREADME
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
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 withcssoas global
<script src="node_modules/csso/dist/csso.js"></script>
<script>
csso.minify('.example { color: green }');
</script>
dist/csso.esm.js– minified ES module
<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:
<!-- 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 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:
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:
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
syntaxfield as well as AST format. Both might be changed with changes in CSSTree. If you rely heavily onsyntaxAPI, a better option might be to use CSSTree directly.
Related projects
- Web interface
- csso-cli – command line interface
- gulp-csso –
Gulpplugin - grunt-csso –
Gruntplugin - broccoli-csso –
Broccoliplugin - postcss-csso –
PostCSSplugin - csso-loader –
webpackloader - csso-webpack-plugin –
webpackplugin - CSSO Visual Studio Code plugin
- vscode-csso - Visual Studio Code plugin
- atom-csso - Atom plugin
- Sublime-csso - Sublime plugin
API
<!-- TOC depthfrom:3 -->- minify(source[, options])
- minifyBlock(source[, options])
- syntax.compress(ast[, options])
- Source maps
- Usage data
minify(source[, options])
Minify source CSS passed as String.
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 ofSourceMapGeneratorornull
Options:
-
sourceMap
Type:
Boolean
Default:falseGenerate a source map when
true. -
filename
Type:
String
Default:'<unknown>'Filename of input CSS, uses for source map generation.
-
debug
Type:
Boolean
Default:falseOutput debug information to
stderr. -
beforeCompress
Type:
function(ast, options)orArray<function(ast, options)>ornull
Default:nullCalled right after parse is run.
-
afterCompress
Type:
function(compressResult, options)orArray<function(compressResult, options)>ornull
Default:nullCalled right after
syntax.compress()is run. -
Other options are the same as for
syntax.compress()function.
minifyBlock(source[, options])
The same as minify() but for list of declarations. Usually it's a style attribute value.
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). Usecloneoption 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:trueDisable or enable a structure optimisations.
-
forceMediaMerge
Type:
Boolean
Default:falseEnables merging of
@mediarules 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:falseTransform a copy of input AST if
true. Useful in case of AST reuse. -
comments
Type:
StringorBoolean
Default:trueSpecify 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:
Objectornull
Default:nullUsage data for advanced optimisations (see Usage data for details)
-
logger
Type:
Functionornull
Default:nullFunction 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 instance. This object can be mixed with another source map or translated to string.
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:
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)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 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 whit
