1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React + Vite】環境変数の設定方法 – VITE_ を必ず付けよう

1
Posted at

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。
React + Vite 環境で開発していると、API の URL などを環境によって使い分けたい場面があると思います
そんなときに使うのが**環境変数(Environment Variables)**です。

ただ、Vite には**環境変数名は VITE_ で始めないとフロントエンドから参照できない」**というルールがあります。
この記事では、その設定方法と注意点をまとめます。


1. 環境変数ファイルの作成

Vite ではプロジェクトのルートに .env ファイルを作成します。

例えば API のベース URL を環境変数で管理する場合は、以下のように書きます。

# .env
VITE_API_BASE_URL=https://example.com/api

VITE_ を付けないと、Vite はその変数をクライアント側で使えるようにしてくれません。


2. React コンポーネントでの読み込み方法

.env に書いた変数は、import.meta.env を使って読み込みます。

// src/App.tsx
function App() {
  console.log(import.meta.env.VITE_API_BASE_URL);

  return <div>API Base URL: {import.meta.env.VITE_API_BASE_URL}</div>;
}

export default App;

3. 複数環境の使い分け

開発環境と本番環境で API の URL を切り替えるには、以下のようにファイルを分けます。

.env.development
.env.production

例:

# .env.development
VITE_API_BASE_URL=http://localhost:3000

# .env.production
VITE_API_BASE_URL=https://example.com/api

Vite は npm run dev 実行時は .env.development を、npm run build 実行時は .env.production を自動で読み込みます。


4. よくある間違い

VITE_ を付けない

API_BASE_URL=https://example.com/api  # 間違い!

こうするとフロントエンド側からアクセスできず、undefined になります。

.env の場所が間違っている

.env は必ずプロジェクトルートpackage.json と同じ階層)に置きます。


5. まとめ

  • Vite では環境変数は .env ファイルで管理
  • フロントから参照する環境変数は必ず VITE_ で始める
  • import.meta.env で参照
  • 開発/本番で変数を分けるなら .env.development.env.production を使う

このルールを守れば、React + Vite 環境で安全かつ柔軟に設定を管理できます。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?