反应本机。一处转on/off控制台日志的机制

React Native. Mechanism for turning on/off console logs in one place

我的代码中有很多console.log。 我们知道这些日志会大大降低应用程序的速度,所以在开发结束时我需要删除所有这些日志,但当然我不记得我有它的所有地方。我如何使用我可以使用的 console.log 的包装器,以便我可以在一个地方打开或关闭所有控制台日志?如果我的方法不是很好,请告诉我一些库、工具、做我需要的方法...

您可以通过以下两种方式进行:

if(!__DEV__) {
  console = {};
  console.log = () => {};
  console.error = () => {};
}

更好的方法是使用 babel 插件 transform-remove-console 创建 .babelrc 文件,并设置 babel 转译器。

示例设置:

{
  "presets": ["react-native"],
  "env": {
    "production": {
      "plugins": ["transform-remove-console"]
    }
  }
}

来源:https://facebook.github.io/react-native/docs/performance.html#using-consolelog-statements

使用这个:https://github.com/babel/minify/tree/master/packages/babel-plugin-transform-remove-console

或者您可以像这样在 utils 中创建一个函数:

export const showLog = (tag, log) => {
  console.log(tag + ' : ' + log);
};

并在项目的任何位置使用 showLog:

import { showLog } from '../utils/utils';

showLog('VideoPlayer', response)

最后,我选择了此处描述的方法 - https://levelup.gitconnected.com/step-up-your-console-messaging-game-in-your-react-app-42eee17659ec 我最喜欢它。

Upd:正如 Chmac 提到的(谢谢),link 已经死了。归档 link here