-
-
Notifications
You must be signed in to change notification settings - Fork 861
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Importing dotenv in ES6 #89
Comments
@jcblw you've done some work with ES6 right? |
@Sparragus can you provide a little more code so we can try to reproduce? I've added some examples of how to use dotenv in various ways in #90 including ES6 preloading. Are you using babel or something else for your I would caution against using |
I believe since we are not exporting out a key for import dotenv from 'dotenv'
dotenv.config() 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? |
@maxbeatty and @jcblw I've uploaded a repo with sample code showing everything I mentioned on my first message. All examples use Clone it and then make sure you also pull all the branches. Here's a one-liner to do that. Each branch has a README.md with details about that particular branch. Make sure to check it out. Start by trying out the Then try the other two branches: Let me know how it goes. |
This is an issue with using |
@maxbeatty I agree with you. I didn't know about Thanks all for your comments. |
On newer version of babel (v6.x?), this is what worked for me:
I've also found that this way (manually importing |
…red in a file not commited to repo. Note nodemon is being run with node instead of babel-node because dotenv can be passed a required module from command line using node's -r flag which is highjacked by babel-node, Therefore server/index.js is back to using babel-node inline.
Just a small note for those want to develop on Windows: you should remove quotes around the module names: node --require dotenv/config --require babel-register index.js
nodemon index.js --exec "node --require dotenv/config --require babel-register" Using this in {
// ...
"scripts": {
// ...
"start": "nodemon src/ --exec \"node --require dotenv/config --require babel-register\"",
"start:prod": "babel-node --require dotenv/config --require babel-register src/"
}
// ...
} |
@Sparragus Thanks a lot. I was getting undefined on my dotenv config and changing it to |
I have the following lines on the
I've added Thanks @Sparragus. |
You should follow this step as also mentioned in dotenv documentation. it is working fine in all the files.
|
For anyone using Babel - this saved me: https://www.npmjs.com/package/babel-plugin-dotenv |
@uds214125 Your method works fine for me. But I didn't have to preload the 'dotenv/config' on my script. |
@slorenzo Since I had the same weird behaviour as you, I found out it's because, as it has been quoted above :
It means that the imports are executed first, so executes When you put To summarize : |
does this not work for you? import 'dotenv/config` |
good job the best way to import, I don't know why on the top import to a variable! |
Because this does not work in node v12.10.0 (node:19322) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/default_resolve.js:79
let url = moduleWrapResolve(specifier, parentURL);
^
Error: Cannot find module /home/anders/dev/kaboom/node_modules/dotenv/config imported from /home/anders/dev/myfamily-api/src/index.mjs
at Loader.resolve [as _resolve] (internal/modules/esm/default_resolve.js:79:13)
at Loader.resolve (internal/modules/esm/loader.js:73:33)
at Loader.getModuleJob (internal/modules/esm/loader.js:152:40)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:43:40)
at link (internal/modules/esm/module_job.js:42:36) {
code: 'ERR_MODULE_NOT_FOUND'
} |
|
Just in case anyone is using esm to get es module syntax, then you can combine it with dotenv like so:
This preloads your dotenv values and ensures that your references to them in your es modules will work properly. |
|
The result of this is the env variables inside a parsed parent object, why is this? IE if I console.log(config()) I get:
|
I made a project, to show how it worked for me. https://github.com/AntonioGomes42/DotEnv-with-ES6-COMMOM-JS- . It was the only way i could find to make dotenv work with '.env' file an so. I hope it could help someone! |
import dotenv from "dotenv" |
@MackKaputo This has the same problem as explained above unless you put it into a separate module only for this purpose and then import that module at the top of your main module. |
It is worked |
Hi everyone. We've updated the docs to clarify this for ESM. It is right at the top fold now: |
import dotenv from 'dotenv'; dotenv.config({path: 'config.env'}); |
works for node version v16.14.2 |
All these examples that work across files don't seem to show how to set the config, e.g a custom path. |
@alexcroox One thing that worked for me (but I don't know if it's completely correct) to get the path working was:
|
@alexcroox good point! Yes, @joeflan is correct here. I'll update the README to communicate that better. |
Path is default to ./root/. To add path to current directory (Dir), we need this code inside of the file that we want all variables to be imported
server.js and .env can should be in the same directory if you don't manipulate the You can reach the variables process.env.myvariable. Just be sure it works and print all variables: console.log(process.env) Thanks |
import { config } from 'dotenv' |
now sure why so much stress import {config} from 'dotenv" config() |
This will lead to surprises depending on how some modules import other modules, for the reasons I explained here: #89 (comment) |
@CherryDT , is this correct though? I just tested it and I get this output:
|
import 'dotenv/config'; |
You are right, I made a mistake while writing this post. Of course it works because I incorrectly wrote to use What I meant to write (and changed now accordingly) was to use |
Doesn't work for my case. I have import dotenv from "dotenv";
dotenv.config({
path: resolve(process.cwd(), ".env.local"),
});
import { env } from "./env" // <-- throws zod parse error content import z from "zod";
const configSchema = z.object({
NEXTAUTH_URL: z.string().url(),
});
export const env = configSchema.parse(process.env); The problem is because Any ideas how to solve this? |
That's exactly the scenario I explained why However, in your case you need to pass arguments to
import './setupDotEnv';
import { env } from "./env";
import dotenv from "dotenv";
dotenv.config({
path: resolve(process.cwd(), ".env.local"),
});
import z from "zod";
const configSchema = z.object({
NEXTAUTH_URL: z.string().url(),
});
export const env = configSchema.parse(process.env); |
import dotenv from 'dotenv' dotenv.config(); const app = express(); app.get('/', (req, res) => { Welcome to my aapp"); }) //port const port = process.env.PORT app.listen(port, () => { |
YOU SAVED ME THANKSSS |
for those coming across this we are starting to recommend using https://github.com/dotenvx/dotenvx
dotenvx will work the same whether you are running node, bun, deno, python, anything. |
read this, |
I tried every single code here but it always says "process is not defined" |
import dotenv from "dotenv"; |
Support 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:
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:
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?
The text was updated successfully, but these errors were encountered: