環境
"react": "^18.2.0",
"vite": "^5.0.0"
"tailwindcss": "^3.3.6",
"prettier": "^3.1.0",
"eslint-plugin-tailwindcss": "^3.13.0",
React + Vite の環境構築
まずは、React + Vite の環境を構築します。
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
Tailwind CSS を導入
次に、Tailwind CSS を導入します。
下記コマンドを実行して、必要なパッケージをインストールします。
npm install -D tailwindcss postcss autoprefixer
次に、設定ファイルを作成します。
コマンドを実行すると、tailwind.config.js
と postcss.config.js
が作成されます。
npx tailwindcss init -p
プロジェクトに Tailwind CSS を適用していきます。
// tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {},
},
plugins: [],
};
/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
Tailwind CSS の自動整形
自動整形に必要なパッケージをインストールします。
npm install -D prettier eslint-plugin-tailwindcss
VSCode にも拡張機能をインストールする必要があります。
下記リンクからインストール もしくは、VSCode上の拡張機能からPrettier - Code formatter
を検索してインストールします。
次に eslint の設定を行います。
// .eslintrc.cjs
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:react-hooks/recommended",
+ "plugin:tailwindcss/recommended",
],
ignorePatterns: ["dist", ".eslintrc.cjs"],
parser: "@typescript-eslint/parser",
plugins: ["react-refresh"]
rules: {
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
},
};
最後に vscode の設定を行います。
// .vscode/settings.json
{
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.formatOnType": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": ["source.fixAll.eslint"]
}
動作確認
設定が完了したので、動作確認を行います。
src/app.tsx の h1 タグにclassName="text-blue-300 m-2"
を追加して保存してみましょう。
自動でclassName="m-2 text-blue-300"
に並びかえられました!