簡體   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