简体   繁体   English

为什么我不能用 Webpack 在我的捆绑代码中记录 `process.env`?

[英]Why can't I log `process.env` in my bundled code with Webpack?

I'm adding those environment variables to my bundle using Dotenv and DefinePlugin() .我正在使用DotenvDefinePlugin()将这些环境变量添加到我的包中。

webpack.config.js 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. Dotenv加载一个带有一堆环境变量的.env文件。 It's all working fine.一切正常。

Webpack also injects by default NODE_ENV based on the mode you set in the webpack.config.js .默认情况下, NODE_ENV根据您在 webpack.config.js 中设置的mode注入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.这工作正常,我可以从我编译和捆绑的代码中读取NODE_ENVTEST_ENV

index.js 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.如上图所示,我可以从process.env object 成功访问并记录变量NODE_ENVTEST_ENV

But when I try to log process.env itself, it logs an empty object {} , as you can also see from the picture.但是当我尝试记录process.env本身时,它会记录一个空的 object {} ,您也可以从图片中看到。

Why is that?这是为什么? Why can't I log process.env just like I did with its properties NODE_ENV and TEST_ENV ?为什么我不能像使用它的属性NODE_ENVTEST_ENV那样记录process.env

From: https://webpack.js.org/plugins/define-plugin/来自: https://webpack.js.org/plugins/define-plugin/

在此处输入图像描述

Given the fact that DefinePlugin does a direct replacement on your code, when you do this:鉴于DefinePlugin直接替换您的代码,当您执行此操作时:

webpack.config.js 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 index.js

const SOME_VARIABLE = process.env.SOME_VARIABLE;

Webpack will transpile it as: Webpack 将其转译为:

const SOME_VARIABLE = "SOME_VALUE"

It completely replaces the process.env.SOME_VARIABLE for the string "SOME_VALUE" .它完全替换了字符串"SOME_VALUE"process.env.SOME_VARIABLE That's also why you need the JSON.stringify("SOME_VALUE") call.这也是您需要调用JSON.stringify("SOME_VALUE")的原因。 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.因为否则你会得到const SOME_VARIABLE = SOME_VALUE ,没有字符串引号,你会得到SOME_VALUE is not defined错误。

That's why you can't log or destructure process.env in your bundled code.这就是您不能在捆绑代码中记录或解构process.env的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM