LoginSignup
0
0

More than 1 year has passed since last update.

Dotenvのサンプルコードを動かしてみる

Posted at

はじめに

reactで環境変数を切り替える方法を毎回忘れるのでメモりました。
ここではdotenvのサンプルコードを動かして検証していきます。

サンプルアプリの起動

  • Git
  • node.js
git clone https://github.com/dotenv-org/examples.git
cd examploe/dotenv-react
npm i
npm run start

上手く起動ができました!
.envに書かれている”CHANGE_ME”が表示されてることが確認できます!

スクリーンショット 2022-10-14 23.10.53.png

環境ごとに切り替える

ここで他の環境変数へ切り替えたいので、開発用、ステージング用、本番用のenvファイルを作成します。

スクリーンショット 2022-10-14 23.58.47.png

ただReact公式ドキュメントを見ると、.env.development(開発環境)と.env.production(本番環境)はnpm run start, npm run buildで切り分けられていると書かれていて、これだと開発環境をデプロイしたり、ステージング環境を追加したりといったことができません。

Files on the left have more priority than files on the right:
npm start: .env.development.local, .env.local, .env.development, .env
npm run build: .env.production.local, .env.local, .env.production, .env
npm test: .env.test.local, .env.test, .env (note .env.local is missing)
What other .env files can be used?

dotenv-cliを入れて、コマンドで読み込む.envファイルの読み込みを切り替えられるようにしましょう。

npm install --save-dev dotenv-cli

スクリプトの実装

package.jsonを以下のように書き換えると、npm run build-development.env.developmentを、npm run build-production.env.productionを参照するようになります。

  "scripts": {
    "start": "react-scripts start",
    "build-development": "dotenv -e .env.development react-scripts build",
    "build-production": "dotenv -e .env.production react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

参考サイト

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