5
我正在为ReactJS编写Mixin。我希望它做一些验证,但只有在development mode中使用ReactJS时。如何判断ReactJS是否处于JavaScript开发模式?
如何从JavaScript确定ReactJS是处于开发还是生产模式?
我正在为ReactJS编写Mixin。我希望它做一些验证,但只有在development mode中使用ReactJS时。如何判断ReactJS是否处于JavaScript开发模式?
如何从JavaScript确定ReactJS是处于开发还是生产模式?
ReactJS源使用一个名为__DEV__
的变量来跟踪这个变量,但它没有被导出,所以它对你的Mixin不可用。但是,其后果是,例如,当你破坏一个不变量时,开发模式ReactJS会给你一个很好的描述错误的描述。在生产模式下,它会给出一个通用错误,告诉您使用dev版本。
我们可以用它来构建其确定反应的功能在开发模式:
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"
“渲染”这个词是特定于我们违反的不变量,所以它只在dev版本的异常中出现。
您可以使用webpack设置'__DEV__'变量。 – 2014-09-19 17:35:43
如果您正在编写Mixin,您可能不希望强制用户自己重建ReactJS。 – danvk 2014-09-19 17:38:39