Caveat: using PostCSS with dynamically generated content (JavaScript)

PostCSS removes “unused” CSS definitions. The underlying software therefore looks at the generated HTML pages to find the classes and elements they use. While this is generally fine and leads to smaller CSS data, there’s a possible conflict with JavaScript libraries that generate content at run time.
The case that bit me was lightgallery.js: Its CSS definitions were mostly removed by PostCSS because the relevant elements didn’t exit at build time. Consequently, the gallery did not behave as expected.
Removing PostCSS fixed that.

I’m not saying that PostCSS is faulty or anything, just that its use should be considered carefully.

PostCSS does not do this, the PurgeCSS plugin does. But you can configure it to preserve stuff, e.g. whitelists.

1 Like

Not PostCSS is removing those, a plugin that you configured in postcss.config.js does so. It does what you tell it to do. So do it the other way round: remove everything from your config and then look at what plugin you configure and use. Don’t copy paste samples. That’s the same as if I would be saying “don’t use Unix, because sudo rm -rf / breaks your system”.

1 Like

I love the analogy because that’s exactly what I did once about 40 years ago (with rm -rf * while the current directory was /). And I understand that it is not PostCSS itself that did what it did.
But then it might actually be helpful to amend the documentation so that it is clearer how it all fits together and where the pitfalls are. rm has the f flag, and one does not become root on a Unix machine easily (anymore, that is).
As it stands, “Purging with PostCSS” is explained (kind of) in “PostProcess” (why does it belong there, but not in “PostCSS”?). Then, instead of explaining what might be going on, it points to a tailwind page without any further explanation. Tailwind has examples but again points to another page for details.
But I learn that a stats file is written (although I do not learn what this file is needed for). And then there’s the example config file that is nothing more than unexplained JSON.
Under these circumstances, I think that a too broad “Caveat” might be more helpful.

The hugo_stats.json file contains the tags, classes, and ids used by your site. Using the config from the docs, PurgeCSS then reads this stats file and whitelists everything in it.

Tho, in my experience, I needed to whitelist more things, so I added the safelist config option to PurgeCSS with my custom tags/classes/ids.

1 Like

Thanks for the explanation. In the meantime, I had that figured out, too :slight_smile: In the beginning, I used a separate purgecss.config.js file, which of course did not get read. So now PostCSS uses purgecss with a safelist that protects all of lightgallery.
OT: Hugo is really great software. With better documentation (i.e. written for a clearly defined audience) it would also be a lot easier to use.

1 Like