是否有任何方法关闭我的JavaScript代码中的所有console.log语句,用于测试目的?
当前回答
如果你正在使用gulp,那么你可以使用这个插件:
使用下面的命令安装这个插件: NPM安装gulp-remove-logging 接下来,将这一行添加到gulpfile中: Var gulp_remove_logging = require("gulp-remove-logging"); 最后,将配置设置(见下文)添加到gulpfile中。 任务配置 饮而尽。任务("remove_logging",函数(){ 返回gulp.src (" src / javascript / * * / * . js”) .pipe ( gulp_remove_logging () ) .pipe ( gulp.dest ( “构建/ javascript /” ) ); });
其他回答
我的全面解决方案禁用/覆盖所有控制台。*函数在这里。
当然,请确保在检查必要的上下文之后包含它。例如,只包含在产品版本中,它不会轰炸任何其他关键组件等。
这里引用一下:
“使用严格的”; (() => { Var控制台=(窗口。控制台=窗口。控制台|| {}); [ “维护”、“清楚”、“数”、“调试”,“dir”、“dirxml”, "error", "exception", "group", " groupcollapse ", "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd", "table", "time" "timeEnd" "timeStamp" "trace" "warn" ]。forEach(方法=> { Console [method] = () => {}; }); console.log("此消息不应该在控制台日志中可见"); })();
只需更改标志DEBUG以覆盖console.log函数。这应该能奏效。
var DEBUG = false;
// ENABLE/DISABLE Console Logs
if(!DEBUG){
console.log = function() {}
}
这是在JS 2020中引入的。在浏览器上globalThis和window一样,在nodejs上globalThis和global一样等等。在任何环境上,它将直接指向全局对象,因此这段代码将在任何支持JS2020的env上工作了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
对于任何现代浏览器& nodejs v12或更新版本,你应该使用这个:
globalThis.console.log = () => null;
globalThis.console.warn = () => null;
globalThis.console.info = () => null;
globalThis.console.error = () => null;
嘿~让我们用现代的2022方式来做~
ES6中引入了代理和反射。这些是我们正在寻找的工具,使console.log被条件“禁用”。
在传统的方法中,你必须创建另一个函数,像这样:
let console_disabled = true;
function console_log() {
if (!console_disabled) {
console.log.apply(console, arguments); //Dev Tools will mark the coding line here
}
}
但是,这将创建另一个函数,并且您无法使用Dev Tools中显示的编码行记录消息。
这就是2022年之路。
// Disable Console Log without altering debug coding line. // No override original `console` object let console_disabled = false; const nullFunc = function(){}; const _console = new Proxy(console, { get(target, prop, receiver){ if(prop==='log' && console_disabled){ return nullFunc; } return Reflect.get(...arguments) } }); console_disabled = true; _console.log('you cannot see me'); console_disabled = false; _console.log('you can see me @ line 18'); console_disabled = true; _console.log('you cannot see me'); console_disabled = false; _console.log('you can see me @ line 22');
您还可以重写原来的控制台对象。
// Disable Console Log without altering debug coding line. // Override original `console` object let console_disabled = false; const nullFunc = function(){}; console = new Proxy(console, { get(target, prop, receiver){ if(prop==='log' && console_disabled){ return nullFunc; } return Reflect.get(...arguments) } }); console_disabled = true; console.log('you cannot see me'); console_disabled = false; console.log('you can see me @ line 18'); console_disabled = true; console.log('you cannot see me'); console_disabled = false; console.log('you can see me @ line 22');
有关代理和反射的详细信息, 请访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
当使用React时,你可以利用钩子来管理它,这样它就被限制在你的组件范围内
import { useEffect, useRef } from "react";
type LoggingReplacements = {
debug?: typeof console["debug"];
error?: typeof console["error"];
info?: typeof console["info"];
log?: typeof console["log"];
warn?: typeof console["warn"];
};
/**
* This replaces console.XXX loggers with custom implementations. It will restore console log on unmount of the component.
* @param replacements a map of replacement loggers. They're all optional and only the functions defined will be replaced.
*/
export function useReplaceLogging({
debug,
error,
info,
log,
warn,
}: LoggingReplacements): void {
const originalConsoleDebug = useRef(console.debug);
const originalConsoleError = useRef(console.error);
const originalConsoleInfo = useRef(console.info);
const originalConsoleLog = useRef(console.log);
const originalConsoleWarn = useRef(console.warn);
if (debug) {
console.debug = debug;
}
if (error) {
console.error = error;
}
if (info) {
console.info = info;
}
if (log) {
console.log = log;
}
if (warn) {
console.warn = warn;
}
useEffect(() => {
return function restoreConsoleLog() {
console.debug = originalConsoleDebug.current;
console.error = originalConsoleError.current;
console.info = originalConsoleInfo.current;
console.log = originalConsoleLog.current;
console.warn = originalConsoleWarn.current;
};
}, []);
}
在https://github.com/trajano/react-hooks/tree/master/src/useReplaceLogging上编写测试代码
推荐文章
- 一元加/数字(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?