Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PurgeCSS and Tailwind CSS, how to preserve responsive classes using the Command Line Interface?

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)

like image 279
Tristan Bains Avatar asked Mar 02 '23 19:03

Tristan Bains


1 Answers

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
like image 196
Zsolt Meszaros Avatar answered Mar 05 '23 15:03

Zsolt Meszaros