R4ttlesnake
R4ttlesnake

Reputation: 1771

PurgeCSS and Markdown output, how to whitelist element selectors?

starting to use tailwindcss i was soon confronted with the need for PurgeCSS in order to wipe of (a lot of) superfluous css from my stylesheets. Next to being a great tool in general, PurgeCSS can become a cat-and-mouse-game for wanted and unwanted selectors, especially after deploying tree-shaken-minified-nano-purged production code.

In order to prevent PurgeCSS from being to tidy it has some possibilities to whitelist selectors from being purged: using whitelist, whitelistPatterns, whitelistPatternsChildren or /* purgecss start and stop ignore */ directly in stylesheets.

Usually i'd protect some selectors regexp in the options and some whole imported stylesheets by comments (see example below). But especially selectors which have been created dynamically such as Markdown converted to HTML. All the <p>, <blockquote>, <h1>, <h2>, <a>, would be purged because they have not been present in the .md files.

This concerns mostly element selectors, so: is there a way or a regexp to whitelist all selectors which are not a class?

I tried some regexp for whitelistPatterns, like ^(?!\.).+, ^(?!\.)\w+, …, but they either did not work or whitelisted all selectors, including classes.

Thanks for any help.

// postcss.config.js
const whitelist = /^(\.|p|ul|ol|h\d+|pre|code|carousel|flickity|spinner)/
const purgecss = require("@fullhuman/postcss-purgecss")({
  // …
  whitelistPatterns: [whitelist],
  whitelistPatternsChildren: [whitelist] 
});
// styles.css
/*! purgecss start ignore */
@import "admin.css";
/*! purgecss end ignore */

Upvotes: 1

Views: 2283

Answers (1)

Matt
Matt

Reputation: 3900

Tailwind runs a pretty forgiving purge by default, as mentioned here. Keeping the default works for me, but if I configure purge mode "all", I start to lose styles exactly as you describe - Because the elements don't appear in my Markdown files.

To fix this, you can pass a list of whitelisted elements through to PurgeCSS from your Tailwind config file.

First, make sure you are using the optional configuration file:

npx tailwindcss init

You can then configure it something like below. Here, I am using the more aggressive purge but also whitelisting specific elements. Here's an example which parses 11ty layouts:

module.exports = {
    // Purge is executed only when NODE_ENV=production
    purge: {
        mode: 'all',
        content: [
            'site/_includes/**/*.njk'
        ],       
        options: {
            whitelist: [
                'body',
                'html',
                'a',
                'h1',
                'h2',
                'h3',
                'h4',
                'p'                
            ]
        }

  },
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}

Upvotes: 2

Related Questions