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 https://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:

The HTML files are loaded by PhantomJS and JavaScript is executed. Used stylesheets are extracted from the resulting HTML. The stylesheets are concatenated and the rules are parsed by css-parse. document.querySelector filters out selectors that are not found in the HTML files. 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) { console.log(output); }); /* Look Ma, no options! */ uncss(files, function (error, output) { console.log(output); }); /* Specifying raw HTML */ var raw_html = '...'; uncss(raw_html, options, function (error, output) { console.log(output); });