顾名思义,开发人员工具应仅在development期间可见或可访问,而不能在production中使用。我不希望我的最终用户看到状态和组件树,从而知道幕后情况。尽管生产中的React Developer Tool既不允许修改组件的状态,也不能透露组件的名称,但是它并不能完全隐藏组件或完全禁用工具。最终用户仍然可以看到每个组件的状态和整个应用程序树。
有没有一种方法可以在生产版本中排除/禁用React Developer工具或断开其连接,就像Augury对Angular的作用一样?
虽然当我还在互联网上寻找答案时,这个问题仍在草案中,但我发现了this。但是可悲的是这没有用。但是它确实告诉我,它与__REACT_DEVTOOLS_GLOBAL_HOOK__
有关。
因此,在使用它并对其进行修改之后,它就可以了。它成功地将应用程序与React Developer Tools断开了连接。
这里是使应用程序与React Developer Tools断开连接的代码。
// 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();
// ...
此代码将在控制台中引发任何错误或警告。