In this tutorial, we aim to learn how to reduce the size of our CSS files by eliminating styles that aren't being used. Large CSS files can slow down websites, so it's beneficial to keep these files as lean as possible. We'll be using a tool called PurgeCSS to accomplish this.
By the end of this tutorial, you should have a clear understanding of how to remove unused CSS from your files, therefore improving your website's performance.
PurgeCSS is a tool to remove unused CSS. It can be used as part of your development workflow. PurgeCSS comes with a JavaScript API, a CLI, and plugins for popular build tools.
Here are the steps to use PurgeCSS:
npm install --save-dev purgecss
purgecss.config.js
file in your project root. This file will specify the paths to all of the files in your project you want PurgeCSS to scan for used classes:module.exports = {
content: ["./src/**/*.html", "./src/**/*.vue", "./src/**/*.jsx"],
css: ["./src/**/*.css"]
};
In this example, PurgeCSS will scan all .html, .vue, and .jsx files in your src
directory for used classes, and compare them to the classes in your CSS files.
npx purgecss --config ./purgecss.config.js --output ./dist
This command will generate a new CSS file in the dist
directory. This file will only include the CSS used in your project.
Let's say we have a CSS file with the following content:
/* src/styles.css */
.button {
padding: 10px;
color: white;
background-color: blue;
}
.unused-class {
color: red;
}
And an HTML file that looks like this:
<!-- src/index.html -->
<button class="button">Click me</button>
After running PurgeCSS, our CSS file would look like this:
/* dist/styles.css */
.button {
padding: 10px;
color: white;
background-color: blue;
}
The .unused-class
has been removed because it is not used in any of the HTML files.
PurgeCSS is a powerful tool that can significantly reduce the size of your CSS files by removing unused styles. It's easy to integrate into your build process and can help improve the performance of your website.
Create a CSS file with 10 classes, but only use 5 in your HTML. Run PurgeCSS and verify that the unused classes have been removed.
Add PurgeCSS to the build process of an existing project. How much does it reduce the size of your CSS file?
(Advanced) Configure PurgeCSS to run whenever you save a file in your project. You can use a tool like npm-watch or nodemon for this.