skip to Main Content

I would like to prevent Tailwind from purging some classes. They are generated in the component eg.

className=`text-${size}`

Tailwind does not know it will result in text-sm, text-base and text-lg even if size variable is a union of

type Size = "sm" | "base" | "lg";

Is it possible to achieve that without using full classes elsewhere in the code?
The only solution I managed to find is:

const sizeClass = size === "sm" ? "text-sm" : size === "lg" ? "text-lg" : "text-base";
(...)
className={sizeClass}

2

Answers


  1. Although Tailwind doesn’t recommend dynamic classes for this reason, you can still generate them if you add them to the safelist in your Tailwind config:

    module.exports = {
      ...
      safelist: [
        'text-sm',
        'text-base',
        'text-lg'
      ],
      ...
    }
    

    You can also use a regex instead of individual strings. For more info, see https://tailwindcss.com/docs/content-configuration#safelisting-classes

    Login or Signup to reply.
  2. Simplify your code, and avoid string concatenation entirely. Then this problem never occurs.

    className=`${textSize}`
    
    type Size = "text-sm" | "text-base" | "text-lg";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search