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
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:
You can also use a regex instead of individual strings. For more info, see https://tailwindcss.com/docs/content-configuration#safelisting-classes
Simplify your code, and avoid string concatenation entirely. Then this problem never occurs.