0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Vite + React】環境変数を設定したけど値が「undefined」になってしまった

Posted at

経緯

開発環境にてフロント ↔︎ バックエンドで通信する時、localhostを直接書いていました。

本番環境に反映するため毎回書き換えるのは馬鹿らしいので、開発環境・本番環境でURLを簡単に切り替えられるようにしました。

設定するときに若干詰まったので、備忘録として残します。

環境

  • Docker
  • Vite
  • React
  • Typescript

設定(失敗)

まずは.envを作成して環境変数を定義します。
Reactを使用しているので以下のように設定しました。

.env
REACT_API_BASE_URL=http://localhost // 開発環境

.envの準備ができたので、コンテナを起動してうまく値を取得できているか確認。

console.log( process.env.REACT_API_BASE_URL);

// -> undefined

undefinedが出力されてしまいました…

再設定(解決)

少し調べてみると、Viteを使用しているため、環境変数の定義が間違えていることがわかりました。

.env
REACT_API_BASE_URL=http://localhost // これはこの環境では間違い

VITE_API_BASE_URL=http://localhost // こちらが正しい

環境変数を修正して、再度ログ出力をしてみると

console.log(import.meta.env.REACT_API_BASE_URL);

// -> http://localhost 

欲しい値が取得できました。

あとは同じように本番環境用の環境変数を定義したファイルを準備して、コンテナ起動時にオーバーライドさせれば、環境を切り替えることができるようになります。

以上です。

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?