Tailwind class sorting in Twig files with Prettier
Finally this is possible thanks to a workaround added to Tailwind's class sorting plugin
Posted 5th May 2023 • #development
Updated July 2024
You can find a working example of these articles in my boilerplate Craft site repository.
About a year ago, Tailwind CSS released a plugin for Prettier that automatically sorts your Tailwind classes using Prettier.
Prettier saves me a ton of time not having to manually format my Twig templates and you can set it up to format automatically whenever you save the file. Until recently though, the plugin I use for Prettier to make it work with Twig, and this Tailwind plugin were incompatible with each other. Thanks to Tailwind though, there's finally a workaround which lets these two work in tandem.
First, you'll want to follow the instructions in my Using Prettier with Twig in VS Code article to enable Prettier for Twig files. After that, follow the instructions on Tailwind's blog post to install the Tailwind class sorting plugin: Automatic Class Sorting with Prettier.
Once you've got both of them installed, add this to your .prettierrc file and you're good to go!
"plugins": [
"@zackad/prettier-plugin-twig-melody",
"prettier-plugin-tailwindcss"
]