CRA(Create-React-App)とViteといったビルドツールによってReactアプリの作成方法が異なるのでその違いと、.envファイルの読み込む方法も異なるので記載しておきます。
CRA(Create-React-App)を使ったプロジェクト作成とTailwindcssを取り込む方法
Install Tailwind CSS with Create React App
CRAを使ったプロジェクト作成手順
1.プロジェクト作成
下記のコマンドを使ってプロジェクトを作成します。
npx create-react-app [プロジェクト名]
2.作成したプロジェクトの配下に移動
下記のコマンドでプロジェクトに移動します。
cd [プロジェクト名]
3.TailwindCSSをインストール
コマンドを使ってTailwindCSSをインストールします。
npm install -D tailwindcss@3
npx tailwindcss init
4.Templateパスの設定
tailwind.config.jsにパスを設定します。
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
5.TailwindCSSをインポート
index.cssにTailwindcssをインポートします。
@tailwind base;
@tailwind components;
@tailwind utilities;
6.アプリを起動
下記のコマンドでアプリを起動します。
npm run start
Viteを使ったプロジェクト作成とTailwindcssを取り込む方法
Get started with Tailwind CSS
Viteを使ったプロジェクト作成手順
1.プロジェクト作成
下記のコマンドを使ってプロジェクトを作成します。
npm create vite@latest [プロジェクト名]
2.作成したプロジェクトの配下に移動
下記のコマンドでプロジェクトに移動します。
cd [プロジェクト名]
3.TailwindCSSをインストール
コマンドを使ってTailwindCSSをインストールします。
npm install tailwindcss @tailwindcss/vite
4.Viteプラグインの設定
修正前
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [
react()
],
})
修正後
import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'//👈追加
// https://vite.dev/config/
export default defineConfig({
plugins: [
tailwindcss(),//👈追加
],
})
5.TailwindCSSをインポート
index.cssにTailwindCSSをインポートします。
@import 'tailwindcss';
6.アプリを起動
下記のコマンドでアプリを起動します。
npm run dev
.envファイルの設定情報はビルドツールによって異なる点に注意する
.envファイルの①開発用と②本番用の書き方の記事については以前に紹介しましたので下記を参照してください。
さて、今回は前回記事に補足した情報を追加しておきます。
1. 前提:どのツールで React を動かしているかを確認する
React プロジェクトの種類によって 環境変数の扱いが違います。
| ツール | 使用可能な環境変数の接頭辞 |
|---|---|
| CRA (create-react-app) | REACT_APP_ |
| Vite | VITE_ |
| Next.js | NEXT_PUBLIC_ |
| Webpack 手動構築 | 任意(DefinePlugin) |
CRA(Create-React-App)の場合の環境変数の書き方
REACT_APP_△△△=〇〇〇〇
具体例を示すと、
REACT_APP_URL=https://example.com/api
という書き方になります。
⚠️ REACT_APP_ で始まらない変数は読み込まれません。
また .env.development はnpm startの時にだけ読み込まれます。
App.tsxの書き方は下記のようになります。
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Navbar from './components/navbar/page';
const App: React.FC = () => {
const [message, setMessage] = useState<string>('');
const topUrl = process.env.REACT_APP_TOP_URL;
useEffect(() => {
if (!topUrl) {
alert("URL情報(REACT_APP_TOP_URL)がありません。");
return;
}
axios
.get(topUrl)
.then((response) => {
setMessage(response.data);
})
.catch((error) => {
console.error('There was an error!', error);
});
}, [topUrl]); // ← 依存配列に入れる
return (
<div>
<Navbar />
<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full">
Button
</button>
<h1>{message}</h1>
</div>
);
};
export default App;
Viteの場合の環境変数の書き方
Vite では 環境変数は必ずVITE_で始める必要があります。
VITE_△△△=〇〇〇〇
具体例を示すと、
VITE_TOP_URL=https://example.com/api
という書き方になります。
⚠️ VITE_ で始まらない変数は読み込まれません。
また.env.development はnpm run dev実行時に読み込まれます。
Vite ではimport.meta.envを使うことが重要です。
App.tsxは下記のようになります。
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Navbar from './components/navbar/page';
const App: React.FC = () => {
const [message, setMessage] = useState<string>('');
// Vite の環境変数は import.meta.env
const topUrl = import.meta.env.VITE_TOP_URL as string | undefined;
useEffect(() => {
if (!topUrl) {
alert("URL情報(VITE_TOP_URL)がありません。");
return;
}
axios
.get(topUrl)
.then((response) => {
setMessage(response.data);
})
.catch((error) => {
console.error('There was an error!', error);
});
}, [topUrl]);
return (
<div>
<Navbar />
<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full">
Button
</button>
<h1>{message}</h1>
</div>
);
};
export default App;
型安全にしたい場合(オプション)
env.d.ts を追加:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_TOP_URL: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
これでimport.meta.env.VITE_TOP_URLが TypeScript で型チェックされます。
サイト
npx tailwindcss initでnpm error could not determine executable to runエラーが出た際の対処方法