0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React プロジェクトへの Tailwind CSS(V4) 導入方法

0
Last updated at Posted at 2026-01-25

概要

Tailwind CSS の公式ドキュメントでは Tailwind CSS のプロジェクトの作り方としての説明しかなく、既存の React プロジェクトなどへの導入手順が書かれていない。

実のところ vite で作ったプロジェクトならば以下公式ページの "Using Vite" タブの手順そのままで大体問題無いが、一部 HMR に影響のある設定などを加える必要がある。

ここでは一応その手順をメモっておく。

オーバービュー

全体の手順を先に示しておく

  1. Tailwind CSS と vite 向けプラグインをインストールする
  2. vite.config.ts にプラグインを追加する
  3. CSS に Tailwind の import 文を書いておく
  4. src/main.tsx 等に CSS をインポートする
  5. tailwind.config.ts を作成して、CSS の生成範囲を絞る

前提条件

  • 使用する Tailwind CSS のバージョンは V4
  • npm create vite@latest my-app 等のように vite で作られた React のプロジェクトがすでにある

手順

1. Tailwind CSS と vite 向けプラグインをインストールする

npm install tailwindcss @tailwindcss/vite
  • tailwindcss: Tailwind CSS 本体
  • @tailwindcss/vite: Vite 専用の Tailwind CSS 統合プラグイン

2. vite.config.ts にプラグインを追加する

vite.config.ts に以下の様に記述して @tailwindcss/vite プラグインを追加します。

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";// 追加

export default defineConfig({
	plugins: [react(), tailwindcss()],
	//                 ^^^^^^^^^^^^^^ 追加
});

3. CSS に Tailwind の import 文を書いておく

src/index.css などのグローバル CSS に以下の様に記述しておく。

@import "tailwindcss";

4. src/main.tsx 等に CSS をインポートする

import "./index.css";

公式ドキュメントでは html の方に <link href="/src/style.css" rel="stylesheet"> という感じでリンクする方法が紹介されているが、Vite を使っている場合:

  • .css を JS/TS で importする方式をとっておくと HMR に対応した CSS になる。
  • ビルド時は Vite が CSS としてまとめて出力してリンクしてくれる(つまり、 <link href="/src/style.css" rel="stylesheet"> の記述は不要)

というメリットがある。

5. tailwind.config.ts を作成して、CSS の生成範囲を絞る

プロジェクトのルートに tailwind.config.ts ファイルを作成し、以下の様に記述する。

export default {
  content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
};

この記述により CSS のビルド対象を限定することができ、tailwind によるビルドを軽く出来る。

6. それでも HMR が遅い場合

それでも npm run dev で動くサーバの HMR が重い場合、ファイルの watch モードが原因の可能性がある。

vite.config.ts でサーバーの watch モードを polling に設定することで改善が望める。

export default defineConfig({
  plugins: [react(), tailwindcss()],
  // ↓ を追記
  server: {
    watch: {
      usePolling: true,
      interval: 500,
    },
  },
})

interval (単位 ms)については PC の負荷を考え、適宜調整すること。


以上で導入完了。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?