tailwind2-1 Exercise 2: A Class Name Built in Code =================================================== Run this in an empty folder that has Tailwind installed. It is bash. rm -rf dyn && mkdir -p dyn/src && cd dyn cat > src/badge.js <<'EOF' export const badge = (color) => `rounded px-2 py-1 text-white bg-${color}-600`; EOF cat > input.css <<'EOF' @import "tailwindcss" source(none); @source "./src"; EOF check() { npx @tailwindcss/cli -i input.css -o out.css >/dev/null 2>&1 for c in red green blue; do grep -q "^ \.bg-$c-600 " out.css && printf '%s ' $c; done; echo "(utility rules: $(grep -c '^ \.' out.css))"; } echo "1) template literal:"; check cat > src/badge.js <<'EOF' const colors = { red: "bg-red-600", green: "bg-green-600", blue: "bg-blue-600", }; export const badge = (color) => `rounded px-2 py-1 text-white ${colors[color]}`; EOF echo "2) lookup table:"; check cat > src/badge.js <<'EOF' export const badge = (color) => `rounded px-2 py-1 text-white bg-${color}-600`; EOF cat > input.css <<'EOF' @import "tailwindcss" source(none); @source "./src"; @source inline("bg-{red,green,blue}-600"); EOF echo "3) @source inline:"; check Output: 1) template literal: (utility rules: 4) 2) lookup table: red green blue (utility rules: 7) 3) @source inline: red green blue (utility rules: 7) WHY THIS WORKS AS AN ANSWER --------------------------- In step 1 the scanner reads src/badge.js as text. The string `bg-${color}-600` contains the characters "bg-$" and "-600", but no complete class name, so nothing is generated: four rules exist (rounded, px-2, py-1, text-white) and none of the three colours. At run time the browser would receive "bg-red-600", but by then the CSS has already been built. Step 2 puts the full names bg-red-600, bg-green-600 and bg-blue-600 in the file as ordinary strings; the scanner finds them, giving 7 rules. Step 3 keeps the dynamic template and tells Tailwind in the CSS which names to generate with @source inline("bg-{red,green,blue}-600"); the brace list expands to the same three classes and the count is again 7. The lookup table is better when the set is small and known, because the names are visible in the code where they are used. @source inline() is better when the names come from outside the code (for example a CMS or a user setting) and you want a fixed allowed list.