是否有任何方法关闭我的JavaScript代码中的所有console.log语句,用于测试目的?
当前回答
据我从文档中得知,Firebug没有提供任何变量来切换调试状态。相反,将console.log()包装在一个有条件地调用它的包装器中,即:
DEBUG = true; // set to false to disable debugging
function debug_log() {
if ( DEBUG ) {
console.log.apply(this, arguments);
}
}
为了不需要改变所有现有的调用,你可以使用这个代替:
DEBUG = true; // set to false to disable debugging
old_console_log = console.log;
console.log = function() {
if ( DEBUG ) {
old_console_log.apply(this, arguments);
}
}
其他回答
如果你使用IE7,控制台将不会被定义。所以一个更IE友好的版本是:
if (typeof console == "undefined" || typeof console.log == "undefined")
{
var console = { log: function() {} };
}
如果你使用Grunt,你可以添加一个任务来删除/注释console.log语句。因此console.log不再被调用。
https://www.npmjs.org/package/grunt-remove-logging-calls
console.log('pre');
/* pre content */
// define a new console
let preconsole = Object.assign({}, window.console);
let aftconsole = Object.assign({}, window.console, {
log: function(text){
preconsole.log(text);
preconsole.log('log');
}
});
console = aftconsole;
/* content */
console.log('content');
/* end of content */
console = preconsole;
console.log('aft');
警告:无耻的插头!
您还可以使用类似我的JsTrace对象的东西来进行模块化跟踪,并具有模块级别的“切换”功能,从而只打开您当时想要看到的内容。
http://jstrace.codeplex.com
(也有一个NuGet包,为那些谁关心)
所有级别默认为“error”,尽管你可以关闭它们。 不过,我想不出为什么您不希望看到错误
你可以这样改变它们:
Trace.traceLevel('ModuleName1', Trace.Levels.log);
Trace.traceLevel('ModuleName2', Trace.Levels.info);
要获得更多文档,请查看文档
T
我认为2020年最简单、最容易理解的方法是创建一个像log()这样的全局函数,你可以选择以下方法之一:
const debugging = true;
function log(toLog) {
if (debugging) {
console.log(toLog);
}
}
function log(toLog) {
if (true) { // You could manually change it (Annoying, though)
console.log(toLog);
}
}
你可以说这些功能的缺点是:
您仍然在运行时调用函数 您必须记住在第二个选项中更改调试变量或if语句 您需要确保在加载所有其他文件之前加载了该函数
And my retorts to these statements is that this is the only method that won't completely remove the console or console.log function which I think is bad programming because other developers who are working on the website would have to realize that you ignorantly removed them. Also, you can't edit JavaScript source code in JavaScript, so if you really want something to just wipe all of those from the code you could use a minifier that minifies your code and removes all console.logs. Now, the choice is yours, what will you do?
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何在Visual c++中保持控制台窗口打开?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?