Detecting production vs. development React at runtime

JavascriptReactjs

Javascript Problem Overview


Is it possible to detect whether the current version of React is development or production at runtime? I'd like to do something like this:

if (React.isDevelopment) {
  // Development thing
} else {
  // Real thing
}

Javascript Solutions


Solution 1 - Javascript

This is best done emulating the Node way of doing things with your build tool - webpack, browserify - by exposing process.env.NODE_ENV. Typically, you'll have it set to "production" in prod and "development" (or undefined) in dev.

So your code becomes:

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
    // dev code
} else {
    // production code
}

For how to set it up, see envify or Passing environment-dependent variables in webpack

Solution 2 - Javascript

I use a helper file (in Typescript):

import process from "process";

const development: boolean = !process.env.NODE_ENV || process.env.NODE_ENV === 'development';

export default function isDev(): boolean
{
    return development;
}

Then elsewhere I use it like this:

import isDev from "./helpers/DevDetect";

if (isDev())
{
    ...
}

Solution 3 - Javascript

I wanted access to this from the index.html and desired a solution which didn't involve ejecting webpack or configuring it with additional modules and I came up with this.

Sources are David's answer above and the create-react-app documentation for using environment variables in the html file

if ( ! '%NODE_ENV%' || '%NODE_ENV%' === 'development') {
  // dev code
} else {
  // production code    
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpfhayesView Question on Stackoverflow
Solution 1 - JavascriptDavid L. WalshView Answer on Stackoverflow
Solution 2 - JavascriptJamesView Answer on Stackoverflow
Solution 3 - JavascriptMax CarrollView Answer on Stackoverflow