1

I have a main.ts and a helper.ts. In the helper.js I tried to override console.log and export it so I could use the code in my main.js, but when I run a console.log() it crashes with the error below. I was trying to adapt this SO Answer. What am I missing here?

I am transpiling Typescript files to JS using ts-node main.ts

Error in main.ts:

ReferenceError: window is not defined

I tried to fix this by adding at the bottom of helper.ts: (this as any).window.console = console; but got the same error.

helper.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")
Rilcon42
  • 9,584
  • 18
  • 83
  • 167

2 Answers2

0

I use something like this in my app, but to register a log in a separate file:

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+' })
m4el
  • 455
  • 1
  • 4
  • 14
0

If you want access to the global object across environments, use globalThis. Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis

That said, I wouldn't recommend replacing accessing global objects. It'll just lead to misery down the road.

Bronzdragon
  • 345
  • 3
  • 13