Javascript React + webpack:'process.env' 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29096018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:50:55  来源:igfitidea点击:

React + webpack: 'process.env' is undefined

javascriptreactjswebpack

提问by Henrik

I'm trying to run the hot dev server on our site with webpack; the site uses ReactJS, which has this code in it:

我正在尝试使用 webpack 在我们的站点上运行热开发服务器;该站点使用 ReactJS,其中包含以下代码:

if (\"production\" !== process.env.NODE_ENV) // etc

When not running hot-swap it's fine, but with the hot-swap, it gets run, resulting in the error:

不运行热插拔时很好,但是使用热插拔时,它会运行,从而导致错误:

TypeError: process.env is undefined

The code looks like this:

代码如下所示:

error is on this line

错误在这一行

The project is modelled after https://github.com/webpack/react-starterwhich doeswork; so the question is; what error have I made in the config file and/or how do I go about looking for the error when the 'production' compilation works just fine?

该项目以https://github.com/webpack/react-starter为模型,它确实有效;所以问题是;我在配置文件中犯了什么错误和/或当“生产”编译工作正常时我如何去寻找错误?

I've posted the gist of the webpack config file.

我已经发布了webpack 配置文件要点

采纳答案by Alexandre Kirszenberg

In your webpack config, there are two options that can affect process.env:

在你的 webpack 配置中,有两个选项会影响process.env

Looking at your code, it looks like process.envmight be undefined when both options.prerenderand options.minimizeare false.

查看您的代码,process.envoptions.prerenderoptions.minimize都是时,它看起来可能未定义false

You could fix this by always using an environment that defines process.env(ex: node), or by using DefinePluginto assign a default value to the variable yourself.

您可以通过始终使用定义process.env(例如:)的环境node或使用DefinePlugin自己为变量分配默认值来解决此问题。

回答by Matt

This is the simplest way:

这是最简单的方法:

new webpack.EnvironmentPlugin( { ...process.env } )

Add that to your list of webpack plugins.

将其添加到您的 webpack 插件列表中。

回答by Grant Eagon

This answer made more sense to me. Posting for others with the same need for a complete example.

这个答案对我来说更有意义。为具有相同需求的其他人发布完整示例。

https://github.com/webpack/webpack/issues/868

https://github.com/webpack/webpack/issues/868