13

I am trying to preserve all TailwindCSS colour classes (i.e bg-green, bg-red, text-green, text-red) when it is processed via PurgeCSS. These colour classes are set in the CMS rather than code so we cannot search the code for them as they don't (all) exist here.

Therefore I want to use the whitelisting feature of PurgeCSS to retain all classes that beging with 'bg-' or 'text-'. However, the pattern I have below doesn't seem to be doing the trick? Any ideas how to tweak it?

whitelistPatterns: ['^bg\-', '^text\-'],
TylerH
  • 20,799
  • 66
  • 75
  • 101
dungey_140
  • 2,602
  • 7
  • 34
  • 68

6 Answers6

16

The issue appears to be simply to use regexp, not a string.

whitelistPatterns: [/^bg-/, /^text-/], // Retain all classes starting with...
dungey_140
  • 2,602
  • 7
  • 34
  • 68
14

If you run newer versions of tailwind: whitelist and whitelistPatterns merged into safelist. This info cost me a day of research.

purge: {
  options: {
    safelist: ["bg-red-50"],
  },
  // ... or even
  options: {
    safelist: [/^bg-/, /^text-/]
  },

}
Haukez
  • 141
  • 1
  • 6
3
purge: {
  options: {
    safelist: ["whitelisted"],
  },
  // ...
}
Oleg
  • 121
  • 1
  • 2
3

In TailwindCSS version 3.0.24 it is integrated a bit differently.

// Example tailwind.config.js (see my config file)

module.exports = {
  content: [
    './pages/**/*.{html,js}',
    './components/**/*.{html,js}',
  ],
  safelist: [
    'text-2xl',
    'text-3xl',
    {
      pattern: /bg-(red|green|blue)-(100|200|300)/,
      variants: ['lg', 'hover', 'focus', 'lg:hover'],
    },
  ],
  // ...
}

Source: Documentation

Julian
  • 598
  • 8
  • 23
1

Im doing it based on official suggestion like this:

whitelistPatterns: [/\-blue\-/],
whitelistPatterns: [/\-pink\-/],
...etc

Selectors with ending or starting it does not fit your needs. Think this one

.xl\:hover\:bg-pink-900:hover

or this one

.xl\:bg-cover
Stavros
  • 743
  • 8
  • 19
0

Based on this tailwind documentation, using something like this worked for a similar problem I had. The '+' works as wildcard.

module.exports = {
 // ...
 safelist: [
   {
      pattern: /bg-+/
   },
   {
     pattern: /text-+/
   },
 ],
 // ...
LaZza
  • 360
  • 3
  • 7