DEV Community

Cover image for Automatically Sorting Tailwind Classes with Prettier
James 'Dante' Midzi
James 'Dante' Midzi

Posted on

Automatically Sorting Tailwind Classes with Prettier

Ever since TailwindCSS was released there has been a silent battle as to what is the best order for Tailwind's utility classes. I like to believe there is now a definitive answer.

What Is Tailwind?

Tailwind is a utility first CSS framework that aims to get you to use as little CSS as possible.

Up until now, there hasn't been a definitive answer to how to order the classes - which is fitting considering the nature of Tailwind.

Extensions like Headwind have tried to give some rules to this.

Enter Prettier Plugin Tailwind


How Does The Plugin Work?

It uses Prettier's format on save and Tailwind's method of sorting classes. Meaning classes in the base will be first, followed by ones in components, then lastly the ones in utilities:

usorted.png
unsorted classes

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

sorted.png
classes after sorting

If you made custom classes, they would go first, for example:

custom...png
My custom classes

custom.png
How they are sorted after saving


How To Start Using The Plugin

After making sure you have a package.json in your project, simply run:

npm install -D prettier prettier-plugin-tailwindcss
Enter fullscreen mode Exit fullscreen mode

Now any time you save, your classes will be automatically sorted.

Formatting An Existing Project

If you have an existing project that you would like to use the plugin on, simply run the above command then:

  1. Check which files need formatting
npx prettier --check .
Enter fullscreen mode Exit fullscreen mode
  1. Write to those files or folders:
npx prettier --write [dir name]
Enter fullscreen mode Exit fullscreen mode

Conclusion

How do you order your Tailwind classes? Would you consider using the plugin?

image credit: TailiwindCSS


Thank you for reading, let's connect!

Thank you for visiting this little corner of mine. Let's connect on Twitter, Polywork and LinkedIn

Top comments (0)