Profiles in React
When working with create-react-app, you can configure your app using environment variables.
It is explained in detail in the documentation here: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
All environment variables need to be prefixed with REACT_APP_
.
You can define profiles with different environment variables using .env files.
For example, to set an API URL in production, create a file .env.production with the following contents:
REACT_APP_API_URL=https://my.beautiful.api/
…and as default (for local development), create a file .env:
REACT_APP_API_URL=http://localhost:3001/
- The environment variables from the .env.production file will be used when you build your project with
npm run build
- The environment variables from the .env file will be used when you work on your project in local dev mode with
npm start
Example for using the environment variable in your app's code:
fetch(process.env.REACT_APP_API_URL) .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(JSON.stringify(myJson));});
The way i handle this case is by using package react-native-config
and i have create .env file (.env.dev, .env.staging, .env.prod) and i have define some scripts in the package.json. I am using react-native init project though.as below
"scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "test": "jest", "postinstall": "sed -i '' 's/#import <RCTAnimation\\/RCTValueAnimatedNode.h>/#import \"RCTValueAnimatedNode.h\"/' ./node_modules/react-native/Libraries/NativeAnimation/RCTNativeAnimatedNodesManager.h", "clean": "cd android && gradlew clean", "feature": "node scripts/createfeature.js", "component": "node scripts/createcomponent.js", "android": "cd android && gradlew app:assembleDebug && gradlew installDebug", "storybook": "storybook start -p 7007", "prestorybook": "rnstl", "android-dev": "SET ENVFILE=.env.dev && react-native run-android", "android-staging": "SET ENVFILE=.env.staging && react-native run-android", "android-prod": "SET ENVFILE=.env.prod && react-native run-android", "ios-dev": "ENVFILE=.env.dev react-native run-ios", "ios-staging": "ENVFILE=.env.staging react-native run-ios", "ios-prod": "ENVFILE=.env.prod react-native run-ios", "build-android-prod": "SET ENVFILE=.env.prod && cd android && gradlew assembleRelease" },