エンジニアを目指す初学者に向けて、わかりやすく解説したブログです。
サイトをリニューアルしました

ReactRouterのプロジェクトにTailwindCSSのPrettierを設定する

ゴール

以下のように、TailwindCSSのクラス名が一定の規則に従って整列するようになる。

Tailwindを使っていると、このクラス名がなにかと汚くなりがちなので、
VSCodeでファイル保存したときに自動でソートしてくれるようにしたい。

!-- Before -->
<button class="text-white px-4 sm:px-8 py-2 sm:py-3 bg-sky-700 hover:bg-sky-800">...</button>
<!-- After -->
<button class="bg-sky-700 px-4 py-2 text-white hover:bg-sky-800 sm:px-8 sm:py-3">...</button>

1. PrettierとTailwindCSSのPretteirプラグインをインストール

yarn add -D prettier prettier-plugin-tailwindcss

2. 設定ファイルにプラグインの記述を追加

拡張子は何でも良いが、筆者はよく.prettierrc.js を使っている。

/**
 * @see https://prettier.io/docs/configuration
 * @type {import("prettier").Config}
 */
const config = {
  plugins: ['prettier-plugin-tailwindcss'],
};

export default config;

3. VSCodeの設定

Command + ,で設定を開く。

設定ファイルを参照

prettierと検索し、 Prettier: Config Path に2で設定したファイルへのパスを記載する。

Image in a image block

保存時に自動フォーマットするようにする

formatと検索し、 Editor: Format On Saveにチェックを入れる。

Image in a image block