uncss: Find Unused CSS

You know what's better than adding features to a website or app, from a code perspective?  Removing stuff you don't need.  Whether it be code, images, or dependencies, getting rid of the crap stale code is like the first sip of a big glass of wine after a long day of stressful work.  Running a directory of images through ImageOptim is a euphoric experience, am I right?  What if there was a tool, however, which would allow you to find unused CSS for a given website?  There is, and it's called uncss, a NodeJS powered utility.  Let's take a look at how uncss works!

A basic usage of uncss's command line tool would be:

uncss http://davidwalsh.name > styles.css

The output of this execution is a stylesheet featuring only the used CSS rules -- unused rules are removed.  So how does uncss work?  I'll let them tell you how:

  1. The HTML files are loaded by PhantomJS and JavaScript is executed.
  2. Used stylesheets are extracted from the resulting HTML.
  3. The stylesheets are concatenated and the rules are parsed by css-parse.
  4. document.querySelector filters out selectors that are not found in the HTML files.
  5. The remaining rules are converted back to CSS.

Like just about every NodeJS-based utility, you can also take advantage of its JavaScript API.  Here's an example usage:

var uncss = require('uncss');

var files   = ['my', 'array', 'of', 'HTML', 'files'],
    options = {
        ignore       : ['#added_at_runtime', /test\-[0-9]+/],
        media        : ['(min-width: 700px) handheld and (orientation: landscape)'],
        csspath      : '../public/css/',
        raw          : 'h1 { color: green }',
        stylesheets  : ['lib/bootstrap/dist/css/bootstrap.css', 'src/public/css/main.css'],
        ignoreSheets : [/fonts.googleapis/],
        urls         : ['http://localhost:3000/mypage', '...'], // Deprecated
        timeout      : 1000,
        htmlroot     : 'public'

uncss(files, options, function (error, output) {

/* Look Ma, no options! */
uncss(files, function (error, output) {

/* Specifying raw HTML */
var raw_html = '...';
uncss(raw_html, options, function (error, output) {

There's no arguing that years of maintaining, adding, and removing from a site will add excess code to the codebase.  That excess code comes at the cost of users who have load the extra code, so eliminating the dead code is important.  Give uncss a try -- it's an easy to use, automated helper to keep your codebase as tight as possible!