当我覆盖控制台.log时,如何将其导出到其他文件?



我有一个main.ts和一个helper.ts。在帮助程序中.js我尝试覆盖控制台.log并将其导出,以便我可以在我的 main.js 中使用代码,但是当我运行 console.log(( 时,它崩溃并出现以下错误。我试图改编这个SO答案。我在这里错过了什么?

我正在使用ts-node main.ts将打字稿文件转换为 JS

main.ts 中的错误:

引用错误: 窗口未定义

我试图通过在helper.ts的底部添加来解决此问题:(this as any).window.console = console;但得到了同样的错误。

助手.ts

export var console = (function(oldCons) {
return {
log: function(text: any) {
oldCons.log("WHEEE" + text);
// Your code
},
info: function(text: any) {
oldCons.info(text);
// Your code
},
warn: function(text: any) {
oldCons.warn(text);
// Your code
},
error: function(text: any) {
oldCons.error(text);
// Your code
}
};
})(window.console);

主目录

import {console} from './helper.ts'
console.log("hi stack overflow")

我在应用程序中使用了这样的东西,但是要在单独的文件中注册日志:

console.log = function(d) {     
try {
var timestamp = 'n[' + new Date(Date.now()).toLocaleString() + '] '
log_file.write(util.format(timestamp + d))
log_stdout.write(util.format(timestamp + d))
} catch(e) {
return
}
}
var log_file    = fs.createWriteStream('log/'+ new Date().getDate() +'-'+ (new Date().getMonth()+1) +'-'+ new Date().getFullYear() +'.log', { encoding: 'utf-8', flags: 'a+' })

如果要跨环境访问全局对象,请使用globalThis。链接: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis

也就是说,我不建议替换访问全局对象。这只会导致未来的痛苦。

最新更新