Importing dotenv in ES6
See original GitHub issueSupport on ES6 has been tricky for me. Yesterday I tried preloading dotenv with iojs -r dotenv/config index.js
. However, it didn’t work and I couldn’t understand why. My app did nothing. After running the app, a second or two later it would finish without doing anything.
I ended up with a very simple way to use dotenv. I simply import it like this:
import {} from 'dotenv/config'
import somethingElse from 'somethingElse'
...
[the rest of your code]
This works because of how ES6 modules imports modules. Before doing anything else in a file (say index.js) it does all the imports first. It does a depth first traversal of these imports, executing any code inside it. If we import dotenv first, it will execute config and add any env variables before doing anything else in the code.
From ES6 In Depth: Modules:
When you run a module containing an import declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.
So, importing dotenv on the first line of a bootstrap file in an app will set the env vars for anything that might use them.
I suggest we add a brief section about importing dotenv with ES6 modules to the README. But before sending a pull request and wanted to open it up for discussion here.
Any thoughts?
Issue Analytics
- State:
- Created 8 years ago
- Reactions:146
- Comments:47 (5 by maintainers)
I believe since we are not exporting out a key for
dotenv
the default import behavior ofbabel
@maxbeatty mentions should work.I would also be interested in how your running into an issue with preloading the module. Can you post the version of node/iojs and dotenv that you are using?
@jcblw you’ve done some work with ES6 right?