I'm adding those environment variables to my bundle using Dotenv
and DefinePlugin()
.
webpack.config.js
new Dotenv(),
new webpack.DefinePlugin({
"process.env.TEST_ENV": JSON.stringify("xxx")
}),
Dotenv
loads a .env
file with a bunch of environment variables. It's all working fine.
Webpack also injects by default NODE_ENV
based on the mode
you set in the webpack.config.js
.
This is working fine and I'm able to read both NODE_ENV
and TEST_ENV
from my compiled and bundled code.
index.js
const { NODE_ENV, TEST_ENV } = process.env;
console.log(`process.env: ${JSON.stringify(process.env)}`);
console.log(`NODE_ENV: ${JSON.stringify(NODE_ENV)}`);
console.log(`TEST_ENV: ${JSON.stringify(TEST_ENV)}`);
I can successfully access and log both variables NODE_ENV
and TEST_ENV
from the process.env
object, as you can see from the image above.
But when I try to log process.env
itself, it logs an empty object {}
, as you can also see from the picture.
Why is that? Why can't I log process.env
just like I did with its properties NODE_ENV
and TEST_ENV
?
From: https://webpack.js.org/plugins/define-plugin/
Given the fact that DefinePlugin
does a direct replacement on your code, when you do this:
webpack.config.js
new webpack.DefinePlugin({
"process.env.SOME_VARIABLE": JSON.stringify("SOME_VALUE")
});
And you call it in your code like this:
index.js
const SOME_VARIABLE = process.env.SOME_VARIABLE;
Webpack will transpile it as:
const SOME_VARIABLE = "SOME_VALUE"
It completely replaces the process.env.SOME_VARIABLE
for the string "SOME_VALUE"
. That's also why you need the JSON.stringify("SOME_VALUE")
call. Because otherwise you would get const SOME_VARIABLE = SOME_VALUE
, without the string quotes, and you'll get the SOME_VALUE is not defined
error.
That's why you can't log or destructure process.env
in your bundled code.
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.