
VSCode で React + Vite 環境に Tailwind CSS を導入して自動整形させてみた
この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
環境
"react": "^18.2.0",
"vite": "^5.0.0"
"tailwindcss": "^3.3.6",
"prettier": "^3.1.0",
"eslint": "^8.55.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の場合
// .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 },
],
},
};
Flat Configの場合
// eslint.config.js
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
import tailwind from "eslint-plugin-tailwindcss";
export default tseslint.config(
{ ignores: ["dist"] },
{
extends: [
js.configs.recommended,
...tseslint.configs.recommended,
...tailwind.configs["flat/recommended"],
],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.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"
に並びかえられました!