react-native-configからreact-native-ultimate-configへ乗り換えました
By kkoudev
React Nativeでのenvファイルの読み込みといえば react-native-config が有名なのですが、
v1.0.0 以降、iOSでどうも上手いこと動かず、issueを漁ると /tmp/envfile を作らないといけないといった記述がみられて微妙な感じになっていました。
そのためずっと 0.x.x バージョンの react-native-config を使っていたのですが、
react-native-ultimate-config の存在を知ったので今回乗り換えてみました。
使い方
使い方はREADMEをみていけばわかるのですが、 react-native-config と少し似ています。
ただ、こちらは非常にシンプルで、インストールすると使える rnuc
コマンドにて引数に指定した .env ファイルに基づいた環境変数設定を自動的に作成してくれます。
予めいくつか設定しておく必要があるので、詳しい設定方法はこちらをご覧ください。
yarn rnuc (元となる .env ファイルを指定する)
.envファイルは環境別に用意して以下のようにビルドや実行前に切り替えればOKです
# Staging環境へ切り替え
yarn rnuc .env.staging
# Production環境へ切り替え
yarn rnuc .env.production
また、そこまでメリットはないかもですがYAML形式のファイルを使うこともできるようです。
yarn rnuc .env.staging.yaml
まとめ
react-native-configはiOSシミュレータでの利用時にキャッシュがあると上手いこと読み込む変数が切り替わらなかったりすることがありましたが、
react-native-ultimate-config は今のところそのようなこともなく快適に使えています。(これも /tmp/envfile の影響かもしれませんが)
react-native-config に苦労した経験のある方は試しに乗り換えてみるといいかもしれません。