React + node project, got my .env file in root (along with all other root files like .eslint, .gitignore), it contains 6 lines like APIKEY=aeofiunoief
, no other special symbols.
In src/
I have index.js
which does normal imports (like React, ReactDOM), then //eslint-disable import/first
, then require('dotenv').load()
. According to everything I've seen this should load my variables into process.env
, but when I check console.log, I don't see anything but NODE_ENV
and PUBLIC_URL
.
It's really confusing...
Your file structure:
src
index.js
...
.env
...
Do:
require('dotenv').config({ path: '../.env' });
console.log(process.env);
From dotenv GitHub:
You can specify a custom path if your file containing environment variables is named or located differently.
require('dotenv').config({path: '/custom/path/to/your/env/vars'})
In my case, I was using the Dotenv webpack plugin and I was pointing to the wrong file path:
plugins: [
htmlWebpackPlugin,
new Dotenv({
path: path.resolve(__dirname, .., '.env')
})
],
For my structure, path: path.resolve(__dirname, '.env')
was the right configuration that worked. As long as you are pointing to the right .env
within your system, you should be good.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.