clean-css、cssnano、csso、postcss-clean はすべて CSS ファイルを圧縮・最適化するための npm パッケージです。これらは不要な空白、コメント、冗長な記述を削除し、ファイルサイズを小さくすることで、Web アプリケーションの読み込み速度を向上させます。cssnano と postcss-clean は PostCSS プラグインとして動作し、ビルドパイプラインに簡単に統合できます。一方、clean-css と csso はスタンドアロンのライブラリとして設計されており、独自の API を通じて直接利用可能です。postcss-clean は内部で clean-css を使用しており、PostCSS 環境で clean-css の機能を利用したい場合に便利です。
CSS の圧縮は、現代のフロントエンド開発において必須の最適化ステップです。clean-css、cssnano、csso、postcss-clean はいずれも CSS を小さく・高速にするための代表的なツールですが、それぞれ設計思想や統合方法、機能セットが異なります。この記事では、プロフェッショナルな開発者がアーキテクチャ選定を行う際に役立つ、実践的な観点から深く比較します。
各パッケージは、CLI、Node.js API、または PostCSS プラグインとして利用できますが、その対応状況は異なります。
clean-css はスタンドアロンの Node.js ライブラリとして設計されており、独自の API を提供します。PostCSS との連携は公式ではありませんが、サードパーティ製プラグイン経由で可能です。
// clean-css の基本的な Node.js 使用例
const CleanCSS = require('clean-css');
const output = new CleanCSS().minify('.foo { color: red; }');
console.log(output.styles);
cssnano は PostCSS プラグインとして設計されており、PostCSS のエコシステムに完全に統合されています。これにより、他の PostCSS プラグイン(例: Autoprefixer)と組み合わせて一貫した処理パイプラインを構築できます。
// cssnano の PostCSS での使用例
const postcss = require('postcss');
const cssnano = require('cssnano');
const result = await postcss([cssnano()]).process('.foo { color: red; }', { from: undefined });
console.log(result.css);
csso もスタンドアロンのライブラリで、独自の API を持ちます。PostCSS との統合は postcss-csso という別パッケージが必要です。
// csso の基本的な使用例
const csso = require('csso');
const minified = csso.minify('.foo { color: red; }').css;
console.log(minified);
postcss-clean は PostCSS プラグインであり、内部で clean-css をラップしています。つまり、clean-css の機能を PostCSS パイプライン内で直接使えるようにするラッパーです。
// postcss-clean の使用例
const postcss = require('postcss');
const clean = require('postcss-clean');
const result = await postcss([clean()]).process('.foo { color: red; }', { from: undefined });
console.log(result.css);
💡 注:
postcss-cleanはclean-cssを内部で使用しているため、clean-css単体で使うか、PostCSS 経由で使うかの違いに過ぎません。
各ツールは異なる最適化戦略を持ち、結果の CSS サイズや安全性に影響します。
clean-css は非常に包括的な最適化を提供し、以下のような高度な変換を行います:
.a{color:red}.b{color:red} → .a,.b{color:red})0px → 0)#ff0000 → red)設定オプションも豊富で、安全でない最適化(例: @import の再配置)を無効にすることも可能です。
// clean-css の詳細設定例
new CleanCSS({
level: {
1: { all: true }, // 基本最適化
2: { all: true } // 高度最適化(セレクタの結合など)
}
}).minify(css);
cssnano は「安全な最適化」を重視し、デフォルトでは CSS の意味を変えない変換のみを行います。ただし、preset: 'advanced' を有効にすることで、より積極的な最適化(例: セレクタの再順序付け)も可能です。
// cssnano のプリセット指定
const result = await postcss([
cssnano({ preset: 'default' }) // 安全な最適化のみ
]).process(css);
csso は構造的最適化(Structural Optimization)に特化しており、CSS の構文木を解析して冗長なルールを削除します。たとえば、同じセレクタが複数回現れた場合にマージしたり、上書きされるプロパティを削除したりします。
// csso は構造最適化に強い
const input = '.a{color:red}.a{color:blue}';
// 出力: .a{color:blue}
postcss-clean は内部で clean-css を使用するため、最適化内容は clean-css と同一です。違いは統合方法のみです。
clean-css は最も細かい制御が可能で、レベル1(単純置換)とレベル2(構造変更)の最適化を個別に有効/無効にできます。また、compatibility オプションで古いブラウザ向けの挙動も調整可能です。
cssnano は PostCSS のプラグインとして動作するため、他の PostCSS プラグインとの併用が自然です。また、個別の最適化プラグイン(例: postcss-discard-comments)を個別に有効化・無効化できます。
csso の設定オプションは比較的シンプルで、主に restructure(構造最適化の有効化)と debug(デバッグ出力)のみです。
postcss-clean は clean-css のオプションをそのまま渡すことができ、PostCSS パイプライン内で clean-css の全機能を利用できます。
// postcss-clean に clean-css のオプションを渡す
postcss([
clean({
level: 2,
compatibility: 'ie9'
})
])
clean-css: レベル2の最適化は、まれに意図しない副作用を引き起こす可能性があります(例: セレクタの結合により specificity が変わる)。ただし、compatibility オプションでリスクを軽減できます。cssnano: デフォルトプリセットは「安全」とされ、CSS の意味を変える変換は行いません。advanced プリセットを使用する場合は注意が必要です。csso: 構造最適化は理論的に安全ですが、動的クラス名や JavaScript によるランタイム操作に依存する場合、削除されたルールが問題になることがあります。postcss-clean: 内部が clean-css なので、同じ注意点が適用されます。cssnano// webpack.config.js
module.exports = {
module: {
rules: [{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: [require('cssnano')()]
}
}
]
}]
}
};
clean-css または csso// build.js
const fs = require('fs');
const CleanCSS = require('clean-css');
const minified = new CleanCSS().minify(fs.readFileSync('input.css', 'utf8'));
fs.writeFileSync('output.css', minified.styles);
postcss-cleanclean-css の全機能を利用できる。| パッケージ | 最適なユースケース |
|---|---|
clean-css | スタンドアロンで高度な最適化が必要な場合。細かい制御が可能な設定が求められるプロジェクト。 |
cssnano | PostCSS エコシステム内で安全な最適化を行いたい場合。標準的なビルドツール(Vite, Webpack, Rollup)との統合が容易。 |
csso | 構造的最適化に特化した軽量な圧縮が欲しい場合。シンプルな API と最小限の依存関係が好ましい環境。 |
postcss-clean | PostCSS パイプライン内で clean-css の機能を使いたい場合。既存の clean-css 設定を PostCSS に移行したいケース。 |
cssnano が第一候補 — エコシステムとの親和性が高く、安全で十分な最適化を提供します。clean-css(または postcss-clean) — 特に古いコードベースや複雑な CSS に対して効果的です。csso — 小規模プロジェクトや、最小限の依存関係を保ちたい場合に適しています。どのツールも成熟しており、プロジェクトのニーズに応じて選べば、どれも信頼できる結果を提供します。重要なのは、最適化の「安全性」と「圧縮率」のトレードオフを理解し、適切な設定を行うことです。
csso は、構造的最適化に特化した軽量な圧縮を求める場合に適しています。シンプルな API と最小限の依存関係を持つため、小規模プロジェクトや、依存関係を極力減らしたい環境で有効です。ただし、高度な最適化オプションは少なく、PostCSS との統合には別途 postcss-csso パッケージが必要です。
clean-css は、高度な最適化オプションと細かい制御を必要とするプロジェクトに最適です。特に、メディアクエリのマージやセレクタの結合など、積極的な圧縮が必要な場合や、PostCSS を使用せずにスタンドアロンで CSS 圧縮を行いたい場合に選択してください。ただし、レベル2の最適化はまれに副作用を引き起こす可能性があるため、テスト環境での検証が推奨されます。
cssnano は PostCSS エコシステム内で安全かつ効率的に CSS を圧縮したい場合に最適です。デフォルト設定では CSS の意味を変えない「安全な」最適化のみを行うため、多くのプロジェクトで安心して導入できます。Vite、Webpack、Rollup などのモダンなビルドツールと自然に統合できる点も大きな利点です。
postcss-clean は、既に PostCSS パイプラインを使用しており、clean-css の高度な最適化機能をそのまま使いたい場合に選択してください。内部で clean-css をラップしているため、clean-css の全機能を PostCSS 環境で利用できます。PostCSS ベースのワークフローに clean-css の設定を移行する際の橋渡しとしても有用です。
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');
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
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.
Gulp pluginGrunt pluginBroccoli pluginPostCSS pluginwebpack loaderwebpack pluginMinify 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:
String – resulting CSSObject – instance of SourceMapGenerator or nullOptions:
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.
const result = 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). Usecloneoption 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.
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') +
' */'
);
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.
idsandclassesare 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 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 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.