I have the "full" 3.9 MB Tailwind CSS file and successfully applied PurgeCSS to reduce it to 9 kB. But it also purged all responsive classes like md:px-6
, they don't show up in my purged version.
Note: this question is for using the command line interface (CLI)
This is what I did:
purgecss --css ~/Desktop/Projects/Flask/Project1/build/static/css/main.css --content ~/Desktop/Projects/Flask//Project1/build/**/*.html --output ~/Desktop/Projects/Flask/Project2/static/css/main.css
I chose to create the output file in a different folder (Project2
) so that I could check on the input vs output.
One thing I tried is to add --safelist [/md/]
, but didn't help. In fact the safelist didn't seem to be used at all...
(I use CLI since it is part of a bigger Python Flask project)
PurgeCSS relies on extractors to get the list of selectors used in a file. It provides a default extractor that is working fine with a wide variety of file types, but it can be limited and does not fit every CSS framework out there.
The default extractor considers every word of a file as a selector but it doesn't consider special characters like the colon (:
) which is heavily used in Tailwind CSS.
So, by default, PurgeCSS removes responsive (md:px-6
), hover (hover:bg-gray-500
), etc. classes. To avoid this, Tailwind has its own extractor. You could use this (or your very own) extractor but the PurgeCSS CLI has limited options and it's missing a defaultExtractor
option.
Luckily, it accepts a config file option, so if you create your own purgecss.config.js
file and add a default extractor in there, it will preserve these classes too. You can also add your other options to this file.
I used to use this extractor which will work with Tailwind's class names (e.g. bg-red-500
, dark:bg-red-500
, px-2.5
, .max-w-[800px]
, bg-[#FFFFFF]
)
(content) => content.match(/[\w\-:.\/\[#%\]]+(?<!:)/g) || []
Your config file will look like this:
// purgecss.config.js
module.exports = {
content: ['build/**/*.html'],
css: ['build/static/css/main.css'],
defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
output: 'static/css/main.css',
};
And you can use the following command to run PurgeCSS with the above config:
purgecss --config ./purgecss.config.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With