Purge CSS
Learn how to manage CSS classes by using the purge tool.
We'll cover the following
Tailwind generates an enormous number of classes that we probably will not use. For example, Tailwind generates hundreds of color variants for many different utility families. We can get pretty far by using the corePlugins
option to remove unused plugins, especially by limiting the color options to colors we use, but there’s a more automated way available. Tailwind uses a tool called PurgeCSS to identify which classes we use and remove unused classes from our build.
Enable purging
To enable purging, we change the array in the tailwind configuration file to contain a list of file patterns for any file in our project that might reference a Tailwind utility. This includes our static .html
and .jsx
files for a React project or .erb
files for a Rails project. It includes other files that might reference Tailwind utilities that are called template files. If we define lists of Tailwind classes in JavaScript or Ruby or any other language, those files also need to be listed in the purge array. We might wind up with something like the following for a React project:
module.exports = {
future: {},
purge: [
"./src/**/*.html",
"./src/**/*.jsx",
"./src/**/*.tsx",
], theme: {
extend: {},
},
variants: {},
plugins: [],
}
Below is how a Rails project might look:
module.exports = {
future: {},
purge: [
"./app/views/**/*.html",
"./app/views/**/*.erb",
"./app/helpers/**/*.rb"
],
theme: {
extend: {},
},
variants: {},
plugins: [],
}
If the purge key is not empty, when Tailwind is compiled and the NODE_ENV
is production
, the purge list will be used to generate a list of used classes and other classes will be purged.
Mechanism of purging
The mechanism PurgeCSS uses is simple by design. All it does is try to match this regular expression:
/[^<>"'`\s]*[^<>"'`\s:]/g
This results, more or less, in a list of all the words in our files. A Tailwind utility is purged if it’s not in that list. This is a somewhat expansive list of classes in that it might contain class names not being used as class names, which is generally fine. It would not catch a class name that is dynamically created via string concatenation.
We looked at the following example to create a hover
effect:
const hoverDarker = (color) => {
return `text-${color}-300 hover:text-${color}-700`
}
Because it creates a class name dynamically, this function would prevent those classes from being found by PurgeCSS, so we would either need to list those classes elsewhere or find another way to create this feature.
Get hands-on with 1400+ tech skills courses.