从React Native应用程序中删除console.log

时间:2016-08-14 06:57:00

标签: performance automation react-native console.log

在将React Native应用程序部署到商店之前,是否应该删除console.log()个调用?如果console.log()调用保留在代码中,是否存在某些性能问题或其他问题?

有没有办法用一些任务运行器删除日志(与Grunt或Gulp等与Web相关的任务运行程序类似)?我们在开发/调试/测试阶段仍然需要它们,但不需要生产。

谢谢!

7 个答案:

答案 0 :(得分:42)

嗯,你总是可以这样做:

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

一旦console.log不成立,每个__DEV__都会失效。

答案 1 :(得分:28)

Babel转发器可以使用以下插件删除console语句:

npm i babel-plugin-transform-remove-console --save-dev

编辑.babelrc:

{
  "env": {
    "production": {
      "plugins": ["transform-remove-console"]
    }
  }
}

console语句会从您的代码中删除。

来源:https://hashnode.com/post/remove-consolelog-statements-in-production-in-react-react-native-apps-cj2rx8yj7003s2253er5a9ovw

答案 2 :(得分:9)

相信最佳做法是将调试代码包装在诸如...的语句中

if(__DEV__){
    console.log();
}

这样,它只在您在打包程序或模拟器中运行时运行。更多信息在这里...... https://github.com/facebook/react-native/tree/master/packager#pathtomodulenamemapbundle-query-params

答案 3 :(得分:3)

我知道这个问题已经回答了,但是只想添加我自己的两位。由于我们不需要在内存中创建和分配空对象,因此边上返回null而不是{}的速度更快。

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

这显然是极端,但是您可以在下面看到结果

// return empty object
console.log = () => {}
console.time()
for (var i=0; i<1000000; i++) console.log()
console.timeEnd()

// returning null
console.log = () => null
console.time()
for (var i=0; i<1000000; i++) console.log()
console.timeEnd()

尽管在其他地方测试时更明显:

empty console function

老实说,在现实世界中,仅以我愿意分享,这可能不会带来任何重大好处。

答案 4 :(得分:1)

我发现以下是一个不错的选择,因为即使您不是远程调试人员,即使__DEV__ === true,也无需登录。

事实上,我发现某些版本的RN / JavaScriptCore / etc在登录时(甚至只是字符串)几乎停滞了,而Chrome的V8引擎则不是这种情况。

// only true if remote debugging
const isDebuggingEnabled = (typeof atob !== 'undefined');

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

Check if in remote JS debugging is enabled

答案 5 :(得分:0)

使用Sentry跟踪例外会自动禁用生产中的console.log,但也会使用它来跟踪来自设备的日志。因此,您可以在哨兵异常详细信息(面包屑)中查看最新日志。

答案 6 :(得分:0)

我使用 babel-plugin-transform-remove-console 尝试过,但上述解决方案对我不起作用。

如果有人也尝试使用 babel-plugin-transform-remove-console 来实现,可以使用这个。

npm i babel-plugin-transform-remove-console --save-dev

编辑babel.config.js

module.exports = (api) => {
  const babelEnv = api.env();
  const plugins = [];
  if (babelEnv !== 'development') {
    plugins.push(['transform-remove-console']);
  }
  return {
    presets: ['module:metro-react-native-babel-preset'],
    plugins,
  };
};


相关问题