最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 16

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.

发布评论

评论列表(0)

  1. 暂无评论