PurgeCSS: Remove unused CSS code
Tags: css, webdev, tutorial
Published: 2022-01-07 18:44:02

**Written by [Hamsa Harcourt](https://blog.logrocket.com/author/harcourthamsa/)** ✏️

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](https://blog.logrocket.com/top-utility-first-css-frameworks/). 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](https://purgecss.com/), 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](https://purgecss.com/configuration.html#options) 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](https://www.npmjs.com/package/purgecss) and [6.5k GitHub stars.](https://github.com/FullHuman/purgecss)

## Getting Started

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

```shell
npx create-react-app purgecss-tutorial
```

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

```react
cd purgecss-tutorial
```

Now, go ahead and install PurgeCSS and its dependencies:

```shell
npm i --save-dev @fullhuman/postcss-purgecss glob-all purgecss-webpack-plugin
```

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

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

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

export default App;
```

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:

```css
.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);
  }
}
```

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

```css
"postbuild": "purgecss --css build/static/css/*.css --content build/index.html build/static/js/*.js --output build/static/css"
```

`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](https://github.com/isaacs/node-glob/blob/master/README.md#glob-primer). 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:

```js
// import PurgeCSS webpack plugin and glob-all
const PurgecssPlugin = require('purgecss-webpack-plugin')
const glob = require('glob-all')
```

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

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

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:

```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)}}
```

## 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:

```css
/*! purgecss start ignore */
h1 {
  color: pink;
  font-size: 2rem;
}
/*! purgecss end ignore */
```

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.

<span style="font-family: -apple-system, BlinkMacSystemFont, 'segoe ui', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'helvetica neue', sans-serif;">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! </span>

---

## 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](https://logrocket.com/signup/).

[![LogRocket Dashboard Free Trial Banner](https://blog.logrocket.com/wp-content/uploads/2019/12/cpu-memory-usage.png)](https://logrocket.com/signup/)

[LogRocket](https://logrocket.com/signup/) 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](https://logrocket.com/signup/).