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

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

npmのダウンロードトレンド
3 年
GitHub Starsランキング
統計詳細
パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
uncss64,7669,423-586年前MIT
purify-css40,6149,893-819年前MIT
機能比較: uncss vs purify-css

動的スタイルの処理

  • uncss:

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

  • purify-css:

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

設定の柔軟性

  • uncss:

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

  • purify-css:

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

パフォーマンス

  • uncss:

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

  • purify-css:

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

学習曲線

  • uncss:

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

  • purify-css:

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

コミュニティとサポート

  • uncss:

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

  • purify-css:

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

選び方: uncss vs purify-css
  • uncss:

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

  • purify-css:

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

uncss のREADME

UnCSS

NPM version Linux Build Status Windows Build status Coverage Status dependencies Status devDependencies Status

UnCSS is a tool that removes unused CSS from your stylesheets. It works across multiple files and supports Javascript-injected CSS.

How

The process by which UnCSS removes the unused rules is as follows:

  1. The HTML files are loaded by jsdom and JavaScript is executed.
  2. All the stylesheets are parsed by PostCSS.
  3. document.querySelector filters out selectors that are not found in the HTML files.
  4. The remaining rules are converted back to CSS.

Please note:

  • UnCSS cannot be run on non-HTML pages, such as templates or PHP files. If you need to run UnCSS against your templates, you should probably generate example HTML pages from your templates, and run uncss on those generated files; or run a live local dev server, and point uncss at that.
  • UnCSS only runs the Javascript that is run on page load. It does not (and cannot) handle Javascript that runs on user interactions like button clicks. You must use the ignore option to preserve classes that are added by Javascript on user interaction.

Installation

npm install -g uncss

Usage

Online Server

Within Node.js

var uncss = require('uncss');

var files   = ['my', 'array', 'of', 'HTML', 'files', 'or', 'http://urls.com'],
    options = {
        banner       : false,
        csspath      : '../public/css/',
        htmlroot     : 'public',
        ignore       : ['#added_at_runtime', /test\-[0-9]+/],
        ignoreSheets : [/fonts.googleapis/],
        inject       : function(window) { window.document.querySelector('html').classList.add('no-csscalc', 'csscalc'); },
        jsdom        : {
            userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X)',
        },
        media        : ['(min-width: 700px) handheld and (orientation: landscape)'],
        raw          : 'h1 { color: green }',
        report       : false,
        strictSSL    : true,
        stylesheets  : ['lib/bootstrap/dist/css/bootstrap.css', 'src/public/css/main.css'],
        timeout      : 1000,
        uncssrc      : '.uncssrc',
        userAgent    : 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X)',
    };

uncss(files, options, function (error, output) {
    console.log(output);
});

/* Look Ma, no options! */
uncss(files, function (error, output) {
    console.log(output);
});

/* Specifying raw HTML */
var rawHtml = '...';

uncss(rawHtml, options, function (error, output) {
    console.log(output);
});

At build-time

UnCSS can also be used in conjunction with other JavaScript build systems, such as Grunt, Broccoli or Gulp!

From the command line

Usage: uncss [options] <file or URL, ...>
    e.g. uncss https://getbootstrap.com/docs/3.3/examples/jumbotron/ > stylesheet.css

Options:

  -h, --help                            output usage information
  -V, --version                         output the version number
  -i, --ignore <selector, ...>          Do not remove given selectors
  -m, --media <media_query, ...>        Process additional media queries
  -C, --csspath <path>                  Relative path where the CSS files are located
  -s, --stylesheets <file, ...>         Specify additional stylesheets to process
  -S, --ignoreSheets <selector, ...>    Do not include specified stylesheets
  -r, --raw <string>                    Pass in a raw string of CSS
  -t, --timeout <milliseconds>          Wait for JS evaluation
  -H, --htmlroot <folder>               Absolute paths' root location
  -u, --uncssrc <file>                  Load these options from <file>
  -n, --noBanner                        Disable banner
  -a, --userAgent <string>              Use a custom user agent string
  -I, --inject <file>                   Path to javascript file to be executed before uncss runs
  -o, --output <file>                   Path to write resulting CSS to

Note that you can pass both local file paths (which are processed by glob) and URLs to the program.

  • banner (boolean, default: true): Whether a banner should be prepended before each file block in the processed CSS.

  • csspath (string): Path where the CSS files are related to the HTML files. By default, UnCSS uses the path specified in the <link rel="stylesheet" href="path/to/file.css"/>.

  • htmlroot (string): Where the project root is. Useful for example if you have HTML that references local files with root-relative URLs, i.e. href="/css/style.css".

  • ignore (string[]): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors:

    /* uncss:ignore */
    .selector1 {
        /* this rule will be ignored */
    }
    
    .selector2 {
        /* this will NOT be ignored */
    }
    
    /* uncss:ignore start */
    
    /* all rules in here will be ignored */
    
    /* uncss:ignore end */
    
  • ignoreSheets (string[] | RegExp[]): Do not process these stylesheets, e.g. Google fonts. Accepts strings or regex patterns.

  • inject (string / function(window)): Path to a local javascript file which is executed before uncss runs. A function can also be passed directly in.

    Example inject.js file

    'use strict';
    
    module.exports = function(window) {
        window.document.querySelector('html').classList.add('no-csscalc', 'csscalc');
    };
    

    Example of passing inject as a function

    {
      inject: function(window){
        window.document.querySelector('html').classList.add('no-csscalc', 'csscalc');
      }
    }
    
  • jsdom (object) (Supported only by API): Supply the options used to create the JSDOM pages (https://github.com/jsdom/jsdom). At the moment, config.resources is not yet supported.

  • media (string[]): By default UnCSS processes only stylesheets with media query _all_, _screen_, and those without one. Specify here which others to include.

  • raw (string): Give the task a raw string of CSS in addition to the existing stylesheet options; useful in scripting when your CSS hasn't yet been written to disk.

  • report (boolean, default: true): Return the report object in callback.

  • strictSSL (boolean, default: true): Disable SSL verification when retrieving html source

  • stylesheets (string[]): Use these stylesheets instead of those extracted from the HTML files. Prepend paths with the file:// protocol to force use of local stylesheets, otherwise paths will be resolved as a browser would for an anchor tag href on the HTML page.

  • timeout (number): Specify how long to wait for the JS to be loaded.

  • uncssrc (string): Load all options from a JSON file. Regular expressions for the ignore and ignoreSheets options should be wrapped in quotation marks.

    Example uncssrc file:

    {
        "ignore": [
            ".unused",
            "/^#js/"
        ],
        "stylesheets": [
            "css/override.css"
        ]
    }
    
  • userAgent (String, default: 'uncss'): The user agent string that jsdom should send when requesting pages. May be useful when loading markup from services which use user agent based device detection to serve custom markup to mobile devices. Defaults to uncss.

As a PostCSS Plugin

UnCSS can be used as a PostCSS Plugin.

postcss([ require('uncss').postcssPlugin ]);

See PostCSS docs for examples for your environment.

Note: Depending on your environment, you might not be able to use uncss as a PostCSS plugin since the plugin is not directly exported. In such cases, use the wrapper library postcss-uncss.

Options

  • html (string[]): provide a list of html files to parse for selectors and elements. Usage of globs is allowed.

  • ignore (string[] | RegExp[]): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors in your CSS:

    /* uncss:ignore */
    .selector1 {
        /* this rule will be ignored */
    }
    
    .selector2 {
        /* this will NOT be ignored */
    }
    
Example Configuration
{
  html: ['index.html', 'about.html', 'team/*.html'],
  ignore: ['.fade']
}

License

Copyright (c) 2019 Giacomo Martino. See the LICENSE file for license rights and limitations (MIT).