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
React + webpack: 'process.env' is undefined
提问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:
代码如下所示:


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:
- When you specify
config.target(seeconfig.target) - When you define the
process.envvariable viaDefinePlugin
Looking at your code, it looks like process.envmight be undefined when both options.prerenderand options.minimizeare false.
查看您的代码,process.env当options.prerender和options.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.
这个答案对我来说更有意义。为具有相同需求的其他人发布完整示例。

