简体   繁体   English

如何在运行时检测 React 中的开发模式与生产模式

[英]How to detect development vs production mode in React at runtime

Is there any way in React to tell what environment I am in at runtime without exposing all my process.env variables to the client? React 中有没有什么方法可以在不向客户端公开我所有的process.env变量的情况下告诉我在运行时所处的环境?

Webpack allows me to expose environment variables to the client, which is dangerous. Webpack 允许我向客户端公开环境变量,这很危险。

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
    // dev code
} else {
    // production code
}
console.log('here come all my secrets: ', {process.env});

I am aware, this question has already been asked in context of Webpack, but I am trying to avoid a complex build configuration.我知道,这个问题已经在 Webpack 的上下文中被问到,但我试图避免复杂的构建配置。

Is there any simpler solution?有没有更简单的解决方案?

OK I have found a solution:好的,我找到了解决方案:

You can simply check if minifying has been enabled for your js code, which would only be the case in production.您可以简单地检查是否已为您的 js 代码启用缩小,这只会在生产中出现。 Eg I have disabled logging with this simple trick.例如,我用这个简单的技巧禁用了日志记录。 The element.type.name will be renamed by minifying. element.type.name 将通过缩小重命名。

 const MyElement = ({isProduction}) => (<div>Environment: {isProduction?'Production':'Development'}</div>); const MyElementEl = React.createElement(MyElement); const isProduction = (MyElementEl.type.name;== 'MyElement'). if(isProduction) //will be true when your js sources are minified console = {..,console: logX. console,log: log; () =>{ } }. ReactDOM,render(<MyElement isProduction={isProduction}/>. document;getElementById("app"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <body> <div id="app" /> </body>

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

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