Remove unused CSS out of an html template

How many times do you have to clean out HTML / CSS templates chosen for a given site you have to build?

If the answer to this question is yes, you are at the right place!

I have been facing this multiple times, especially with that so nice template that you need for only one page, which contains single-theme CSS files worth 600Kb or worse…

The solution I have been using has been working for me multiple times, and really helped reducing size of required files to be used.

First, create a node project, in which you can pre-create a package.json file (only to save development dependencies).

Then install the following packages :

npm install grunt --save-dev
npm install grunt-uncss --save-dev

grunt-unccs is a node package that will do for you the CSS cleaning, taking care of cleaning unused CSS classes for one or multiple html pages.

Now, create your gruntfile.js file, with the following content:

'use strict';

module.exports = function (grunt) {
  // Project Configuration

  grunt.loadNpmTasks('grunt-uncss');
  // Project Configuration
  grunt.initConfig({
  	uncss: {
	  dist: {
	    files: {
	      'dist/tidy.css': ['src/pages/index.html', 'src/pages/about.html']
	    }
	  }
	}
  });
};

Make sure your pages are accessible as per given entry under the files json object.

This will then let you run the following command:

C:\Projects\NodeTidyTest>grunt uncss
Running "uncss:dist" (uncss) task
File dist/tidy.css created: 888.72 kB → 32.98 kB

You are done!

Warnings:

  • This does not solve in-CSS file links such as images or font loading (e.g. Font-Awesome if loaded locally),
  • Complex CSS selectors are not managed by this plugin (could make it crash); once identified move them into a separated CSS file, not parsed by the lib to avoid issues.

Leave a Reply

Your email address will not be published. Required fields are marked *