1

我有一个 main.ts 和一个 helper.ts。在 helper.js 中,我尝试覆盖 console.log 并将其导出,以便可以使用 main.js 中的代码,但是当我运行 console.log() 时,它会因以下错误而崩溃。我试图适应这个SO Answer。我在这里想念什么?

我正在使用将 Typescript 文件转换为 JSts-node main.ts

main.ts 中的错误:

ReferenceError:未定义窗口

我试图通过在 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);

main.ts

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

2 回答 2

0

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

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

于 2020-01-31T15:24:44.460 回答
0

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

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+' })
于 2020-01-31T15:19:50.950 回答