How do I know if ReactJS works in development mode with JavaScript?

I am writing Mixin for ReactJS. I would like it to do some validation, but only when ReactJS is used in development mode .

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

+5
source share
1 answer

The ReactJS source uses the __DEV__ variable to track this, but it is not exported, so it is not available for your Mixin.

Its consequences, however. For example, when you break an invariant, dev mode ReactJS will give you a good description of what went wrong. In production mode, it will give a general error telling you to use the dev version.

We can use this to build a function that determines whether 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 the render method differs in 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" refers to the invariant that we violated, so it appears only in the exception version.

+10
source

Source: https://habr.com/ru/post/1202914/


All Articles