Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting production vs. development React at runtime

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 } 
like image 911
pfhayes Avatar asked Feb 17 '16 23:02

pfhayes


People also ask

What is process ENV Node_env in React?

To identify which environment we are in, we can make use of a special environment variable: process. env. NODE_ENV . When you are using Create React App, the react-scripts will set the value of NODE_ENV to development when npm start is executed and to production when you run npm run build .

What makes Reactjs performance faster?

To optimize React rendering, you need to make sure that components receive only necessary props. It will let you control the CPU consumption and avoid over-rendering unnecessary features. The solution is to create a functional component that will collect all props and redistribute them to other components.


2 Answers

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

like image 57
David L. Walsh Avatar answered Sep 18 '22 12:09

David L. Walsh


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()) {     ... } 
like image 44
James Avatar answered Sep 17 '22 12:09

James