DEV Community

Cover image for PurgeCSS: Remove unused CSS code
Matt Angelosanto for LogRocket

Posted on • Originally published at blog.logrocket.com

PurgeCSS: Remove unused CSS code

Written by Hamsa Harcourt ✏️

CSS frameworks are collections of style sheets that are preprepared in advance and come ready to use. Developers opt for CSS frameworks to deliver digital experiences in a more intuitive, efficient, and standards-compliant manner.

However, CSS frameworks can also pose a problem. It's unlikely that you'll use every feature offered in a CSS framework, meaning unused code will be leftover in your final application. Unused code can result in a larger file size, harm performance, make it easy to lose track of each item, and cause optimization problems.

Removing unnecessary code will make your website load faster because the browser will request and parse less code. In this tutorial, we’ll explore PurgeCSS, a tool for removing unused CSS code. With PurgeCSS as a part of our development workflow, we can easily remove unused CSS, resulting in smaller CSS files and improving our application overall. Let's get started!

Why should you use PurgeCSS?

While PurgeCSS is not the only tool for removing unused CSS, it stands out thanks to its modularity, ease of use, and wide range of customization options.

Modularity

Modularity enables developers to create module extractors for specific use cases and frameworks. An extractor is a function that reads the contents of a file and extracts a list of CSS selectors that are used.

PurgeCSS provides a very reliable default extractor that can work with a wide range of files types. However, by default, PurgeCSS ignores unused CSS code containing special characters like @​,:, and /. Therefore, PurgeCSS may not fit the exact file type or CSS framework that you're using.

Wide range of customization options

PurgeCSS has a wide range of options that allow you to customize its behavior according to your needs. For example, PurgeCSS includes options for fontFace, keyframes, extractors, css, and more. Customization can improve the performance and efficiency of PurgeCSS.

Easy to use

PurgeCSS is very easy to get started with and includes thorough documentation. At the time of writing, PurgeCSS is loved by developers with 1.9m weekly downloads on npm and 6.5k GitHub stars.

Getting Started

First, open up your terminal and run the following command to install React using create-react-app:

npx create-react-app purgecss-tutorial
Enter fullscreen mode Exit fullscreen mode

Next, move into the purgecss-tutorial directory we just created:

cd purgecss-tutorial
Enter fullscreen mode Exit fullscreen mode

Now, go ahead and install PurgeCSS and its dependencies:

npm i --save-dev @fullhuman/postcss-purgecss glob-all purgecss-webpack-plugin
Enter fullscreen mode Exit fullscreen mode

Open your App.js file and paste the following code:

import React from 'react';
import "./App.css";

function App() {
  return <div className="App"></div>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In the code above, we created a functional component called App and returned a div with a classname of App.

Our App.css is left untouched, so it contains the following unused CSS code:

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
Enter fullscreen mode Exit fullscreen mode

Open up your package.json file and add the following line under scripts:

"postbuild": "purgecss --css build/static/css/*.css --content build/index.html build/static/js/*.js --output build/static/css"
Enter fullscreen mode Exit fullscreen mode

post is a prefix that can be added to any npm script and will automatically run when you run the main script. In our case, postbuild runs after the build script is executed.

The command executed by postbuild contains three options. The --css option specifies what CSS files PurgeCSS should process. It can be an array of filenames or globs. The --content option is similar to the --css option, specifying what content should be analyzed by PurgeCSS. The --output option specifies what directory you should write the purified CSS files to. By default, it places the result in the console.

In essence, the command executed by postbuild does the following:

  1. Checks every CSS file in your build/static/css
  2. Matches the selectors used in your files and removes any unused CSS
  3. Outputs the new CSS file in build/static/css

Finally, eject Create React App to expose the webpack configuration offered by the original Create React App. After ejecting, we're going to modify the config/webpack.prod.conf.js file by adding the following code along with the rest of the imports:

// import PurgeCSS webpack plugin and glob-all
const PurgecssPlugin = require('purgecss-webpack-plugin')
const glob = require('glob-all')
Enter fullscreen mode Exit fullscreen mode

Immediately before new ManifestPlugin(...) in the plugins list, add the code below:

    new PurgecssPlugin({
      paths: [paths.appHtml, ...glob.sync(`${paths.appSrc}/**/*`, { nodir: true })]
    }),
Enter fullscreen mode Exit fullscreen mode

The webpack plugin specifies the content that should be analyzed by PurgeCSS with an array of paths.

To confirm if you were successful, open the CSS file in build/static/css. The output looks like the code below, containing only the used CSS:

body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Roboto","Oxygen","Ubuntu","Cantarell","Fira Sans","Droid Sans","Helvetica Neue",sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.App{text-align:center}@keyframes App-logo-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}
Enter fullscreen mode Exit fullscreen mode

Caveats of PurgeCSS

PurgeCSS, along with some other CSS optimization tools like PostCSS and cssnano, strips comments from your CSS files. You can indicate which selectors are safe to leave in the final CSS.

There are two ways we can accomplish this, the PurgeCSS option safelist or the special CSS special comment.

In our case, we’re going to add a special CSS comment directly in our CSS file. PurgeCSS uses /* purgecss start ignore */ and /* purgecss end ignore */ to safelist a range of rules. To prevent our comments from being removed, we add an exclamation mark to tell PurgeCSS that it is important. See the example below:

/*! purgecss start ignore */
h1 {
  color: pink;
  font-size: 2rem;
}
/*! purgecss end ignore */
Enter fullscreen mode Exit fullscreen mode

Prior to PurgeCSS v2.0, unused font faces and keyframes code were removed by default. However, when these features were used incorrectly, the code would break. Unused font faces and keyframes code are now left untouched by default. You can change this default behavior by setting the keyframes and font-faces options to true.

Conclusion

In this article, we explored PurgeCSS, a tool to remove unused CSS from your code, thereby reducing file size and improving optimization. We covered the major offerings of PurgeCSS, including its modularity, customization options, and ease of use. Then, we reviewed the steps required to get started with PurgeCSS and the few caveats to consider.

Even if you decide to use a CSS framework like TailwindCSS, Bootstrap, MaterializeCSS, or Foundation, PurgeCSS should work perfectly. I hope you enjoyed this article! 


Is your frontend hogging your users' CPU?

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.

LogRocket Dashboard Free Trial Banner

LogRocket is like a DVR for web apps, recording everything that happens in your web app or site. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web apps — Start monitoring for free.

Top comments (0)