如何在生产中禁用console.log()并显示横幅?

时间:2018-09-22 04:32:06

标签: javascript frontend

以前,我一直在为自己的团队使用Web应用程序,从未在现实世界中公开过任何应用程序。谁能阐明如何禁用生产中的console.log()?我看到了如下成就:

enter image description here

enter image description here

4 个答案:

答案 0 :(得分:1)

您是否正在使用某种模块捆绑器? 在webpack中,您可以选择在构建中放置drop_console。 drop console的作用是从代码中删除所有console.log语句。 也有同样的npm模块,请看一下。 https://www.npmjs.com/package/babel-plugin-transform-remove-console 这是一个百吉饼插件,如果您有babel设置,就可以使用它。

如果所有这些都不符合您的要求。您可以简单地覆盖console.log语句,或根据其他答案的建议使用自定义记录器。

答案 1 :(得分:0)

var DEBUG = false;
if(!DEBUG){
  if(!window.console) window.console = {};
  var methods = ["log", "debug", "warn", "info"];
  for(var i=0;i<methods.length;i++){
      console[methods[i]] = function(){};
 }
}

答案 2 :(得分:0)

您可以使用其他自定义函数替换代码中的所有console.log(...),以根据需要显示日志信息,例如在DIV元素中。 但是,如果您确实想覆盖console.log函数,则可以像下面这样简单地进行操作(通常不建议这样做):

#myLogDiv {color: #604040; border: 1px solid gray; padding: 5pt; }
<script>
console.log = function(t) { 
    document.getElementById("myLogDiv").innerText += t + "\r\n"; 
  }
</script>


<div id="myLogDiv">» My Log: <br/></div>

<p>This is normal content</p>

<script>
console.log("hello");
</script>

<p>Other content...</p>

<script>
console.log("world!");
</script>

答案 3 :(得分:0)

方法1 :您可以将console.log保存到自己的函数中并删除原始函数。

类似的东西:

writeConsoleLog = console.log; //save the log function in your own function
console.log = function(){} //override the original log function
console.log("Text"); //does nothing
writeConsoleLog("Text"); //mimics the console.log() and writes to the console

方法2:您可以先console.log进行任何操作,然后像这样删除日志功能

console.log("The content you want to print"); //will write to the console
console.log = function(){} //override the log function
console.log("Text"); //now it does nothing