purify-css vs uncss
CSS最適化ライブラリ
purify-cssuncss類似パッケージ:

CSS最適化ライブラリ

CSS最適化ライブラリは、ウェブサイトやアプリケーションのスタイルシートを最適化し、不要なCSSを削除することで、ページの読み込み速度を向上させ、パフォーマンスを改善するためのツールです。これにより、最小限のCSSファイルを生成し、クライアント側のリソース消費を削減します。

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

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
purify-css09,886-819年前MIT
uncss09,419-586年前MIT

機能比較: purify-css vs uncss

動的スタイルの処理

  • purify-css:

    Purify CSSは、JavaScriptによって動的に生成されるスタイルを考慮に入れることができるため、アプリケーションの動的な部分でも適切に最適化が行えます。特に、クラス名が動的に変更される場合に有効です。

  • uncss:

    UnCSSは、静的なHTMLに基づいてCSSを最適化するため、JavaScriptによって変更されるスタイルには対応していません。動的なスタイルが多いアプリケーションには不向きです。

設定の柔軟性

  • purify-css:

    Purify CSSは、設定が非常に柔軟で、特定のファイルやディレクトリを指定して最適化を行うことができます。また、特定のセレクタを保持するためのオプションも提供されており、開発者のニーズに応じて調整可能です。

  • uncss:

    UnCSSは、シンプルな設定で使用できるため、初心者にも扱いやすいですが、柔軟性はPurify CSSに比べて劣ります。特定の条件下でのスタイルの保持には工夫が必要です。

パフォーマンス

  • purify-css:

    Purify CSSは、使用されていないCSSを削除することで、CSSファイルのサイズを大幅に削減し、ページの読み込み速度を向上させます。特に大規模なプロジェクトでは、効果が顕著に現れます。

  • uncss:

    UnCSSも同様に、不要なCSSを削除することでパフォーマンスを向上させますが、動的スタイルの処理ができないため、特定のケースでは効果が限定されることがあります。

学習曲線

  • purify-css:

    Purify CSSは、設定や使用方法が比較的簡単で、ドキュメントも充実しているため、学習曲線は緩やかです。特に、CSSやJavaScriptに慣れている開発者には扱いやすいです。

  • uncss:

    UnCSSは、非常にシンプルなツールで、すぐに使い始めることができます。基本的な使い方を理解するのが容易で、初心者にも適しています。

コミュニティとサポート

  • purify-css:

    Purify CSSは、活発なコミュニティがあり、問題解決のためのリソースやサポートが豊富です。GitHub上での活動も活発で、定期的にアップデートが行われています。

  • uncss:

    UnCSSも一定のコミュニティが存在しますが、Purify CSSに比べるとサポートやリソースはやや少ないです。ただし、基本的な機能に関しては十分な情報が提供されています。

選び方: purify-css vs uncss

  • purify-css:

    Purify CSSは、特定のHTMLファイルやJavaScriptファイルを基に、使用されていないCSSを検出して削除します。動的に生成されるCSSや、特定の条件下でのみ使用されるスタイルがある場合に特に効果的です。

  • uncss:

    UnCSSは、HTMLファイルを解析して、使用されていないCSSを削除しますが、JavaScriptによって動的に生成されるスタイルには対応していません。静的なウェブサイトや、JavaScriptの影響を受けないスタイルの最適化に適しています。

purify-css のREADME

PurifyCSS

Travis npm David Join the chat at https://gitter.im/purifycss/purifycss

A function that takes content (HTML/JS/PHP/etc) and CSS, and returns only the used CSS.
PurifyCSS does not modify the original CSS files. You can write to a new file, like minification.
If your application is using a CSS framework, this is especially useful as many selectors are often unused.

Potential reduction

  • Bootstrap file: ~140k
  • App using ~40% of selectors.
  • Minified: ~117k
  • Purified + Minified: ~35k

Usage

Standalone

Installation

npm i -D purify-css
import purifycss from "purify-css"
const purifycss = require("purify-css")

let content = ""
let css = ""
let options = {
    output: "filepath/output.css"
}
purify(content, css, options)

Build Time

CLI Usage

$ npm install -g purify-css
$ purifycss -h

purifycss <css> <content> [option]

Options:
  -m, --min        Minify CSS                         [boolean] [default: false]
  -o, --out        Filepath to write purified css to                    [string]
  -i, --info       Logs info on how much css was removed
                                                      [boolean] [default: false]
  -r, --rejected   Logs the CSS rules that were removed
                                                      [boolean] [default: false]
  -w, --whitelist  List of classes that should not be removed
                                                           [array] [default: []]
  -h, --help       Show help                                           [boolean]
  -v, --version    Show version number                                 [boolean]

How it works

Used selector detection

Statically analyzes your code to pick up which selectors are used.
But will it catch all of the cases?

Let's start off simple.

Detecting the use of: button-active

  <!-- html -->
  <!-- class directly on element -->
  <div class="button-active">click</div>
  // javascript
  // Anytime your class name is together in your files, it will find it.
  $(button).addClass('button-active');

Now let's get crazy.

Detecting the use of: button-active

  // Can detect if class is split.
  var half = 'button-';
  $(button).addClass(half + 'active');

  // Can detect if class is joined.
  var dynamicClass = ['button', 'active'].join('-');
  $(button).addClass(dynamicClass);

  // Can detect various more ways, including all Javascript frameworks.
  // A React example.
  var classes = classNames({
    'button-active': this.state.buttonActive
  });

  return (
    <button className={classes}>Submit</button>;
  );

Examples

Example with source strings
var content = '<button class="button-active"> Login </button>';
var css = '.button-active { color: green; }   .unused-class { display: block; }';

console.log(purify(content, css));

logs out:

.button-active { color: green; }
Example with glob file patterns + writing to a file
var content = ['**/src/js/*.js', '**/src/html/*.html'];
var css = ['**/src/css/*.css'];

var options = {
  // Will write purified CSS to this file.
  output: './dist/purified.css'
};

purify(content, css, options);
Example with both glob file patterns and source strings + minify + logging rejected selectors
var content = ['**/src/js/*.js', '**/src/html/*.html'];
var css = '.button-active { color: green; } .unused-class { display: block; }';

var options = {
  output: './dist/purified.css',

  // Will minify CSS code in addition to purify.
  minify: true,

  // Logs out removed selectors.
  rejected: true
};

purify(content, css, options);

logs out:

.unused-class
Example with callback
var content = ['**/src/js/*.js', '**/src/html/*.html'];
var css = ['**/src/css/*.css'];

purify(content, css, function (purifiedResult) {
  console.log(purifiedResult);
});
Example with callback + options
var content = ['**/src/js/*.js', '**/src/html/*.html'];
var css = ['**/src/css/*.css'];

var options = {
  minify: true
};

purify(content, css, options, function (purifiedAndMinifiedResult) {
  console.log(purifiedAndMinifiedResult);
});

API in depth

// Four possible arguments.
purify(content, css, options, callback);
The content argument
Type: Array or String

Array of glob file patterns to the files to search through for used classes (HTML, JS, PHP, ERB, Templates, anything that uses CSS selectors).

String of content to look at for used classes.


The css argument
Type: Array or String

Array of glob file patterns to the CSS files you want to filter.

String of CSS to purify.


The (optional) options argument
Type: Object
Properties of options object:
  • minify: Set to true to minify. Default: false.

  • output: Filepath to write purified CSS to. Returns raw string if false. Default: false.

  • info: Logs info on how much CSS was removed if true. Default: false.

  • rejected: Logs the CSS rules that were removed if true. Default: false.

  • whitelist Array of selectors to always leave in. Ex. ['button-active', '*modal*'] this will leave any selector that includes modal in it and selectors that match button-active. (wrapping the string with *'s, leaves all selectors that include it)

The (optional) callback argument
Type: Function

A function that will receive the purified CSS as it's argument.

Example of callback use
purify(content, css, options, function(purifiedCSS){
  console.log(purifiedCSS, ' is the result of purify');
});
Example of callback without options
purify(content, css, function(purifiedCSS){
  console.log('callback without options and received', purifiedCSS);
});
Example CLI Usage
$ purifycss src/css/main.css src/css/bootstrap.css src/js/main.js --min --info --out src/dist/index.css

This will concat both main.css and bootstrap.css and purify it by looking at what CSS selectors were used inside of main.js. It will then write the result to dist/index.css

The --min flag minifies the result.

The --info flag will print this to stdout:

    ________________________________________________
    |
    |   PurifyCSS has reduced the file size by ~ 33.8%
    |
    ________________________________________________

The CLI currently does not support file patterns.