Gathering detailed insights and metrics for csso
Gathering detailed insights and metrics for csso
Gathering detailed insights and metrics for csso
Gathering detailed insights and metrics for csso
npm install csso
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
3,767 Stars
1,088 Commits
186 Forks
94 Watching
8 Branches
51 Contributors
Updated on 26 Nov 2024
JavaScript (61.31%)
CSS (34.04%)
HTML (4.65%)
Cumulative downloads
Total Downloads
Last day
-4%
3,051,344
Compared to previous day
Last week
2.5%
16,015,284
Compared to previous week
Last month
11.6%
67,417,241
Compared to previous month
Last year
8.5%
736,651,903
Compared to previous year
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
1import { minify } from 'csso'; 2// CommonJS is also supported 3// const { minify } = require('csso'); 4 5const minifiedCss = minify('.test { color: #ff0000; }').css; 6 7console.log(minifiedCss); 8// .test{color:red}
Bundles are also available for use in a browser:
dist/csso.js
– minified IIFE with csso
as global1<script src="node_modules/csso/dist/csso.js"></script> 2<script> 3 csso.minify('.example { color: green }'); 4</script>
dist/csso.esm.js
– minified ES module1<script type="module"> 2 import { minify } from 'node_modules/csso/dist/csso.esm.js' 3 4 minify('.example { color: green }'); 5</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:
1<!-- ESM --> 2<script type="module"> 3 import * as csstree from 'https://cdn.jsdelivr.net/npm/csso'; 4 import * as csstree from 'https://unpkg.com/csso'; 5</script> 6 7<!-- IIFE with an export to global --> 8<script src="https://cdn.jsdelivr.net/npm/csso/dist/csso.js"></script> 9<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:
1import { syntax } from 'csso'; 2 3const ast = syntax.parse('.test { color: #ff0000; }'); 4const compressedAst = syntax.compress(ast).ast; 5const minifiedCss = syntax.generate(compressedAst); 6 7console.log(minifiedCss); 8// .test{color:red}
Also syntax can be imported using csso/syntax
entry point:
1import { parse, compress, generate } from 'csso/syntax'; 2 3const ast = parse('.test { color: #ff0000; }'); 4const compressedAst = compress(ast).ast; 5const minifiedCss = generate(compressedAst); 6 7console.log(minifiedCss); 8// .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.
Gulp
pluginGrunt
pluginBroccoli
pluginPostCSS
pluginwebpack
loaderwebpack
pluginMinify source
CSS passed as String
.
1const result = csso.minify('.test { color: #ff0000; }', { 2 restructure: false, // don't change CSS structure, i.e. don't merge declarations, rulesets etc 3 debug: true // show additional debug information: 4 // true or number from 1 to 3 (greater number - more details) 5}); 6 7console.log(result.css); 8// > .test{color:red}
Returns an object with properties:
String
– resulting CSSObject
– instance of 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()
is run.
Other options are the same as for syntax.compress()
function.
The same as minify()
but for list of declarations. Usually it's a style
attribute value.
1const result = csso.minifyBlock('color: rgba(255, 0, 0, 1); color: #ff0000'); 2 3console.log(result.css); 4// > 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:
Object
– resulting ASTOptions:
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 onefalse
– remove all commentsusage
Type: Object
or null
Default: null
Usage data for advanced optimisations (see Usage data for details)
logger
Type: Function
or null
Default: null
Function to track every step of transformation.
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.
1const csso = require('csso'); 2const css = fs.readFileSync('path/to/my.css', 'utf8'); 3const result = csso.minify(css, { 4 filename: 'path/to/my.css', // will be added to source map as reference to source file 5 sourceMap: true // generate source map 6}); 7 8console.log(result); 9// { css: '...minified...', map: SourceMapGenerator {} } 10 11console.log(result.map.toString()); 12// '{ .. source map content .. }'
Example of generating source map with respect of source map from input CSS:
1import { SourceMapConsumer } from 'source-map'; 2import * as csso from 'csso'; 3 4const inputFile = 'path/to/my.css'; 5const input = fs.readFileSync(inputFile, 'utf8'); 6const inputMap = input.match(/\/\*# sourceMappingURL=(\S+)\s*\*\/\s*$/); 7const output = csso.minify(input, { 8 filename: inputFile, 9 sourceMap: true 10}); 11 12// apply input source map to output 13if (inputMap) { 14 output.map.applySourceMap( 15 new SourceMapConsumer(inputMap[1]), 16 inputFile 17 ) 18} 19 20// result CSS with source map 21console.log( 22 output.css + 23 '/*# sourceMappingURL=data:application/json;base64,' + 24 Buffer.from(output.map.toString()).toString('base64') + 25 ' */' 26);
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 elementAll 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.
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
andclasses
are case sensitive,tags
– is not.
Input CSS:
1* { color: green; } 2ul, ol, li { color: blue; } 3UL.foo, span.bar { color: red; }
Usage data:
1{ 2 "tags": ["ul", "LI"] 3}
Resulting CSS:
1*{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:
1:nth-child(2n of ul, ol) { color: red } 2:nth-child(3n + 1 of img) { color: yellow } 3:not(div, ol, ul) { color: green } 4:has(:matches(ul, ol), ul, ol) { color: blue }
Turns into:
1:nth-child(2n of ul){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 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.
1* { color: green; } 2ul, ol, li { color: blue; } 3UL.foo, li.bar { color: red; }
Usage data:
1{ 2 "blacklist": { 3 "tags": ["ul"] 4 }, 5 "tags": ["ul", "LI"] 6}
Resulting CSS:
1*{color:green}li{color:blue}li.bar{color:red}
Scopes is designed for CSS scope isolation solutions such as 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:
1.module1-foo { color: red; } 2.module1-bar { font-size: 1.5em; background: yellow; } 3 4.module2-baz { color: red; } 5.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:
1.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:
1{ 2 "scopes": [ 3 ["module1-foo", "module1-bar"], 4 ["module2-baz", "module2-qux"] 5 ] 6}
The result will be (29 bytes extra saving):
1.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.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 5
Details
Reason
6 existing vulnerabilities detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More