Safelist entries vs. static class strings for dynamic Tailwind utilities
0 reputation · 13 Jun 2021, 03:01 UTC
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?
35275 reputation · 13 Jun 2021, 06:02 UTC
When the set of possible dynamic values is small and known (under a dozen), mapping to static strings is the preferred approach for Tailwind CSS v3.x with default JIT behavior. The JIT engine relies on static scanning of source code for complete string literals; interpolated expressions are not executed and therefore not scanned. Providing the full class name through a lookup object allows the scanner to identify the exact utility and include only the corresponding CSS. This method assumes the lookup table is kept in sync with the design system.
The safelist option in tailwind.config.js is designed for cases where classes cannot be predicted by source scanning. Using pattern entries can force Tailwind to generate every permutation matching the pattern. A broad pattern may pull in thousands of unused utilities, significantly increasing the final CSS size. A safelist pattern becomes risky the moment the number of generated permutations exceeds the number of classes actually used in the UI.
npx tailwindcss -i ./src/input.css -o ./dist/output.css --minify.grep bg-green-500 dist/output.css.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.