react-native-configで環境変数を参照する
react-native-config
1つのプロジェクトで開発、検証、本番などを行う際、 それぞれ別のプロジェクトで運用するのはたいへんなため、環境変数などで APIの向き先などを調整する
今回やること
react-native-configで環境変数を参照するところまで
参考情報
GitHub - luggit/react-native-config: Bring some 12 factor love to your mobile apps!
GitHub - Clintal/react-native-config at ios-manual-linking
react-nativeで環境ごとに定数を切り替える(react-native-config) | I am mitsuruog
ReactNativeConfig使ってみた&使い方 - Qiita
React Nativeにおける環境別ビルド設定 | エンジニアブログ | 株式会社スクーラー
手順
プロジェクトを作成
npx react-native init sampleConfig01 cd sampleConfig01
react-native-configを導入
yarn add react-native-config
pod install(iosのみ実施)
npx pod-install
手動設定(android)
/android/settings.gradleにreact-native-configを追加
rootProject.name = 'sampleConfig01'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
// react-native-config用追加
include ':react-native-config'
project(':react-native-config').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-config/android')
/android/app/build.gradleにreact-native-configを追加
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
// react-native-condig用追加
implementation project(':react-native-config')
・
・
・
}
/android/app/build.gradleの先頭から2行目あたりに以下を追加
project.ext.envConfigFiles = [
debug: ".env",
dev: ".env.dev",
stg: ".env.staging",
prd: ".env.production",
anycustombuildlowercase: ".env",
]
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
手動設定(ios)
workspaceを開く

node_modules配下のreact-native-configのプロジェクトをドラッグして参照を紐付ける

一旦、ビルドを行う

プロジェクトのpod配下にコンパイルされたreact-native-configのモジュールを紐付け

再度、ビルドを行う

.envファイルを作成
.env
APP_NAME=TEST VERSION=0.0.1
react-nativeへ実装
App.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React from 'react';
import {Text, View} from 'react-native';
import Config from 'react-native-config';
const App = () => {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>APP_NAME: {Config.APP_NAME}</Text>
<Text>VERSION: {Config.VERSION}</Text>
</View>
);
};
export default App;
結果

補足
自動リンクではファイルからデータを取得できなかったため、手動で設定して取得するように対応 環境別の指定方法とかは今度かく