Exclude a class being tree-shaken by Tailwind

4.6k views Asked by At

Is there a way to exclude certain classes from being tree-shaken? The reason I ask is that in my JavaScript I'm using an arbitrary-value e.g. bg-[url('/img/hero-pattern.svg')] but the url is passed via a Vue computed property e.g.

`bg-[url('${this.image}')]`

I don't think this is being recognised, although I'm not certain.

I'm aware of how to use tailwind.config.js with the purge option, and the issue does not seem to be there, because other classes in the Vue component are included.

I'm using the mode: 'jit' option to allow arbitrary values.

3

There are 3 answers

1
Jonathan On BEST ANSWER

I've just noticed safelisting which I am using with Nuxt. I will use this in combination with advice based on this Github issue comment by using safelisting patterns e.g.

    options: {
      safelist: {
        greedy: [
          /^bg-/
        ]
      }
    }

Unfortunately, in my usecase, I can't use the above because of computed class names which is not supported. Instead I had to use an inline style.

1
Necor On

You can safelist classes as a last resort

module.exports = {
  content: [
    './pages/**/*.{html,js}'
    './components/**/*.{html,js}',
  ],
  safelist: [
    'bg-red-500',
    'text-3xl',
    'lg:text-4xl',
  ]
  // ...
}

More information at https://tailwindcss.com/docs/content-configuration#safelisting-classes

0
Sveen On

Updating the other solutions now to the TailWind 3.1.2. On the tailwind.config.js insert it

  safelist: [
    {
      pattern: /^(bg-|border-|text-)/,
      variants: ["hover", "active"],
    },
  ],