Colours built from a variable work in dev and come out unstyled in production — what am I misunderstanding?
I have a badge component that takes a colour prop and builds the class from it, something like a template string that produces bg-red-500 or bg-green-500 depending on the value.
In development every badge is correctly coloured. In the production build they are all unstyled — the class is on the element in the DOM, spelled correctly, and there is no rule for it in the stylesheet.
I have checked the content paths in the config and the file is definitely included, because other classes in the same file work fine. It is only the ones I build from the variable.
What is the actual mechanism here? I would like to understand it rather than pasting a fix, because I suspect I have made the same mistake elsewhere.
@full_names_only · 2h ago
The fix that follows directly: write the complete class names out and select between them.
A lookup object mapping your prop values to full class strings. Every class appears literally in the file, the scanner finds all of them, and you index into the map at runtime.
Why this is better than it looks:
bg-red-500finds the place it is used, which a template string breaks completely.The rule I apply everywhere now: never build a class name by concatenation. Not for colours, not for spacing, not for grid columns, not for widths. The moment a class is assembled from pieces you are relying on something that does not exist.
The partial version catches people too —
`bg-${color}-500`is obviously broken once you know the mechanism, but so is`${base}-500`, and so is splitting a class across a line break in a way that leaves the text discontinuous.Since you suspect you have done this elsewhere: search your source for a backtick or a plus sign near a class attribute. That finds nearly all of them in a few minutes.
Reply
Report