21
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ReactプロジェクトにTailwindCSSを導入する

Posted at

ReactにTailwindCSSを導入

近年CSSのフレームワークのTailwindCSSを使う機会が増えてきたので、Reactのプロジェクトに導入する方法をまとめていきます。

Reactのプロジェクトを作成

まずはじめに、create-react-appでReactのプロジェクトを作成します。

$ npx create-react-app react-basic

TailwindCSSを導入

TailwindCSSをインストールします。

$ yarn add -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

 CRACOを導入

Create React APPの場合、TailwindCSSの動作に必要なPostCSSのサポートをしていないため、CRACO(Create React Configuration Override)をインストールします。

$ yarn add @craco/craco

CRACOを使って起動するようにするため、package.jsonのscriptsの箇所を変更します。

package.json
  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  }

プロジェクトのルートにcraco.config.jsを作成します。

craco.config.js
module.exports = {
  style: {
    postcss: {
      plugins: [require("tailwindcss"), require("autoprefixer")],
    },
  },
};

TailwindCSSの構成ファイルを作成します。

$ npx tailwindcss-cli@latest init

tailwind.config.jsファイルができたあと、purgeオプションを変更します。
指定したファイルの中で使用していないスタイルがあると、ビルド時に削除してくれます。

tailwind.config.js

module.exports = {
  purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

動作確認

TailwindCSSが使えるようにCSSファイルを作成します。

/react-basic/src/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;

一度srcフォルダの中にあるファイルをすべて削除し、下記のindex.jsを作成します。

/react-basic/src/index.js
import ReactDom from "react-dom";
import { App } from "./App";
import "./index.css";

ReactDom.render(<App />, document.getElementById("root"));

classNameにTailwindCSSが用意した属性を追加します。

/react-basic/src/App.jsx
export const App = () => {
  return <div className="text-red-400">こんにちは</div>;
};

実行します。

$ yarn start

TailwindCSSが反映されていることが確認できました。おつかれさまでした!

FireShot Capture 084 - React App - localhost.png

21
20
0

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
21
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?