csso vs clean-css vs cssnano vs postcss-minify vs postcss-clean vs uglifycss
CSS 和 JS 文件压缩
cssoclean-csscssnanopostcss-minifypostcss-cleanuglifycss類似パッケージ:

CSS 和 JS 文件压缩

CSS 和 JS 文件压缩库是用于优化网页性能的工具,它们通过减少文件大小来加快网页加载速度。这些库通过删除多余的空格、注释和换行符,甚至通过合并和重排代码来实现压缩。压缩后的文件占用更少的带宽,加载速度更快,从而提高用户体验和搜索引擎排名。clean-css 是一个高性能的 CSS 压缩工具,支持多种压缩级别和优化选项。cssnano 是一个基于 PostCSS 的 CSS 压缩工具,提供模块化的插件系统,允许开发者根据需要选择压缩功能。csso 是一个 CSS 优化和压缩工具,专注于结构化优化,能够有效减少 CSS 文件大小。postcss-clean 是一个 PostCSS 插件,专注于清理和压缩 CSS 代码,删除多余的空格和注释。postcss-minify 是另一个 PostCSS 插件,提供 CSS 代码压缩功能,支持多种优化策略。uglifycss 是一个简单的 CSS 压缩工具,主要通过删除空格、注释和其他冗余字符来减小文件大小。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
csso20,710,6183,798606 kB104-MIT
clean-css18,334,1684,202493 kB422年前MIT
cssnano13,802,7234,9557.37 kB1034ヶ月前MIT
postcss-minify34,03178.22 kB09ヶ月前MIT
postcss-clean13,36643-125年前MIT
uglifycss0281-108年前MIT

機能比較: csso vs clean-css vs cssnano vs postcss-minify vs postcss-clean vs uglifycss

压缩效果

  • csso:

    csso 采用结构化优化算法,能够在保持样式一致的情况下,显著减少 CSS 文件大小。

  • clean-css:

    clean-css 提供高效的压缩效果,支持多级压缩,能够根据配置选择最优压缩策略。

  • cssnano:

    cssnano 通过一系列模块化插件实现压缩,压缩效果依赖于启用的插件,灵活性高。

  • postcss-minify:

    postcss-minify 提供多种压缩策略,压缩效果可根据配置调整,灵活性较好。

  • postcss-clean:

    postcss-clean 主要通过删除多余空格和注释来实现压缩,效果简单直接。

  • uglifycss:

    uglifycss 通过简单的算法删除空格和注释,压缩效果较为基础,适合快速处理。

集成方式

  • csso:

    csso 支持独立使用,也可以作为 PostCSS 插件集成,适合多种工作流。

  • clean-css:

    clean-css 可以作为独立工具使用,也可以集成到构建系统中,如 Webpack、Gulp 等。

  • cssnano:

    cssnano 作为 PostCSS 插件集成,适合与其他 PostCSS 插件一起使用,灵活性高。

  • postcss-minify:

    postcss-minify 也是 PostCSS 插件,支持与其他插件组合使用,灵活性好。

  • postcss-clean:

    postcss-clean 作为 PostCSS 插件,易于与其他插件结合使用,集成简单。

  • uglifycss:

    uglifycss 提供命令行工具,易于快速集成到构建流程中。

配置灵活性

  • csso:

    csso 提供一定的配置选项,特别是在结构优化方面,但相对较少。

  • clean-css:

    clean-css 提供丰富的配置选项,支持细粒度控制压缩过程,适合需要精细调优的项目。

  • cssnano:

    cssnano 通过插件系统提供灵活配置,开发者可以根据需要选择启用的压缩功能。

  • postcss-minify:

    postcss-minify 提供多种配置选项,特别是在选择压缩策略方面,灵活性较好。

  • postcss-clean:

    postcss-clean 配置简单,主要集中在清理和压缩,灵活性有限。

  • uglifycss:

    uglifycss 配置简单,主要针对压缩参数,灵活性较低。

社区和维护

  • csso:

    csso 也有活跃的社区,特别是在 CSS 结构优化方面,持续进行开发和改进。

  • clean-css:

    clean-css 拥有活跃的社区和持续的维护,定期更新以优化性能和兼容性。

  • cssnano:

    cssnano 作为 PostCSS 生态的一部分,拥有活跃的开发者社区,持续更新和维护。

  • postcss-minify:

    postcss-minify 社区活跃,特别是在前端开发者中,持续进行更新和优化。

  • postcss-clean:

    postcss-clean 作为 PostCSS 插件,社区相对较小,但维护较为稳定。

  • uglifycss:

    uglifycss 社区较小,但工具简单易用,维护相对稳定。

代码示例

  • csso:

    使用 csso 压缩 CSS

    const csso = require('csso');
    const inputCSS = 'body { color: red; }';
    const outputCSS = csso.minify(inputCSS).css;
    console.log(outputCSS); // 输出压缩后的 CSS
    
  • clean-css:

    使用 clean-css 压缩 CSS

    const cleanCSS = require('clean-css');
    const inputCSS = 'body { color: red; }';
    const outputCSS = new cleanCSS().minify(inputCSS).styles;
    console.log(outputCSS); // 输出压缩后的 CSS
    
  • cssnano:

    使用 cssnano 压缩 CSS

    const postcss = require('postcss');
    const cssnano = require('cssnano');
    const inputCSS = 'body { color: red; }';
    postcss([cssnano()])
      .process(inputCSS)
      .then(result => {
        console.log(result.css); // 输出压缩后的 CSS
      });
    
  • postcss-minify:

    使用 postcss-minify 压缩 CSS

    const postcss = require('postcss');
    const minify = require('postcss-minify');
    const inputCSS = 'body { color: red; }';
    postcss([minify()])
      .process(inputCSS)
      .then(result => {
        console.log(result.css); // 输出压缩后的 CSS
      });
    
  • postcss-clean:

    使用 postcss-clean 压缩 CSS

    const postcss = require('postcss');
    const clean = require('postcss-clean');
    const inputCSS = 'body { color: red; }';
    postcss([clean()])
      .process(inputCSS)
      .then(result => {
        console.log(result.css); // 输出压缩后的 CSS
      });
    
  • uglifycss:

    使用 uglifycss 压缩 CSS

    const uglifycss = require('uglifycss');
    const inputCSS = 'body { color: red; }';
    const outputCSS = uglifycss.processString(inputCSS);
    console.log(outputCSS); // 输出压缩后的 CSS
    

選び方: csso vs clean-css vs cssnano vs postcss-minify vs postcss-clean vs uglifycss

  • csso:

    选择 csso 如果你需要一个专注于结构优化的 CSS 压缩工具,能够在保持样式的同时显著减少文件大小。它适合对 CSS 结构优化有要求的项目。

  • clean-css:

    选择 clean-css 如果你需要一个高性能的 CSS 压缩工具,支持多种压缩级别和详细配置。它适合需要精细控制压缩过程的项目。

  • cssnano:

    选择 cssnano 如果你正在使用 PostCSS,并且希望通过插件系统灵活地配置 CSS 压缩。它适合现代前端工作流,特别是与其他 PostCSS 插件结合使用时。

  • postcss-minify:

    选择 postcss-minify 如果你需要一个灵活的 PostCSS 插件,提供多种 CSS 压缩优化策略。它适合需要定制化压缩的项目。

  • postcss-clean:

    选择 postcss-clean 如果你需要一个简单的 PostCSS 插件,专注于清理和压缩 CSS 代码。它适合需要快速集成的轻量级解决方案。

  • uglifycss:

    选择 uglifycss 如果你需要一个简单易用的 CSS 压缩工具,快速删除空格和注释。它适合对压缩效果要求不高的项目,且希望快速集成。

csso のREADME

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.