[Solved] React + webpack: ‘process.env’ is undefined

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

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-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?

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

Enquirer: Henrik

||
Solution #1:

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

Looking at your code, it looks like process.env might be undefined when both options.prerender and options.minimize are false.

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.

Respondent: Henrik
Solution #2:

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

Solution #3:

This is the simplest way:

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

Add that to your list of webpack plugins.

Respondent: Grant Eagon
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.