zetachang / react-native-dotenv

A Babel preset let you import application configs from .env file (zero runtime dependency)
MIT License
915 stars 68 forks source link

Using .env variables in android/MainApplication.java file? #51

Closed ATypescriptEnjoyer closed 5 years ago

ATypescriptEnjoyer commented 5 years ago

Hi,

Is there any detailed way of using the .env file and building it into either the BuildConfig.java or using the files directly in a different way? Any help is appreciated :)

ATypescriptEnjoyer commented 5 years ago

Used this instead: https://github.com/luggit/react-native-config

brendonhc commented 4 years ago

Used this instead: https://github.com/luggit/react-native-config

Thanks! This library is perfect for that! Before I was using the react-native-dotenv to import my .env file inside my js code, but, now I need that my MainApplication.java code import the .env file too and I Can't do this with react-native-dotenv lib.

My solution was to use both libs, react-native-dotenv to my JS code, and react-native-config to java code (native).

For any who would find the solution is easy:

  1. First install the react-native-library:
yarn add react-native-config
react-native link react-native-config
  1. PRINCIPAL STEP: Add inside your MainApplication.java file this code where you need to use the environment var:

    // example, here I added the code inside onCreate() method of my MainApplication class
    public void onCreate() {
    String VAR_WITH_ANY_NAME = BuildConfig.ANY_ENV_VAR_AS_YOU_WANT;
    // ... any code ...
    }
  2. Now, rebuild your project (I like to do it in different terminals, one for the bundle and another for build)

    • Init your js bundle
      yarn && yarn start --reset-cache
    • recompile your native project
      yarn run android

I recommend to read react-native-config README.md with most updated doc: https://github.com/luggit/react-native-config#native-usage