點燈坊

失くすものさえない今が強くなるチャンスよ

Sorting TailwindCSS Utilities Automatically with Prettier

Sam Xiao's Avatar 2022-02-08

People have been talking about the best way to sort your utility classes in TailwindCSS projects for many years. TailwindCSS announced the official Prettier plugin to solve this problem.

Version

TailwindCSS 3.0

Add Packages

$ npm install -D prettier prettier-plugin-tailwindcss
  • prettier : code formatter for HTML/CSS/JavaScript
  • prettier-plugin-tailwindcss : code formatter for TailwindCSS

Prettier

prettier000

WebStorm -> Preferences -> Language & Frameworks -> Prettier

  • Prettier package : WebStorm will get a path automatically after installing Prettier
  • Rule for files : add html for Prettier to work with TailwindCSS
  • On Reformat Code action : run Prettier with the default Reformat code action
  • On save : run Prettier on save

After checking On Reformat Code action and On save, Prettier works as the default code formatter instead of WebStorm internal formatter

Before Prettier

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.tailwindcss.com"></script>
    <title>TailwindCSS</title>
  </head>
  <body>
    <div class="text-white px-4 sm:px-8 py-2 bg-sky-700 sm:py-3 hover:bg-sky-800">
      <h1>Hello World</h1>
    </div>
  </body>
</html>

Line 10

<div class="text-white px-4 sm:px-8 py-2 bg-sky-700 sm:py-3 hover:bg-sky-800">
  <h1>Hello World</h1>
</div>

Utilities are written in random order.

After Prettier

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.tailwindcss.com"></script>
    <title>TailwindCSS</title>
  </head>
  <body>
    <div
      class="bg-sky-700 px-4 py-2 text-white hover:bg-sky-800 sm:px-8 sm:py-3"
    >
      <h1>Hello World</h1>
    </div>
  </body>
</html>

Line 10

<div
  class="bg-sky-700 px-4 py-2 text-white hover:bg-sky-800 sm:px-8 sm:py-3"
>
  • Utilities are sorted automatically by Prettier
  • HTML is also formatted by Prettier

Conclusion

  • With the official Prettier plugin for TailwindCSS, we can finally stop worrying about the order and grouping of utilities

Reference

WebStorm, Prettier
TailwindCSS, Automatic Class Sorting with Prettier
Tailwind Labs, Sorting Tailwind CSS Classes Automatically with Prettier