Use PurgeCSS to Remove Unused CSS from a WordPress Theme

When developing a WordPress theme, it is common to rely on CSS frameworks to speed things up. By the time the theme is finished, though, a large portion of that framework CSS is often unused.

Removing unused CSS is one of the most important steps in front-end performance optimization. It is also extremely hard to do manually. PurgeCSS solves that problem, and this article shows how to use it in a Gulp-based workflow.

Use PurgeCSS to remove unused CSS

If Node.js is already installed and the project has been initialized with npm init, install the Gulp plugin first:

npm i -D gulp-purgecss

Then create a gulpfile.js and add the task below:

const gulp = require('gulp');
const purgecss = require('gulp-purgecss');

gulp.task('purgecss', () => {
  return gulp
    .src('src/**/*.css')
    .pipe(
      purgecss({
        content: ['src/**/*.html']
      })
    )
    .pipe(gulp.dest('build/'));
});

Next, create a src directory beside gulpfile.js and place the front-end files there. Then run:

gulp purgecss

After the command finishes, the build directory will contain the CSS files after PurgeCSS has removed selectors that were never used in the scanned content.

On a real site, the reduction can be dramatic. In the example from the original article, the CSS file dropped from 220 KB to 75 KB.

Whitelist CSS classes generated by JavaScript

Some classes are generated dynamically by JavaScript, which means they do not appear in the static HTML files scanned by PurgeCSS. If you do nothing, PurgeCSS may remove them by mistake. Use a whitelist for those classes:

const purgecss = new Purgecss({
  content: [],
  whitelist: ['random', 'yep', 'button'],
  whitelistPatterns: [/red$/],
});

Use it with Tailwind CSS

By default, PurgeCSS may not parse some of Tailwind CSS’s special class formats correctly. You can fix that by adding a custom extractor, especially to support class names that contain :.

extractors: [
  {
    extractor: content => content.match(/[A-z0-9-:/]+/g) || [],
    extensions: ['css', 'html'],
  },
],

Because PurgeCSS works on static content, it cannot directly understand a dynamic PHP application. In a WordPress project, that usually means you need to generate static HTML first, then feed those files into PurgeCSS. Tools like HTTrack or SiteSucker can help with that export step.

If you already use Gulp, Webpack, or PostCSS to build your WordPress styles, PurgeCSS can usually be integrated directly into that workflow so unused CSS is removed automatically during theme builds.

Related Posts

Leave a Reply

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