I figured out some trickiness that I had with es6 imports being transpiled with babel.
The issue is that if you have some code that looks like this...
import dotenv from 'dotenv';
dotenv.load();
import foo from 'foo'; // this file reads from process.env
babel will transpile it to something equivalent to
var dotenv = require('dotenv');
var foo = require('foo');
dotenv.load();
_(note: the above is what the transpiled code would be functionally equivalent to.
If you want to see babels exact output you can look here)_
As you can see, babel is moving up all the imports. This is because the es6 modules spec requires that all imports are loaded depth first before executing the module body.
The issue is that foo.js ends up getting required before dotenv.load() is called, so it won't process.env populated.
A solution (similiar to what was suggested in https://github.com/motdotla/dotenv/issues/89) is to change the code to look like
import 'dotenv/config';
import foo from 'foo'; // this file reads from process.env
What that does is import this file which essentially calls dotenv.config() as a side effect. This way by the time the 'foo' is imported dotenv has already loaded.
The only downside of this solution is that it will try to parse argv (which is not necessary). The way to work around that would be to add a load.js file in the root of the project that would just contain
require('./lib/main').load()
You would then be able to do something like this in es6
import 'dotenv/load';
import foo from 'foo'; // this file reads from process.env
Let me know if you're ok with adding a load.js and I'll open a PR to add the files and update the example.
Thanks! :smile:
This is an issue with babel transpiling and not with ES6. For newer projects, preloading is a better way to go since load order is guaranteed, you need less code, and have more freedom for deployment in different environments (not tied to flat file)
I'm not sure if i'm fully convinced to use preloading over import 'dotenv/config'; :smile:
In any case I just wanted to document this here in case anyone was bumping into the same issue I was.
And once I have an open issue I'd also like to thank you guys for putting out an awesome project :+1:
Could clear instructions on this go into the readme?
This is an issue with babel transpiling and not with ES6. For newer projects, preloading
I'm running into this issue with ts-node but the link to preloading is broken. Is there a modern solution for importing that loads variables with ts-node?
Most helpful comment
I'm not sure if i'm fully convinced to use preloading over
import 'dotenv/config';:smile:In any case I just wanted to document this here in case anyone was bumping into the same issue I was.
And once I have an open issue I'd also like to thank you guys for putting out an awesome project :+1: