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-starter which does work; 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配置文件的要点。
3 个解决方案
#1
29
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.env
variable viaDefinePlugin
指定config.target时(请参阅config.target)
通过DefinePlugin定义process.env变量时
Looking at your code, it looks like process.env
might be undefined when both options.prerender
and options.minimize
are false
.
查看代码,当options.prerender和options.minimize都为false时,看起来process.env可能是未定义的。
You could fix this by always using an environment that defines process.env
(ex: node
), or by using DefinePlugin
to assign a default value to the variable yourself.
您可以通过始终使用定义process.env(例如:node)的环境或使用DefinePlugin自行为变量分配默认值来解决此问题。
#2
6
This answer made more sense to me. Posting for others with the same need for a complete example.
这个答案对我来说更有意义。发布其他人需要一个完整的例子。
#3
4
This is the simplest way:
这是最简单的方法:
new webpack.EnvironmentPlugin( { ...process.env } )
Add that to your list of webpack plugins.
将其添加到您的webpack插件列表中。
#1
29
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.env
variable viaDefinePlugin
指定config.target时(请参阅config.target)
通过DefinePlugin定义process.env变量时
Looking at your code, it looks like process.env
might be undefined when both options.prerender
and options.minimize
are false
.
查看代码,当options.prerender和options.minimize都为false时,看起来process.env可能是未定义的。
You could fix this by always using an environment that defines process.env
(ex: node
), or by using DefinePlugin
to assign a default value to the variable yourself.
您可以通过始终使用定义process.env(例如:node)的环境或使用DefinePlugin自行为变量分配默认值来解决此问题。
#2
6
This answer made more sense to me. Posting for others with the same need for a complete example.
这个答案对我来说更有意义。发布其他人需要一个完整的例子。
#3
4
This is the simplest way:
这是最简单的方法:
new webpack.EnvironmentPlugin( { ...process.env } )
Add that to your list of webpack plugins.
将其添加到您的webpack插件列表中。