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

Configure default if envvar is not present #10

Open j2kun opened 7 years ago

j2kun commented 7 years ago

Would it be possible to add a configuration value to the .babelrc that allows one to import variables that aren't present in any .env? This would allow one to specify sensible defaults for a project with many variables.

E.g., then I could do something like import { MY_VAR } from 'react-native-dotenv' followed by myconfig.MY_VAR = MY_VAR || 'default'

zetachang commented 7 years ago

Hi Jeremy, this looks like a useful feature. Would you mind providing some code example to demonstrate the use case?

Jeremy Kun notifications@github.com 於 2017年2月14日週二 上午8:19 寫道:

Would it be possible to add a configuration value to the .babelrc that allows one to import variables that aren't present in any .env? This would allow one to specify sensible defaults for a project with many variables.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/zetachang/react-native-dotenv/issues/10, or mute the thread https://github.com/notifications/unsubscribe-auth/AAzRJT416spPSRquqPEHIPzOQ7Qr23xzks5rcPMDgaJpZM4L_5j5 .

j2kun commented 7 years ago

Sure. The gist is that in an ideal setup, I can import react-native-dotenv and configure it even if there is no .env file present, or some of the config variables are not present in the .env file.

Example project setup:

.
├── App
│   ├── Settings.js   <--- Where react-native-dotenv is imported
│   └── ...
├── android
├── build
├── index.android.js
├── index.ios.js
├── ios
├── package.json
└── ...

In Settings.js

import dotenv from 'react-native-dotenv';

var API_URL = dotenv.API_URL || 'api.my-default-url.com';
var WWW_URL = dotenv.WWW_URL || 'my-default-web-url.biz';
var FONT = dotenv.FONT || 'Helvetica';
var NAVBAR_HEIGHT = dotenv.NAVBAR_HEIGHT || 64;
...

This way I can have hundreds of environment variables defined, each with a sensible default, and not require these values to be specified in every .env file for every developer. And from the settings file I can export all of these variables, or attach them to process.env, or whatever, as needed.

From my admittedly limited understanding of babel plugins, it appears this scheme would be possible as I wrote above, but it might not fit into the context of this project, seeing how you laid it out.

j2kun commented 7 years ago

I think, in general 12-factor app design does not assume the existence of an .env file at all, and I notice that your package raises exceptions even in the case that, say, .env exists but .env.development does not

jordanmkoncz commented 7 years ago

I would definitely use this functionality if it was added!