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
4 areas to avoid in Paris: Red flags in the city of love
Kraken Review: Pros, Cons, and Features in 2024
Poe T4 Aisling
Somboun Asian Market
Rek Funerals
Bucks County Job Requisitions
Free VIN Decoder Online | Decode any VIN
The Idol - watch tv show streaming online
Fototour verlassener Fliegerhorst Schönwald [Lost Place Brandenburg]
Kent And Pelczar Obituaries
Campaign Homecoming Queen Posters
Local Collector Buying Old Motorcycles Z1 KZ900 KZ 900 KZ1000 Kawasaki - wanted - by dealer - sale - craigslist
Lake Nockamixon Fishing Report
Dignity Nfuse
Cyndaquil Gen 4 Learnset
Soccer Zone Discount Code
Spergo Net Worth 2022
Swgoh Turn Meter Reduction Teams
Saatva Memory Foam Hybrid mattress review 2024
Nordstrom Rack Glendale Photos
Halo Worth Animal Jam
Breckie Hill Mega Link
Marion City Wide Garage Sale 2023
Lost Pizza Nutrition
Lexus Credit Card Login
Craig Woolard Net Worth
Is Light Raid Hard
Cowboy Pozisyon
Sensual Massage Grand Rapids
Delta Math Login With Google
Wells Fargo Bank Florida Locations
Pixel Combat Unblocked
Warren County Skyward
Solarmovie Ma
Gideon Nicole Riddley Read Online Free
Craigslist Neworleans
Colorado Parks And Wildlife Reissue List
Pillowtalk Podcast Interview Turns Into 3Some
The Vélodrome d'Hiver (Vél d'Hiv) Roundup
Emerge Ortho Kronos
Body Surface Area (BSA) Calculator
Craigslist Freeport Illinois
Lake Andes Buy Sell Trade
Lyndie Irons And Pat Tenore
13 Fun &amp; Best Things to Do in Hurricane, Utah
Kenner And Stevens Funeral Home
How to Connect Jabra Earbuds to an iPhone | Decortweaks
Dicks Mear Me
Theater X Orange Heights Florida
Naughty Natt Farting
Ff14 Palebloom Kudzu Cloth
Famous Dave's BBQ Catering, BBQ Catering Packages, Handcrafted Catering, Famous Dave's | Famous Dave's BBQ Restaurant
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.