Preserving dynamically generated TailwindCSS classes
NicolasBrondinBernard
Missing classes in production are a thing of the past!

Article published on 27/11/2023, last updated on 10/08/2026
If you're reading this article, chances are you've already had to inject a dynamic Tailwind CSS class into an HTML element, something like this:
<template>
<div class="alert" :class="'bg-'+alert.color+'-600'">
<p>{{alert.message}}</p>
</div>
</template>
During the development phase, everything works fine, but as soon as it comes to the "build" phase to put the code into production, you end up with several Tailwind classes missing!
But why?
To avoid having CSS files filled with unused classes (Tailwind has 1500+ of them), the build phase will detect all the classes actually present in the code, and generate the final file with only the classes used.
But the problem is that Tailwind is unable to detect dynamically generated classes like this 'bg-'+alert.color+'-600'
The solutions
There are two main solutions, to be chosen depending on your use case.
Don't hesitate to take a look at the official documentation, in the "Content Configuration" chapter, for more details!
Use full class names
The difference may seem trivial in terms of code, and yet it makes all the difference during the build phase. Instead of "generating" class names dynamically, you should favor using the full names of the classes, and "use" them dynamically, like this:
<template>
<div class="alert" :class="alert.isError ? 'bg-red-600' : 'bg-green-600'">
<p>{{alert.message}}</p>
</div>
</template>
Note that class detection also works in JS/TS scripts if you use the full names of the classes!
Configure a safelist
In the tailwind.config.js configuration file, it's possible to specify a list of classes to include in the final file, even if these classes are not found in the code, for example:
module.exports = {
//...
safelist: [
'text-2xl',
'text-3xl',
{
pattern: /bg-(red|green)-600/,
},
],
}
As you can see, it's even possible to specify regular expressions to include several classes at once!
Note that it is still advisable to use the previous solution, to avoid oversights!
Complete courses, exercises and certificates to really learn programming!
4.8 average rating
No comments yet