volume one
volume one

Reputation: 7563

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.

Upvotes: 1

Views: 1539

Answers (1)

AKX
AKX

Reputation: 169184

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.

Upvotes: 4

Related Questions