Reputation: 9915
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:
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.
Upvotes: 39
Views: 80405
Reputation: 21
If you are not using create-react-app and you use webpack
Install npm install dotenv-webpack --save-dev
And then configure your webpack config file this way
const Dotenv = require('dotenv-webpack');
module.exports = {
// other webpack config options
plugins: [
new Dotenv() //<---
]
};
Note: Be sure you have your .env or .env.development in rhe root of your project, and that your environment variables begin with REACT_APP_. Example
REACT_APP_API_URL=https://example.com/api
Hope this help someone!
Upvotes: 0
Reputation: 305
This is the simplest way:
new webpack.EnvironmentPlugin( { ...process.env } )
Add that to your list of webpack plugins.
Upvotes: 9
Reputation: 36408
In your webpack config, there are two options that can affect process.env
:
config.target
(see config.target
)process.env
variable via DefinePlugin
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.
Upvotes: 32