In this tutorial, we'll delve into how you can customize your PurgeCSS configuration to better fit your project. You'll learn how to set up PurgeCSS to optimize your CSS, improving the performance of your web projects.
By the end of this tutorial, you will be able to:
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 customize PurgeCSS for your project:
Install PurgeCSS: You can install it using npm:
npm
npm install --save-dev purgecss
Configure PurgeCSS: Create a purgecss.config.js
file in your project root.
Define your configuration: The configuration file should export an object with your desired configuration.
Here is a basic example of what a PurgeCSS configuration might look like:
module.exports = {
content: ['./src/**/*.html'],
css: ['./src/**/*.css']
}
In this configuration, PurgeCSS will scan all HTML files in your src
directory for classes. It will then match these classes with the ones in your CSS files.
Let's look at some practical examples.
module.exports = {
content: ['./src/**/*.html'],
css: ['./src/**/*.css']
}
This configuration will remove unused CSS from all CSS files in your project.
Sometimes you might want to ensure certain CSS classes are never purged, you can do this with whitelisting:
module.exports = {
content: ['./src/**/*.html'],
css: ['./src/**/*.css'],
whitelist: ['important-class']
}
In this example, important-class
will never be removed, even if PurgeCSS can't find it in your content files.
In this tutorial, we learned how to install and configure PurgeCSS for your project. We also learned about whitelisting CSS classes to prevent them from being removed.
For further learning, you can explore other options available in PurgeCSS, like using regular expressions for the whitelist, or defining a whitelist pattern.
Exercise 1 - Set up a basic PurgeCSS configuration for a small project with HTML and CSS files.
Solution:
javascript
module.exports = {
content: ['./src/**/*.html'],
css: ['./src/**/*.css']
}
Exercise 2 - Add a class to the whitelist and ensure it doesn't get removed during the purge.
Solution:
javascript
module.exports = {
content: ['./src/**/*.html'],
css: ['./src/**/*.css'],
whitelist: ['my-class']
}
Remember, practice is key to mastering any tool. Keep trying different configurations and options in PurgeCSS to better understand how it works.