'process.env throws Uncaught ReferenceError but process.env.NODE_ENV does not

In my client-side javascript file if I run the following I get no error:

console.log(process.env.NODE_ENV); // outputs development or production

But if I run the following then I get an error:

console.log(process.env) // Uncaught ReferenceError: process is not defined

Why is this happening? Using Webpack 5 for bundling.



Solution 1:[1]

Because you're using a bundler that replaces process.env.NODE_ENV with another value. For Webpack, it's DefinePlugin doing the dirty work (and setting the Webpack --mode option automatically adds the plugin); for e.g. esbuild it's define.

Your resulting bundled JavaScript will not have process.env.NODE_ENV at all, just a static string "production" or "development". However, just process.env will not be replaced (unless configured so), so you're getting a reference error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1