Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

environment variables on react-native custom dependency

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.

like image 486
enapupe Avatar asked Jul 28 '16 13:07

enapupe


People also ask

How do I set up environment variables in React Native?

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.

Why do we need a dedicated environment package for React Native?

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.

What is the scope of global variables in React Native?

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.

How to build a react native app for Android?

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.


1 Answers

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.

like image 96
Mike Grabowski Avatar answered Oct 18 '22 17:10

Mike Grabowski