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
- Install the dotenv package.
- Create a
.env
file with your environment-specific variables. - Add this snippet at the start of Webpack config file:
var dotenv = require(“dotenv”).config({ path: __dirname + “/.env” });
- 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
- Check if not “undefined”
- Follow the migration guide To v5 from v4 | webpack