简体   繁体   English

在运行时可在create-react-app中将“ process.env.NODE_ENV”替换为字符串或过程对象

[英]'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'. 在类似的行上,process.env.NODE_ENV ==='生产'。 Now when we do npm run build , on create-react-app scaffolded app, does, 现在,当我们执行npm run build在create-react-app支架式应用程序上的npm run build

  1. process.env.NODE_ENV string is replaced (and becomes if('development' === 'development') , and which case dead code is removed? ) or, process.env.NODE_ENV字符串被替换(并变成if('development' === 'development') ,并且在哪种情况下删除了无效代码?)或,
  2. process object is available at runtime and when this code is executed it has this object with env object containing NODE_ENV property. process对象在运行时可用,执行此代码时,该对象具有包含NODE_ENV属性的env对象。

The process is important to know, because have seen people write down function like getENV which returns this value. 知道这一过程很重要,因为已经看到人们写下了诸如getENV类的getENV ,该函数会返回该值。 If #1 happens this doesn't help to remove dead code. 如果发生#1,这无助于删除无效代码。

Process #1 is the one that happens. 进程#1是发生的过程。 Everything works because of webpack DefinePlugin , which "translates" process.env to the correct value. 一切都因webpack DefinePluginDefinePlugin ,它可以将process.env“转换”为正确的值。

Now, the tricky thing here is: Webpack does the deadcode elimination (aka Tree shaking) during the build time, which removes all the branches that are not needed. 现在,这里棘手的事情是:Webpack在构建期间消除了死代码(也称为树抖动),这删除了所有不需要的分支。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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