How to quickly and conveniently disable all console.log statements in my code?

后端 未结 28 2518
深忆病人
深忆病人 2020-11-22 16:48

Is there any way to turn off all console.log statements in my JavaScript code, for testing purposes?

28条回答
  •  臣服心动
    2020-11-22 17:42

    I think that the easiest and most understandable method in 2020 is to just create a global function like log() and you can pick one of the following methods:

    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);
      }
    }
    

    You could say that the downside of these features is that:

    1. You are still calling the functions on runtime
    2. You have to remember to change the debugging variable or the if statement in the second option
    3. You need to make sure you have the function loaded before all of your other files

    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?

提交回复
热议问题