LoginSignup
13

More than 3 years have passed since last update.

tailwind2.0 + react + typescript 環境構築

Posted at

tailwindとreactの環境作り、特にPostCSSに苦労したのでまとめようと思ったら本家がわかりやすくなってたのでやってみました。
公式の通りなのでぜひ公式もご覧ください。

Install Tailwind CSS with Create React App

公式ではtypescriptやyarnは使用しません。

環境

$ node -v
v14.15.3

$ yarn -v
1.22.10

$ npx create-react-app --version
3.4.1

Reactアプリ作成

テンプレートをTypescriptで作成します。

$ yarn create react-app app-name --template typescript
$ cd app-name
$ yarn start

tailwind導入

パッケージを追加します。

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

Create React Appで作ったままではPostCSSの設定を上書きできないのでCRACOをインストールします。

$ yarn add @craco/craco

package.jsonファイル内のスクリプトをreact-scriptsの代わりにcracoを使用します。ejectはそのままです。

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

craco.config.jsを作成します。
PostCSSのプラグインとしてtailwindcssとautoprefixerを追加します。

module.exports = {
  style: {
    postcss: {
      plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
      ],
    },
  },
}

tailwindの設定ファイル作成

initを実行するとtailwind.config.jsが作成されます。

$ npx tailwindcss init

buildしたときに未使用のスタイルを含めないようにtailwind.config.jsのpurgeオプションにすべてのコンポーネントへのパスを指定します。

module.exports = {
  purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
  // ...
}

プロジェクトのCSSにtailwindを追加

デフォルトで作成される./src/index.css@tailwindディレクティブを使ってbase, components, utilitiesを含めます。

@tailwind base;
@tailwind components;
@tailwind utilities;

tailwindを使ってみる

簡単にボタンでも作ってみます。
./src/Button.tsxを追加します。

import React from 'react';

export const Button: React.FC = ({ children }) => {
  return (
    <button className="py-2 px-4 bg-green-500 text-white font-semibold rounded-lg shadow-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-400 focus:ring-opacity-75">
      {children}
    </button>
  );
};

./src/App.tsxにButtonをimportします。

import React from 'react';
import logo from './logo.svg';
import './App.css';
import { Button } from './Button';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        // ...
        <Button>Click!</Button>
      </header>
    </div>
  );
}

export default App;

実行します。

$ yarn start

yarnstart.png

とても簡単にtailwindが導入できました。

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
13