[英]How can I tell whether ReactJS is in development mode from JavaScript?
I'm writing a Mixin for ReactJS. 我正在为ReactJS写一个Mixin 。 I'd like it to do some validation, but only when ReactJS is being used in development mode . 我希望它做一些验证,但只有在开发模式下使用ReactJS时。
How can I determine from JavaScript whether ReactJS is in development or production mode? 如何从JavaScript确定ReactJS是处于开发模式还是生产模式?
The ReactJS source uses a variable called __DEV__
to track this, but it's not exported, so it's unavailable to your Mixin. ReactJS源使用一个名为__DEV__
的变量来跟踪它,但它没有被导出,所以它对你的Mixin不可用。
Its consequences are, however. 然而,其后果是。 When you break an invariant, for example, dev mode ReactJS will give you a nice description of what went wrong. 当你打破一个不变量时,例如,dev模式ReactJS会给你一个很好的错误描述。 In production mode, it will give a generic error telling you to use the dev version. 在生产模式下,它会给出一个通用错误,告诉您使用开发版本。
We can use this to build a function which determines if React is in dev mode: 我们可以使用它来构建一个函数来确定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.
};
This works because the exception for not implementing a render
method is different in the two modes: 这是有效的,因为在两种模式下,不实现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"
The word "render" is specific to the invariant we violated, so it only shows up in the dev version's exception. 单词“render”特定于我们违反的不变量,因此它只显示在dev版本的异常中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.