Why Upgrading to Webpack 5 Breaks process.env and How to Fix It
This article recounts a production white‑screen caused by missing node polyfills after upgrading to webpack 5, explains how the undefined process.env variables triggered the crash, and shows how to diagnose and resolve the issue using DefinePlugin or a polyfill plugin.
Friendly Reminder
The article focuses on the break‑change that webpack 5 no longer includes nodejs polyfills after upgrading from webpack 4. If you already know this, you can skip reading unless you want to skim.
Encounter
It started on a Thursday evening when a colleague reported a white screen in production. The upgrade to
[email protected]seemed stable, but the devtool showed
Uncaught ReferenceError: process is not defined.
Discovering Anomaly
Rolling back the release removed the error, indicating the issue only appears in the production build. The problematic line was:
<code>// Application entry page
XXX.init({
...,
environment: process.env.PUBLISH_ENV,
});
</code>The
process.env.PUBLISH_ENVvariable was undefined, causing the crash.
Further inspection revealed the code is guarded by:
<code>if (process.env.GM_BUILD_ENV === 'prod') {
// ...
XXX.init({
...,
environment: process.env.PUBLISH_ENV,
});
// ...
}
</code>Thus the logic only runs in production.
process.env.PUBLISH_ENVis missing, leading to the crash.
process.env.GM_BUILD_ENV === 'prod'ensures only production hits the code.
Rolling back to
masterworks, so the bug originates from the feature branch.
Approaching the Truth
Inspecting the webpack
DefinePluginconfiguration showed no definition for
PUBLISH_ENV. The variable had never existed in the repository for at least six months.
Two possibilities: either
process.env.PUBLISH_ENVhas always been undefined, or the recent upgrade removed it.
Testing on
masterprinted
undefinedwithout crashing, suggesting a polyfill added
processin the old build.
Searching the codebase revealed a file that defines
processas a polyfill. Removing that definition reproduces the error.
Encounter Again
Comparing branches showed the
package.jsonwebpack version changed from 4 to 5, introducing the break‑change: webpack 5 no longer bundles nodejs polyfills.
Webpack 4 automatically provided
process, but the new branch lacked a proper
DefinePluginentry for
PUBLISH_ENV, causing the production build to fail.
The fix is either to add the missing definition via
DefinePluginor to use
node-polyfill-webpack-pluginto re‑introduce the polyfills.
That concludes the investigation; you can now finish your day.
Goodme Frontend Team
Regularly sharing the team's insights and expertise in the frontend field
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.