Removing Unused CSS With PurgeCSS (2024)

Building an efficient site is critical for both user experience and SEO. Unused CSS is one of the most common problems that can negatively impact website performance. This increases the size of the bundle sent to the client. This article will introduce you to PurgeCSS, a tool that can minimize the CSS sent to the browser.

Sending more CSS than needed not only causes delays and bad experience but also negatively affects theCore Web Vitals, which Google uses to evaluate the SEO performance of your site.

At build time, Next.js simply bundles all CSS rules into some optimized files through PostCSS. In other words, it does not automatically remove unused CSS rules. Here is where PurgeCSS comes into play!

Let’s learn what PurgeCSS is, how it works, and how to configure it in a Next.js app to make it automatically remove unused CSS rules.

Why Is Unused CSS a Problem?

Unused CSS occurs when style files sent to the client contain rules that are never used on any page of the site. In a Next.js application, that can cause several issues:

  1. Increased Bundle Size:Including unused CSS in the frontend application bundle shipped to the client unnecessarily inflates its size. This results in longer loading times and higher bandwidth consumption, affecting initial rendering and page navigation.
  2. Developer Confusion:When a codebase contains a lot of extra CSS rules, it becomes more difficult to identify and maintain the styles actually in use. This can confuse developers, leading to errors and inconsistencies.
  3. Impact on Core Web Vitals:Google Lighthouse, a tool for measuring a site’s Core Web Vitals,flags unused CSS as a problem. A low score in those metrics means that Google negatively evaluates the user experience offered by your site, which will result in poor SEO rankings.

It’s time to learn how to address this problem!

What Is PurgeCSS?

PurgeCSSis a tool for removing unused CSS from a web application. It is based on a simple idea. Most sites rely on CSS frameworks like TailwindCSS, Bootstrap, or MaterializeCSS. However, you typically only use a small subset of such frameworks. This means that your application sends much more CSS to the client than required.

PurgeCSS matches the CSS selectors used in your HTML elements with those in stylesheets. Then, it automatically removes all unused rules, producing smaller CSS files. Since the default behavior may produce undesired results, it is highly customizable and supports many options.

The tool is available for several technologies and frameworks, including Vue, React, Next.js, Nuxt.js, Hugo, and WordPress. Let’s now look at how to set it up in Next.js!

The following sections will show you how to configure PurgeCSS in Next.js.

Initializing a Next.js App

First, you need a Next.js application. You can initialize one with theNext Create Appcommand below:

npx create-next-app@latest 

Follow the procedure and answers all the questions. The default options will do.

√ What is your project named? ... purge-css-next-js-demo√ Would you like to use TypeScript with this project? ... No / Yes√ Would you like to use ESLint with this project? ... No / Yes√ Would you like to use Tailwind CSS with this project? ... No / Yes√ Would you like to use `src/` directory with this project? ... No / Yes√ Use App Router (recommended)? ... No / Yes√ Would you like to customize the default import alias? ... No / Yes 

Next, install Bootstrap. In the project folder, run:

npm install bootstrap 

Import it by adding the following line on top of thesrc/app/layout.jsfile:

import 'bootstrap/dist/css/bootstrap.css' 

If you are not using theNext.js App Routerfeature, add it to thepages/_app.jsfile.

Also, remove theglobals.cssimport. You will not need it anymore.

Update your home page component to use a Bootstrap sample layout, as below:

// src/app/page.js// or if you do not use App Router:// pages/index.jsexport default function HomePage() { return ( <div className="container"> <div className="row"> <div className="col-md-6"> <h1>Welcome to My Website</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed euismod vestibulum eros, eu sagittis arcu ullamcorper ut. </p> <button className="btn btn-primary">Learn More</button> </div> <div className="col-md-6"> <div className="card"> <div className="card-body"> <h5 className="card-title">Featured Content</h5> <p className="card-text"> Some text describing the featured content. </p> </div> </div> </div> </div> </div> );} 

Verify that everything works as expected by launching the local development server with:

npm run dev 

Visithttp://localhost:3000in the browser, and you should be seeing:

Removing Unused CSS With PurgeCSS (1)

Great! Your Next.js app using Bootstrap as a CSS framework is ready!

Session Replay for Developers

Uncover frustrations, understand bugs and fix slowdowns like never before withOpenReplay— an open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.

Check our GitHub repoand join the thousands of developers in our community.

Install PurgeCSS

Next.js relies onPostCSSto produce the bundle stylesheet files. For this reason, the easiest way to configure PurgeCSS is with itsPostCSS plugin. Add it to your project’s dependencies with:

npm install --save-dev @fullhuman/postcss-purgecss 

Remember that when you set up a custom PostCSS configuration file, Next.js completelydisables the default behavior. You need to download and configure a couple of plugins to restore that. Install them with the command below:

Recommended by LinkedIn

Preload Protocol Explained: A Key Tool for Better SEO… Dr. Tuhin Banik 2 weeks ago
Was DOM Invented with HTML? Amr Saafan 2 months ago
HTML Hacks: 10 Tips to Build Better Websites Esraa Shaheen 5 months ago
npm install postcss-flexbugs-fixes postcss-preset-env 

Fantastic! You now have everything required to set up PurgeCSS in PostCSS.

Configure PurgeCSS to Remove Unused CSS

To configure PurgeCSS, create apostcss.config.jsfile in the root folder of your project as follows:

// postcss.config.jsmodule.exports = { plugins: [ // restore the Next.js default behavior "postcss-flexbugs-fixes", [ "postcss-preset-env", { autoprefixer: { flexbox: "no-2009", }, stage: 3, features: { "custom-properties": false, }, }, ], [ // configure PurgeCSS "@fullhuman/postcss-purgecss", { content: ["./src/app/**/*.{js,jsx,ts,tsx}"], defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [], safelist: { standard: ["html", "body"], }, }, ], ],}; 

Let’s understand what this configuration file defines by breaking it down into small parts.

First, thepostcss-flexbugs-fixesplugin helps to fix various bugs and issues related to Flexbox, ensuring consistent behavior between different browsers.

Then, thepostcss-preset-envplugin converts modern CSS into a format compatible with most browsers. It includesautoprefixer, automatically adding vendor prefixes to CSS properties to support different browser versions. Here, theflexbox: "no-2009"option excludes support for the outdated syntax of the flexbox specification.

Finally,@fullhuman/postcss-purgecssremoves unused CSS from your Next.js app. It involves the following properties:

  • content: defines the file paths to be scanned for CSS usage. In this example, it includes all files under the./src/appdirectory and its subdirectories. In particular, PurgeCSS will look for JavaScript, TypeScript, and JSX files and extracts the used CSS selectors from them.
  • defaultExtractor: accepts a function that specifies how PurgeCSS extracts CSS selectors from the content files. It uses a regular expression to match valid selectors and ignores pseudo-elements and pseudo-classes.
  • safelist: specifies a list of selectors that should not be purged even if they are not explicitly used in thecontentfiles. Usually, you want to exclude thehtmlandbodyselectors to ensure they are preserved.

If your project still uses theNext.js Pages Router, you need to adapt thecontentfield accordingly:

 content: [ './pages/**/*.{js,jsx,ts,tsx}', './components/**/*.{js,jsx,ts,tsx}',] 

This way, the PurgeCSS plugin will look for CSS selectors in the right folders.

Sometimes, you may need to dynamically add CSS classes on specific events through JavaScript. In this scenario, the CSS selectors are not directly on the HTML elements in the JavaScript files, and PurgeCSS will not be able to recognize them as in use. Therefore, it will remove those dynamic classes from the resulting bundle CSS files. To avoid this, you can whitelist CSS classes:

safelist: { standard: ["html", "body"], deep: [ // whitelist all CSS classes that start // with "mt-" and "mb-" /^mt-/, /^mb-/, // whitelist the "highlighted" class "highlighted", ],} 

Note that thedeeparray insafeListaccepts both strings and regexes.

When using components from external libraries, you also need to add a special path tocontentas below:

content: [ // purging CSS in components from React Bootstrap "./node_modules/react-bootstrap/**/*.js", // remaining paths...] 

Otherwise, PurgeCSS would remove all CSS classes used by library components.

Note that there are many other options and configs available. Explore them inthe official doc.

PurgeCSS in Action

Next.js uses this PostCSS configuration during the build process. This means a change to thepostcss.config.jsfile will not trigger a hot reload. Instead, whenever you update the PostCSS config file, you need to stop the local server, delete the.nextfolder, and relaunchnpm run dev.

To analyze the effects of PurgeCSS, build your Next.js app with:

npm run build 

In the.nextfolder, you will find the build bundle. Specifically, the/static/cssfolder will contain the global CSS file generated with PostCSS.

Removing Unused CSS With PurgeCSS (5)

If you open it in Explorer, you will notice its size is 10 KB.

Now, delete thepostcss.config.jsfile and repeat the same procedure. In this case, the CSS files produced by the build operations are two:

Removing Unused CSS With PurgeCSS (6)

The first is the CSS file with the custom rules defined in the application, and the second is the entire Boostrap. Together, their size is 189 KB.

Summing up, PurgeCSS allows you to 179 KB. On such a simple application, that is a huge difference!

You can look at the entire code in theGitHub repository that supports the article. Clone it and launch it with the following:

git clone https://github.com/Tonel/purge-css-next-js-democd purge-css-next-js-demonpm run dev 

Et voilà! You now know how to use PurgeCSS in Next.js to reduce the bundle size and improve the Core Vitals.

Conclusion

This tutorial is finished! Now you know why unused CSS is a problem for SEO and user experience and how to fix it with PurgeCSS. Here, you saw how to configure PurgeCSS in PostCSS to automatically remove all unused CSS in a Next.js application.

As shown above, removing unnecessary CSS can lead to a significant difference in bundle size. This will result in better download and loading time for the end user!

Removing Unused CSS With PurgeCSS (2024)

FAQs

Removing Unused CSS With PurgeCSS? ›

PurgeCSS matches the CSS selectors used in your HTML elements with those in stylesheets. Then, it automatically removes all unused rules, producing smaller CSS files. Since the default behavior may produce undesired results, it is highly customizable and supports many options.

How do I remove unused CSS asset CleanUp? ›

Asset CleanUp Page Options

In the Manage CSS & JS page option, set the CSS that should not be loading on the page or post to be unloaded and when you save and refresh that page in your browser. The disabled/removed unused CSS assets will no longer be loading on the page or post.

Should I remove unused CSS? ›

you should remove it if you dont plan on ever using it. leaving unused code will increase you file size and slow your website down. Plus it will confuse you or future programmers as to why the code is their in the first place.

How do I purge unused CSS? ›

How to remove unused CSS manually
  1. Open Chrome DevTools.
  2. Open the command menu with: cmd + shift + p.
  3. Type in "Coverage" and click on the "Show Coverage" option.
  4. Select a CSS file from the Coverage tab which will open the file up in the Sources tab.
Mar 4, 2019

Is PurgeCSS good? ›

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 ...

How do I remove an existing CSS? ›

Using the removeProperty() method

To remove CSS property using JavaScript, we have used removeProperty() method. The removeProperty() method is used to remove the specified CSS property in the parameter. This method removes only inline styles.

How do I clear CSS properties? ›

CSS clear Syntax

The syntax of the clear property is as follows, clear: none | left | right | both | initial | inherit; Here, none : allows the element to float (default value)

What is PurgeCSS? ›

PurgeCSS is a tool to remove unused CSS from your project.

What is the alternative to unused CSS? ›

PurgeCSS. PurgeCSS is a powerful tool used to remove unused CSS from your project. It analyzes your contents and CSS files to identify CSS selectors that are not being used. It also removes unused CSS from your code, thereby resulting in smaller and optimized CSS files.

What is the impact of unused CSS? ›

Although a browser is very fast and you don't always notice it, unused CSS definitely affects page loading speed. In the long run, this in turn affects usability and ultimately a page's search engine results.

What is the alternative to PurgeCSS? ›

As mentioned before, there are 2 alternatives to PurgeCSS: UnCSS & PurifyCSS.

How to identify unused CSS? ›

To find unused code in your page, use the Coverage tool:
  1. To open DevTools, right-click the webpage, and then select Inspect. ...
  2. In DevTools, open the Command Menu. ...
  3. Start typing coverage, press the Down Arrow key to highlight the Show Coverage command, and then press Enter:
Dec 7, 2023

Does Tailwind remove unused CSS? ›

Tailwind does not delete unused css.

How to remove unused CSS in Angular? ›

In angular material, color="primary" changed to mat-primary in runtime. Post-build (PurgeCss), All the mat classes are removed from styles. css which are not used in any of the HTML/js files.

How to use PurgeCSS in React? ›

This example shows how to set up PurgeCSS with create-react-app template.
  1. Method 1 - Use craco. Custom PostCSS plugins (including PurgeCSS) can be added to Create React App apps using craco. ...
  2. Method 2 - Run PurgeCSS CLI in postbuild. Add the following code in package.json.
  3. Method 3 - eject create-react-app.
Nov 22, 2019

How to use critical CSS? ›

Configuring Critical CSS Manually

The goal here is dividing your CSS into two parts – critical and non-critical. First, you'll need to inspect your page's Document Object Model (DOM), go through every element on the page and consider the style that's applied to it. You'll need to do this for every page on your website.

How do I remove CSS from Chrome? ›

Open the Sources tool in Chrome or Edge DevTools. Find the CSS files that you want to disable, for example by pressing Ctrl+P (or Command+P on macOS) to open the Command Menu and by typing . css to filter the CSS files. Select the entire text in the CSS file and delete it.

How do I get rid of important CSS? ›

The only thing that can override an ! important tag is another ! important tag. By using it one once, you potentially end up with a CSS file that is full of !

How to find unused CSS in Chrome? ›

Chrome and Edge have a useful Coverage tool that can help identify which parts of code are unused. To detect unused code on page load: Open the Coverage tool by using the Command Menu: type Ctrl+Shift+P (or cmd+Shift+P on mac), then type Coverage and press Enter .

How do I delete unused managed objects? ›

To Delete Unused Attribute and Metric Managed Objects

In Developer, from the Administration menu, select Projects > Delete unused managed objects.

Top Articles
Retreat to Crete: why the Greek island is a perfect escape
How Are You Taxed After Selling a Mutual Fund in a Roth IRA?
Places 5 Hours Away From Me
Cottonwood Vet Ottawa Ks
Faint Citrine Lost Ark
Archived Obituaries
Western Union Mexico Rate
New Slayer Boss - The Araxyte
South Carolina defeats Caitlin Clark and Iowa to win national championship and complete perfect season
True Statement About A Crown Dependency Crossword
83600 Block Of 11Th Street East Palmdale Ca
REVIEW - Empire of Sin
Cooktopcove Com
Walthampatch
Saberhealth Time Track
Love In The Air Ep 9 Eng Sub Dailymotion
Pac Man Deviantart
Snow Rider 3D Unblocked Wtf
Velocity. The Revolutionary Way to Measure in Scrum
Spider-Man: Across The Spider-Verse Showtimes Near Marcus Bay Park Cinema
Inter-Tech IM-2 Expander/SAMA IM01 Pro
Kamzz Llc
Faurot Field Virtual Seating Chart
Mc Donald's Bruck - Fast-Food-Restaurant
Terry Bradshaw | Biography, Stats, & Facts
Buying Cars from Craigslist: Tips for a Safe and Smart Purchase
Craigslist Alo
eugene bicycles - craigslist
Victory for Belron® company Carglass® Germany and ATU as European Court of Justice defends a fair and level playing field in the automotive aftermarket
Dove Cremation Services Topeka Ks
Restaurants In Shelby Montana
27 Fantastic Things to do in Lynchburg, Virginia - Happy To Be Virginia
HP PARTSURFER - spare part search portal
Ups Drop Off Newton Ks
Alternatieven - Acteamo - WebCatalog
Winterset Rants And Raves
Frommer's Belgium, Holland and Luxembourg (Frommer's Complete Guides) - PDF Free Download
Kstate Qualtrics
Craigslist Car For Sale By Owner
Dr Adj Redist Cadv Prin Amex Charge
Dmitri Wartranslated
Merkantilismus – Staatslexikon
Cheetah Pitbull For Sale
Colorado Parks And Wildlife Reissue List
Sound Of Freedom Showtimes Near Amc Mountainside 10
Ratchet And Clank Tools Of Destruction Rpcs3 Freeze
10 Best Tips To Implement Successful App Store Optimization in 2024
Sitka Alaska Craigslist
Great Clips Virginia Center Commons
Best brow shaping and sculpting specialists near me in Toronto | Fresha
Costco Gas Price Fort Lauderdale
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 5782

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.