PurgeCSS: Remove unused CSS code (2024)

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

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

Now, go ahead and install PurgeCSS and its dependencies:

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

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;

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

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"

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-allconst PurgecssPlugin = require('purgecss-webpack-plugin')const glob = require('glob-all')

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

 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:

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:

/*! 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.

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.

PurgeCSS: Remove unused CSS code (1)

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.

PurgeCSS: Remove unused CSS code (2024)
Top Articles
Amazon: i compratori tentano un recupero verso i $100, come operare? | Investire.biz
10 Easy tips to Eat Healthy when you're on a Tight Budget
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated:

Views: 6640

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.