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?
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?
Share Improve this question edited May 23, 2017 at 12:10 CommunityBot 11 silver badge asked Sep 18, 2014 at 21:27 danvkdanvk 17k8 gold badges78 silver badges131 bronze badges 2-
You can set
__DEV__
variable with webpack.. – Konstantin Tarkus Commented Sep 19, 2014 at 17:35 - If you're writing a Mixin, you probably don't want to force users to rebuild ReactJS themselves. – danvk Commented Sep 19, 2014 at 17:38
1 Answer
Reset to default 16The 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.