tailwind-cssnuxt.jscss-purge

PurgeCSS ignore regex in whitelistPatterns and remove TailwindCSS classes (on NuxtJS)


I'm using NuxtJS (VueJS) with TailwindCSS and PurgeCSS. Until now, I was specifying complete CSS classes for colors like text-green-800, bg-red-400, etc. But when creating component it's not ideal while the color can be passed as a Prop, but it's also not possible to directly do bg-{color}-400 while PurgeCSS while remove the background colors not found.

So, I wanted to put those classes in the whitelistPatterns from PurgeCSS, allowing regex to protect some classes. This is what I've set up :

  purgeCSS: {
    whitelistPatterns: [/^bg-/, /^text-/, /^border-/]
  },

But PurgeCSS is completely ignoring the configuration. I've tried many regex : /bg-/, /bg/, /^bg-.*/, etc. None have worked. I thought that maybe it's using the new version of PurgeCSS which uses safelist instead, but when I set the whitelistPatterns like this :

  purgeCSS: {
    whitelistPatterns: ['text-green-800', /^bg-/, /^text-/, /^border-/]
  },

Then the text-green-800 class is successfully protected. So i'm completely lost, nothing seems to work. And obviously only happening on production, so difficult to debug.

I've already found this post which gives exactly what I've done : PurgeCSS whitelist patterns with TailwindCSS

If anyone has a lead... Thank you!


Solution

  • Ok, I finally figured it out!

    First, NuxtJS is using purgeCSS in version 2.3, using whitelist (string array) and whitelistPatterns (regex array). But TailwindCSS is also applying purgeCSS, but in version 3.x... using safelist (string|regex array)

    Defining purgeCSS configuration in nuxt.config.js file is actually useless. Everything is happening (for tailwind classes) in tailwind.config.js file.

    The misleading case was that when you define a class (bg-blue-200 for example) in the NuxtJS purgeCSS whitelist, TailwindCSS doesn't purge this class. Why? I don't know. TailwindCSS seems to keep the whitelist from Nuxt config, but not the whitelistPatterns...

    So, my solution is just to remove the purgeCSS config in nuxt.config.js (keep it if you have specific other classes to protect), and define the safelist in tailwind.config.js like this :

      purge: {
        content: [
          './components/**/*.{vue,js}',
          './layouts/**/*.vue',
          './pages/**/*.vue',
          './plugins/**/*.{js,ts}',
          './nuxt.config.{js,ts}'
    
        ],
        options: {
        // Whitelisting some classes to avoid purge
          safelist: [/^bg-/, /^text-/, /^border-/]
        }
      },