csso vs clean-css vs cssnano vs uglifycss vs postcss-clean vs postcss-minify
CSS Minification Tools Comparison
3 Years
cssoclean-csscssnanouglifycsspostcss-cleanpostcss-minifySimilar Packages:
What's CSS Minification Tools?

CSS minification tools are essential in web development for optimizing CSS files by removing unnecessary characters, such as whitespace, comments, and line breaks, without affecting the functionality of the styles. This process reduces the file size, leading to faster load times and improved performance for websites and applications. Minification is a crucial step in the build process, especially for production environments, as it helps decrease bandwidth usage and enhances the overall user experience. Tools like clean-css, cssnano, and uglifycss offer various features and levels of customization for efficient CSS minification.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
csso18,460,974
3,788606 kB103-MIT
clean-css17,854,074
4,197493 kB402 years agoMIT
cssnano13,412,827
4,8857.37 kB10219 days agoMIT
uglifycss59,297
282-107 years agoMIT
postcss-clean28,237
42-124 years agoMIT
postcss-minify22,166
68.22 kB02 months agoMIT
Feature Comparison: csso vs clean-css vs cssnano vs uglifycss vs postcss-clean vs postcss-minify

Minification and Optimization

  • csso:

    csso (CSS Optimizer) not only minifies CSS but also optimizes its structure, potentially leading to smaller file sizes. It performs advanced optimizations like merging and reordering rules, making it effective for both minification and optimization tasks.

  • clean-css:

    clean-css provides advanced minification with multiple optimization levels, allowing users to choose the balance between speed and output size. It supports merging, restructuring, and removing duplicate rules, making it highly efficient for large CSS files.

  • cssnano:

    cssnano focuses on producing the smallest possible CSS by applying a series of optimizations. It is modular, allowing users to enable or disable specific optimizations based on their needs, which makes it flexible and efficient for modern workflows.

  • uglifycss:

    uglifycss is a command-line tool that minifies CSS files by removing whitespace, comments, and other unnecessary characters. It is simple to use and can be integrated into build processes, making it a practical choice for quick and effective minification.

  • postcss-clean:

    postcss-clean is a simple PostCSS plugin that removes whitespace, comments, and other unnecessary characters from CSS. It is lightweight and easy to use, making it suitable for projects that require basic minification without complex configurations.

  • postcss-minify:

    postcss-minify is another PostCSS plugin that focuses on minifying CSS by removing redundant whitespace and comments. It is straightforward and integrates well with other PostCSS plugins, providing a no-frills solution for CSS minification.

Integration with Build Tools

  • csso:

    csso can be integrated into build tools like Gulp and Webpack, and it also provides a command-line interface. Its ability to optimize CSS structure makes it a valuable addition to any build pipeline focused on CSS performance.

  • clean-css:

    clean-css can be easily integrated into various build tools and task runners like Gulp, Webpack, and Grunt. It offers both a command-line interface and an API, providing flexibility for different workflows.

  • cssnano:

    cssnano is designed to work seamlessly with PostCSS, making it an excellent choice for projects that already use PostCSS in their build process. It can be easily configured in PostCSS setups, allowing for smooth integration.

  • uglifycss:

    uglifycss is a standalone tool that can be integrated into build processes via scripts. Its simplicity and command-line interface make it easy to use in automated workflows, although it may not offer the same level of integration as plugin-based solutions.

  • postcss-clean:

    postcss-clean is a PostCSS plugin, which means it integrates effortlessly into any PostCSS workflow. It requires minimal setup and works well alongside other PostCSS plugins, making it a great choice for projects using the PostCSS ecosystem.

  • postcss-minify:

    postcss-minify integrates easily with PostCSS workflows, providing a simple and effective minification solution. Its compatibility with other PostCSS plugins allows for flexible and efficient build processes.

Customization and Configuration

  • csso:

    csso provides some customization options, particularly around its optimization algorithms. However, it is more focused on providing effective optimization out of the box, which may limit configurability compared to more modular tools like cssnano.

  • clean-css:

    clean-css offers extensive customization options, including the ability to set optimization levels, control the handling of colors, URLs, and more. Its API allows for fine-tuning, making it suitable for projects that require specific minification settings.

  • cssnano:

    cssnano is highly configurable, allowing users to enable or disable specific optimization plugins based on their needs. Its modular design means that developers can customize the minification process to suit their project requirements easily.

  • uglifycss:

    uglifycss allows for some customization, such as setting the level of minification and choosing whether to preserve certain comments. However, it is relatively straightforward and does not offer extensive configurability, making it easy to use for quick minification tasks.

  • postcss-clean:

    postcss-clean is a straightforward plugin with minimal configuration options. It is designed to be simple and effective, so it does not offer extensive customization features, making it easy to use without much setup.

  • postcss-minify:

    postcss-minify offers basic customization for minification but is generally designed to be used with default settings. Its simplicity means that it does not have a wide range of configurable options, which keeps it easy to use but limits flexibility.

Ease of Use: Code Examples

  • csso:

    Minification with csso

    const csso = require('csso');
    const inputCSS = 'body { color: red; }';
    const output = csso.minify(inputCSS);
    console.log(output.css);
    
  • clean-css:

    Minification with clean-css

    const CleanCSS = require('clean-css');
    const inputCSS = 'body { color: red; }';
    const output = new CleanCSS().minify(inputCSS);
    console.log(output.styles);
    
  • cssnano:

    Minification with cssnano

    const postcss = require('postcss');
    const cssnano = require('cssnano');
    const inputCSS = 'body { color: red; }';
    postcss([cssnano()]).process(inputCSS, { from: undefined }).then(result => {
      console.log(result.css);
    });
    
  • uglifycss:

    Minification with uglifycss

    const uglifycss = require('uglifycss');
    const inputCSS = 'body { color: red; }';
    const output = uglifycss.processString(inputCSS);
    console.log(output);
    
  • postcss-clean:

    Minification with postcss-clean

    const postcss = require('postcss');
    const postcssClean = require('postcss-clean');
    const inputCSS = 'body { color: red; }';
    postcss([postcssClean()]).process(inputCSS, { from: undefined }).then(result => {
      console.log(result.css);
    });
    
  • postcss-minify:

    Minification with postcss-minify

    const postcss = require('postcss');
    const postcssMinify = require('postcss-minify');
    const inputCSS = 'body { color: red; }';
    postcss([postcssMinify()]).process(inputCSS, { from: undefined }).then(result => {
      console.log(result.css);
    });
    
How to Choose: csso vs clean-css vs cssnano vs uglifycss vs postcss-clean vs postcss-minify
  • csso:

    Opt for csso if you want a minifier that also performs CSS optimization and restructuring, potentially leading to smaller file sizes. It is particularly useful for projects where both minification and structural optimization are desired.

  • clean-css:

    Choose clean-css if you need a fast and efficient CSS minifier that offers a high level of customization and optimization. It is suitable for both small and large projects, providing a good balance between speed and output quality.

  • cssnano:

    Select cssnano if you are looking for a modern, PostCSS-based minifier that integrates well with other PostCSS plugins. It is highly configurable and focuses on producing the smallest possible CSS output while maintaining quality.

  • uglifycss:

    Select uglifycss if you prefer a straightforward command-line tool for CSS minification that also offers some optimization features. It is easy to use and integrates well into build processes, making it a good choice for quick minification tasks.

  • postcss-clean:

    Use postcss-clean if you are already using PostCSS and need a simple, lightweight minification solution that works as a PostCSS plugin. It is easy to integrate into existing workflows and provides basic minification features.

  • postcss-minify:

    Choose postcss-minify for a straightforward minification solution that works within the PostCSS ecosystem. It is simple to use and effective for projects that require basic minification without additional overhead.

README for csso

NPM version Build Status Coverage Status NPM Downloads Twitter

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 with csso as 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 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

API

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:

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.

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). 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 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 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 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:

* { 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 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:

: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.

* { 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

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:

.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 data CSSO 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 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.