theAnubhav
theAnubhav

Reputation: 533

'process.env.NODE_ENV' replaced as a string or process object is available at runtime in create-react-app

Have seen code which does something of this sort,

if(process.env.NODE_ENV === 'development') {
        //some DEVELOPMENT mode operation 
 }

and on similar lines, process.env.NODE_ENV === 'production'. Now when we do npm run build, on create-react-app scaffolded app, does,

  1. process.env.NODE_ENV string is replaced (and becomes if('development' === 'development'), and which case dead code is removed? ) or,
  2. process object is available at runtime and when this code is executed it has this object with env object containing NODE_ENV property.

The process is important to know, because have seen people write down function like getENV which returns this value. If #1 happens this doesn't help to remove dead code.

Upvotes: 0

Views: 501

Answers (1)

PlayMa256
PlayMa256

Reputation: 6831

Process #1 is the one that happens. Everything works because of webpack DefinePlugin, which "translates" process.env to the correct value.

Now, the tricky thing here is: Webpack does the deadcode elimination (a.k.a Tree shaking) during the build time, which removes all the branches that are not needed.

Upvotes: 1

Related Questions