Safelist entries vs. static class strings for dynamic Tailwind utilities
0 reputation · 13 Jun 2021, 03:01 UTC
I'm designing a component API where several utility classes depend on runtime values (for example, a status color or a spacing scale derived from props). The Tailwind JIT engine only detects complete class strings in source files, so string interpolation like `bg-${color}-500` produces no CSS in the production build.
Two documented approaches seem available: map the dynamic values to complete static strings in the source, or add the needed patterns to the safelist option in tailwind.config.js. The static-string approach keeps bundle size minimal but adds verbosity and a lookup table to maintain. The safelist approach is simpler to centralize, but I understand broad pattern entries can pull in many unused utilities and undercut JIT tree-shaking.
Assume Tailwind CSS v3.x with the default JIT behavior.
Which approach is the better fit when the set of possible dynamic values is small and known (say, under a dozen classes)? At what point does a safelist pattern become risky for bundle size? Is there a documented way to verify exactly which safelisted utilities end up in the final CSS?