My project has a node dependency which depends on a environment variable to be set, the code is something simple as const KEY = process.env.SOME_KEY
.
I understand that react-native has no support for traditional environment variables.
What are de options to fulfill this need and make this code work? Supposing I don't have control over the dependency's code.
The React Native tools require some environment variables to be set up in order to build apps with native code. Open the Windows Control Panel. You can find the actual location of the SDK in the Android Studio "Settings" dialog, under Appearance & Behavior → System Settings → Android SDK.
React Native (and similar cross-platform frameworks) are unique. We have more than one environment we need to support - we (may) need to support iOS, Android, JavaScript, and possibly other platforms. So using a dedicated environment package for React Native makes sense. react-native-dotenv is my tried and true.
See this issue and the migration guide. React native does not have the concept of global variables. It enforces modular scope strictly, in order to promote component modularity and reusability. Sometimes, though, you need components to be aware of their environment.
You will need Node, the React Native command line interface, a JDK, and Android Studio. While you can use any editor of your choice to develop your app, you will need to install Android Studio in order to set up the necessary tooling to build your React Native app for Android.
The solution is pretty straight forward here, you should go with a custom babel transformer that will replace all process.env.
calls within your code with real env values during transpilation step (during that phase there's an access to environmental variables). Transforms are also applied to the dependencies of your app which means you can apply neccessary modifications to the 3rd party code w/o actually changing it.
In order to do it, you should first create a .babelrc
file like the one below and place it in the root of your project:
{
"presets": ["react-native"],
"plugins": [
"transform-inline-environment-variables"
]
}
Once that's done, go and npm install babel-preset-react-native
and babel-plugin-transform-inline-environment-variables
.
Finally, rerun react-native start
(basically restart the packager) and all your process.env calls will be replaced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With