繁体   English   中英

如何判断ReactJS是否处于JavaScript开发模式?

[英]How can I tell whether ReactJS is in development mode from JavaScript?

我正在为ReactJS写一个Mixin 我希望它做一些验证,但只有在开发模式下使用ReactJS时。

如何从JavaScript确定ReactJS是处于开发模式还是生产模式?

ReactJS源使用一个名为__DEV__的变量来跟踪它,但它没有被导出,所以它对你的Mixin不可用。

然而,其后果是。 当你打破一个不变量时,例如,dev模式ReactJS会给你一个很好的错误描述。 在生产模式下,它会给出一个通用错误,告诉您使用开发版本。

我们可以使用它来构建一个函数来确定React是否处于开发模式:

function isDevReact() {
  try {
    React.createClass({});
  } catch(e) {
    if (e.message.indexOf('render') >= 0) {
      return true;  // A nice, specific error message
    } else {
      return false;  // A generic error message
    }
  }
  return false;  // should never happen, but play it safe.
};

这是有效的,因为在两种模式下,不实现render方法的异常是不同的:

Development: "Invariant Violation: createClass(...): Class specification must implement a `render` method. Inline JSX script:16"
Production:  "Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings. Inline JSX script:16"

单词“render”特定于我们违反的不变量,因此它只显示在dev版本的异常中。

暂无
暂无

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

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