如何在生产环境中排除/禁用React开发者工具?

4
正如它的名称所示,开发者工具应该只在开发期间可见或可访问,而不应在生产环境中出现。我不想让我的终端用户看到状态和组件树,从而了解底层情况。虽然React开发者工具在生产环境中既不允许修改组件状态,也不会显示其名称,但它并没有完全隐藏这些信息或禁用这些工具。最终用户仍然可以看到每个组件的状态和整个应用程序树。
是否有一种方法可以在生产构建中排除/禁用React开发者工具或断开连接,就像Augury对Angular所做的那样?
1个回答

9
当我在草稿状态下搜索互联网寻找答案时,我发现了这篇文章。但可悲的是它并没有奏效。然而,它告诉我这与__REACT_DEVTOOLS_GLOBAL_HOOK__有关。
因此,在对其进行修改和尝试后,它起作用了。它成功地将应用程序与React开发人员工具断开连接。
以下是断开与React开发人员工具连接的代码。
// 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();
// ...

这段代码不会在控制台中抛出任何错误或警告。


有没有用JS的方法?我还不知道TS。 - Salah Eddine Makdour
2
只需删除那个 declare global,它就可以在JS中正常工作。 - Pushkin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接