CSS Purification Tools Comparison
purify-css vs uncss
1 Year
purify-cssuncssSimilar Packages:
What's CSS Purification Tools?

CSS purification tools are essential in web development for optimizing stylesheets by removing unused CSS rules. This not only reduces the file size of CSS files, leading to faster load times, but also enhances maintainability by keeping the stylesheets clean and relevant to the actual content of the web pages. These tools analyze the HTML content and JavaScript files to determine which CSS selectors are actually used, allowing developers to streamline their stylesheets effectively. By utilizing such tools, developers can improve performance and ensure that their web applications are efficient and responsive.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
purify-css110,3359,922-858 years agoMIT
uncss53,8289,421-565 years agoMIT
Feature Comparison: purify-css vs uncss

Integration

  • purify-css:

    PurifyCSS is designed to be easily integrated into various build tools like Gulp, Grunt, and Webpack. It allows developers to customize the process according to their workflow, making it a flexible choice for different project setups.

  • uncss:

    UnCSS can also be integrated into build tools, but it may require more configuration compared to PurifyCSS. It is particularly effective in environments where HTML is dynamically generated, such as single-page applications.

Performance

  • purify-css:

    PurifyCSS is known for its performance efficiency, as it focuses on removing only the unused CSS selectors without altering the remaining styles. This results in a smaller CSS file size and improved loading times without compromising the visual integrity of the application.

  • uncss:

    UnCSS can sometimes be slower, especially on larger projects, as it analyzes the entire HTML structure to identify unused styles. While it is thorough, this thoroughness can lead to longer processing times compared to PurifyCSS.

Configuration Flexibility

  • purify-css:

    PurifyCSS offers a simple configuration setup, allowing developers to specify the paths to their HTML and CSS files easily. This simplicity makes it accessible for developers who may not want to dive deep into complex configurations.

  • uncss:

    UnCSS provides more advanced configuration options, allowing for greater customization in how unused styles are detected and removed. This can be beneficial for experienced developers looking for fine-tuned control over the purification process.

Dynamic Content Handling

  • purify-css:

    PurifyCSS is primarily focused on static content and may not effectively handle styles that are applied dynamically through JavaScript. Developers need to ensure that all relevant HTML is included during the purification process.

  • uncss:

    UnCSS excels in handling dynamic content, as it can analyze the rendered output of JavaScript frameworks. This makes it a better choice for applications where styles are applied conditionally or through client-side scripts.

Community and Support

  • purify-css:

    PurifyCSS has a smaller community compared to UnCSS, which may result in fewer resources and examples available for troubleshooting. However, its straightforward nature often leads to fewer issues overall.

  • uncss:

    UnCSS has a larger community and more extensive documentation, providing a wealth of resources for developers. This can be advantageous for those seeking help or examples on how to effectively use the tool.

How to Choose: purify-css vs uncss
  • purify-css:

    Choose PurifyCSS if you need a lightweight solution that can be easily integrated into your build process. It is particularly useful for projects where you want to maintain control over the CSS output and prefer a straightforward configuration without additional dependencies.

  • uncss:

    Choose UnCSS if you are looking for a more comprehensive solution that can analyze your HTML files and dynamically generated content. UnCSS is ideal for larger projects where you want to ensure that all unused CSS is removed, including styles that may not be present in static HTML but are generated by JavaScript.

README for purify-css

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.