简体   繁体   中英

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

I'm writing a Mixin for ReactJS. I'd like it to do some validation, but only when ReactJS is being used in development mode .

How can I determine from JavaScript whether ReactJS is in development or production mode?

The ReactJS source uses a variable called __DEV__ to track this, but it's not exported, so it's unavailable to your 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. 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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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