简体   繁体   English

如何在生产版本中排除/禁用 React 开发人员工具?

[英]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.我不希望我的最终用户看到 state 和组件树,从而知道幕后发生了什么。 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.尽管 React Developer Tool in Production 既不允许修改组件的 state 也不允许显示它们的名称,但它并没有完全隐藏它们或完全禁用这些工具。 End Users can still see each component's state and the whole app tree.最终用户仍然可以看到每个组件的 state 和整个应用程序树。

Is there a way to exclude / disable React Developer tools or disconnect it in the production build, like how Augury does for Angular?有没有办法在生产构建中排除/禁用 React Developer 工具或断开它,就像 Augury 对 Angular 所做的那样?

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__ .但是它确实告诉我它与__REACT_DEVTOOLS_GLOBAL_HOOK__

So After playing with it and modifying it, it worked.所以在玩过它并修改它之后,它工作了。 It successfully disconnected the App from React Developer Tools.它成功地断开了应用程序与 React 开发者工具的连接。

Here is the code to disconnect the App from React Developer Tools.这是断开应用程序与 React 开发人员工具的代码。

// disableReactDevTools.ts

// Declare the types if you're using TypeScript
// Remove 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") {
      // this line will remove that one console error

      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 throw any error or warnings in the console.此代码将在控制台中引发任何错误或警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM