“process” is not defined 💻

A Webpack v4 ➡️ v5 problem

“process” is not defined 💻

Recently I’ve tried to upgrade Webpack from v4 to v5. There is a little breaking change that causes problems on frontend projects.
If you are using “process.env” variables it won’t work anymore. I was using the dotenv-webpack package but it doesn’t work anymore for browsers.

We automatically replace any remaining process.envs in these environments with “MISSING_ENV_VAR” to avoid these errors.

💡 The solution

  1. Install the dotenv package.
  2. Create a .env file with your environment-specific variables.
  3. Add this snippet at the start of Webpack config file:
var dotenv = require("dotenv").config({ path: __dirname + "/.env" });
  1. Add this snippet in the plugins section of your Webpack config file:
 plugins: [
    new webpack.DefinePlugin({
      "process.env.DOTENV": JSON.stringify(dotenv.parsed),
    }),
  ],

As the documentation says:

The DefinePlugin allows you to create global constants which can be configured at compile time.
DefinePlugin | webpack

So this will inject the variables in the code.

🤾 Usage

To use your new global constant in your code you can do this:

process.env.DOTENV.YOUR_VALUE

because the DOTENV parameter is an object containing the values in your .env file.

👵 Tips


I hope I’ve spared you some time!

Thanks for reading this article. 🎉

If you liked it, share it. If you didn't like it, tell me why. Always happy to discuss.

See you next time! 👋🏻


Photo by  Reinis Birznieks  on  Unsplash