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
Official exchange rate
What Is a Bitcoin ETF?
Duralast Gold Cv Axle
Pixel Speedrun Unblocked 76
Sound Of Freedom Showtimes Near Governor's Crossing Stadium 14
Koordinaten w43/b14 mit Umrechner in alle Koordinatensysteme
Watch Mashle 2nd Season Anime Free on Gogoanime
30% OFF Jellycat Promo Code - September 2024 (*NEW*)
10000 Divided By 5
Cars For Sale Tampa Fl Craigslist
OnTrigger Enter, Exit ...
David Turner Evangelist Net Worth
No Strings Attached 123Movies
Summoner Class Calamity Guide
Nwi Arrests Lake County
Peraton Sso
Most McDonald's by Country 2024
Youravon Comcom
Dutch Bros San Angelo Tx
Idaho Harvest Statistics
Log in or sign up to view
Driving Directions To Bed Bath & Beyond
Traveling Merchants Tack Diablo 4
Mccain Agportal
2024 INFINITI Q50 Specs, Trims, Dimensions & Prices
What Channel Is Court Tv On Verizon Fios
Titanic Soap2Day
Jail View Sumter
Encyclopaedia Metallum - WikiMili, The Best Wikipedia Reader
Does Hunter Schafer Have A Dick
Rogue Lineage Uber Titles
Mercedes W204 Belt Diagram
Dentist That Accept Horizon Nj Health
The value of R in SI units is _____?
Gr86 Forums
Forager How-to Get Archaeology Items - Dino Egg, Anchor, Fossil, Frozen Relic, Frozen Squid, Kapala, Lava Eel, and More!
The 50 Best Albums of 2023
Merge Dragons Totem Grid
Mohave County Jobs Craigslist
Anguilla Forum Tripadvisor
20 bank M&A deals with the largest target asset volume in 2023
Ferguson Showroom West Chester Pa
Coroner Photos Timothy Treadwell
Wilson Tire And Auto Service Gambrills Photos
Workday Latech Edu
Colin Donnell Lpsg
Automatic Vehicle Accident Detection and Messageing System – IJERT
Research Tome Neltharus
Sml Wikia
Kidcheck Login
Dcuo Wiki
Texas Lottery Daily 4 Winning Numbers
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.