ふんばりフロントエンジニアのブログ

新米フロントエンジニアの備忘録です。ふんばり温泉タオル欲しい...

react-scriptsでのenvファイル切り替えと思うように行かなかったconfig設定

現在Reactの案件を進行中です。

具体的にはCoreUIというUIフレームワークを使って管理画面を作成しています。

このCoreUIはcreate-react-appで作成されているので、ビルドにはreact-scriptsを使っているのですがreact-scripts(create-react-app)でenvファイルを切り替える際には下記のようにする必要があります。

{
// 省略
"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "start:develop": "env-cmd -f .env.development yarn start",
    "start:staging": "env-cmd -f .env.staging yarn start",
    "start:production": "env-cmd -f .env.production yarn start",
    "build:develop": "env-cmd -f .env.development yarn build",
    "build:staging": "env-cmd -f .env.staging yarn build",
    "build:production": "env-cmd -f .env.production yarn build"
  }
}

CRA.md(create-react-appのmdファイル)を見てみると、「envファイルの切り替えは「env-cmd」パッケージ使うといいぞ」的なことが書いてあったのでそうしてます。
「dotenv -e .env.development」とかでもいけるみたいですが。

で、envファイルの読み込みはうまくいったのですが「awsのconfig系を全部書くのだるいな...」と思った私は一つのjsにまとめてNODE_ENVで切り替えればいいかなと思い下記のようなコードを書きました。

const config = {
  "aws_project_region": "ap-northeast-1",
  "userPoolId": "",
  "userPoolWebClientId": "",
  "identityPoolId": "",
  "aws_appsync_authenticationType": "AMAZON_COGNITO_USER_POOLS",
};

const awsmobile = () => {
  switch(process.env.NODE_ENV) {
    case 'development':
      config.userPoolId = 'ap-northeast-xxxxxxxxxx';
      config.userPoolWebClientId = 'xxxxxxxxxx';
      config.identityPoolId = 'ap-northeast-1:xxxxxxxxxx';
      break;
    case 'staging':
      config.userPoolId = 'ap-northeast-xxxxxxxxxx';
      config.userPoolWebClientId = 'xxxxxxxxxx';
      config.identityPoolId = 'ap-northeast-1:xxxxxxxxxx';
      break;
  }

  return config;
}

export default awsmobile;

こんな感じでやろうとしたら見事にハマりまして...

というのも、react-scriptsはstartかbuildでNODE_ENVが固定されて、上書きできないそうなんです。

github.com

なので、build(本番)なら「production」start(ローカル)なら「development」となってしまい、NODE_ENVでの切り替えは無理だとわかりました。

ということで大人しく.envに書きました笑

ただ、固定されることは意外と便利でローカルと本番で画像パス変えたいときとかは下記のように書くことができます。

const url = process.env.NODE_ENV === 'production'
          ? `/information/assets/${id}/${fileName}`
          : `${process.env.REACT_APP_S3_OBJECT_ROOT}/information/assets/${id}/${fileName}`

つまり大枠の環境は「start/build」で決めて、細部の環境(development/staging/production)は.envにまとめるといった形がいいのかな、と。


変なことしようとするもんじゃないですねほんと..