Pushkin
Pushkin

Reputation: 3604

How to exclude / disable React Developer Tools in Production build?

As its name suggests developer tools should be visible or accessible only during development and not in production. I don't want my end users seeing the state and component tree, thus knowing what's going on under the hood. Although React Developer Tool in Production neither allows modification of the components' state nor does it reveal their names, it doesn't fully hide them or disable the tools altogether. End Users can still see each component's state and the whole app tree.

Is there a way to exclude / disable React Developer tools or disconnect it in the production build, like how Augury does for Angular?

Upvotes: 4

Views: 8264

Answers (1)

Pushkin
Pushkin

Reputation: 3604

While I was searching the internet for answers while this question is still in draft, I found this one. But sadly this didn't work. It did however tell me that it has something to do with __REACT_DEVTOOLS_GLOBAL_HOOK__.

So After playing with it and modifying it, it worked. It successfully disconnected the App from React Developer Tools.

Here is the code to disconnect the App from React Developer Tools.

// disableReactDevTools.ts

// Declare the types if you're using TypeScript
// Ignore this block if you're using JavaScript
declare global {
  interface Window {
    __REACT_DEVTOOLS_GLOBAL_HOOK__: any;
  }
}

export function disableReactDevTools() {
  // Check if the React Developer Tools global hook exists
  if (typeof window.__REACT_DEVTOOLS_GLOBAL_HOOK__ !== "object") {
    return;
  }

  for (const prop in window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
    if (prop === "renderers") {
      // initialise this with an empty `Map`,
      // else it will throw an error in console

      window.__REACT_DEVTOOLS_GLOBAL_HOOK__[prop] = new Map()
    } else {
      // Replace all of its properties with a no-op function or a null value
      // depending on their types

      window.__REACT_DEVTOOLS_GLOBAL_HOOK__[prop] =
        typeof window.__REACT_DEVTOOLS_GLOBAL_HOOK__[prop] === "function"
          ? () => {}
          : null;
    }
  }
}
// index.tsx
import React from "react";
import ReactDOM from "react-dom";

// ...

if (process.env.NODE_ENV === "production") disableReactDevTools();
// ...

This code will not throw any error or warnings in the console.

Upvotes: 10

Related Questions