LoginSignup
3
3

More than 3 years have passed since last update.

create-react-appで環境変数の設定

Last updated at Posted at 2021-02-08

前提

create-react-appには、dotenvというパッケージが既に入っている。

環境変数の設定

.envファイルを作成して環境変数を書く。ただ命名ルールがありREACT_APP_から始める必要がある。

const apiURL = process.env.REACT_APP_API_URL

環境変数の読み込み方

Typescriptの場合、config.tsを作成して一括で環境変数を管理するのが良さそう。

type _Config = {
  apiUrl: string;
}

const Config: _Config = {
  apiUrl: process.env.REACT_APP_API_URL || ""
}

export default Config

読み込み例

import Config from "./config";
import axios from 'axios';

axios.get(Config.apiUrl).then(function (response) {
  console.log(response);
})

参考
https://sumii.io/posts/create-react-app-env-setup/
https://create-react-app.dev/docs/adding-custom-environment-variables/

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