在运行时检测生产与开发 React [英] Detecting production vs. development React at runtime

查看:41
本文介绍了在运行时检测生产与开发 React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时检测当前版本的 React 是开发版还是生产版?我想做这样的事情:

Is it possible to detect whether the current version of React is development or production at runtime? I'd like to do something like this:

if (React.isDevelopment) {
  // Development thing
} else {
  // Real thing
}

推荐答案

最好通过暴露 process.env.NODE_ENV.通常,您将在 prod 中将其设置为production",在 dev 中将其设置为development"(或未定义).

This is best done emulating the Node way of doing things with your build tool - webpack, browserify - by exposing process.env.NODE_ENV. Typically, you'll have it set to "production" in prod and "development" (or undefined) in dev.

所以你的代码变成:

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
    // dev code
} else {
    // production code
}

有关如何设置,请参阅envify在webpack中传递环境相关变量

For how to set it up, see envify or Passing environment-dependent variables in webpack

这篇关于在运行时检测生产与开发 React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆