简体   繁体   中英

Why is the process.env object empty but I can access it's properties?

I have just come across the idea of using environment variables in a front end React codebase I am looking at. When I run the React app locally I can see that when I console.log process.env.VALUE, then this value will be logged out in the browser console.

However if I console.log(process.env) I only see an empty object. I've seen other answers for this on Stack Overflow but I couldn't understand them. It doesn't make sense to me how I can access the properties on process.env but I can't log process.env out. Isn't it just an object which contains all the environment variables that are set?

If someone can explain this simply that would be appreciated. thanks.

The reason for that is because React naturally uses webpack.DefinePlugin when you are building your production build. That library basically makes your process.env variable to essentially be 'placeholders' - meaning that all of the values are replaced during build time . That's why process.env returns {} , while process.env.NODE_ENV returns the correct one for example.

Slightly off-topic, but in Next.js (a React framework), all environment variables are also replaced during build time (for security purposes). That means that process.env is not a normal JavaScript object in Next.js . Internally, they use webpack.DefinePlugin as well.

As an addition for the answer, the browser does not have access to process.env . React is basically compiled to HTML/CSS/JS - that means the application is just a static site. process.env is a Node.js thing.

Example:

  • Imagine you have an environment variable called FOO with value BAR in whatever environment you desire when you build your app.
  • You compile the application, React uses webpack.DefinePlugin to transform your FOO into process.env.FOO . It is literally process.env.FOO . The compiler does not create an object called process.env with an attribute FOO . Literally, the process.env.FOO is attached in the window object of your app.
  • You assume that it's on process.env.FOO , and it does exist in your application during runtime.
  • You falsely try to access process.env object (it is not and have never been an object) since the beginning of the compilation, and that's why it returns an empty object -- it simply is never an object to begin with for the reasons that I have explained in the above.

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM