Tailwind, postcss and dynamic classes

What is the best way to handle situations where tailwind css classes are specified dynamically server side? How can post css process find these classes that are not specified explicitly.

<div class={some_class_var} ...

or using alpinejs

<div :class="classVar" ...

My understanding is that the css post processor checks all the files for css classes and purges the ones not used. How can these dynamic classes be ‘declared’ so the post processor will not purge them?

You can adjust the paths that tailwind looks at:

Note it obviously isn’t smart enough to know what bg-#{color} means, but sometimes I have just embedded the output classes in a comment, eg for a component that auto-sized to an input image with some n*n aspect ratios:

    # comments here for tailwindcss
    # iex(local@host)4> 1..16|>Enum.map(&"aspect-w-#{&1} aspect-h-#{&1}")
    # ["aspect-w-1 aspect-h-1", "aspect-w-2 aspect-h-2", "aspect-w-3 aspect-h-3",
    #  "aspect-w-4 aspect-h-4", "aspect-w-5 aspect-h-5", "aspect-w-6 aspect-h-6",
    #  "aspect-w-7 aspect-h-7", "aspect-w-8 aspect-h-8", "aspect-w-9 aspect-h-9",
    #  "aspect-w-10 aspect-h-10", "aspect-w-11 aspect-h-11",
    #  "aspect-w-12 aspect-h-12", "aspect-w-13 aspect-h-13",
    #  "aspect-w-14 aspect-h-14", "aspect-w-15 aspect-h-15",
    #  "aspect-w-16 aspect-h-16"]

These days you could probably just do that with aspect-[arbitrary-values]. I think defining your own plugins to do that is still technically a private API still but do-able if you live dangerously.

So if it finds the class names in a comment, it will pick it up? That sounds like a solution.

1 Like

as in doc link: class detection in depth

Nice, to think I looked at these very docs before posting… Thanks