Bad idea to leave “console.log()” calls in your production JavaScript code?

后端 未结 11 2037
醉话见心
醉话见心 2020-12-07 08:03

I have a bunch of console.log() calls in my JavaScript.

Should I comment them out before I deploy to production?

I\'d like to just leave them th

11条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 08:15

    Hope it helps someone--I wrote a wrapper for it a while back, its slightly more flexible than the accepted solution.

    Obviously, if you use other methods such as console.info etc, you can replicate the effect. when done with your staging environment, simply change the default C.debug to false for production and you won't have to change any other code / take lines out etc. Very easy to come back to and debug later on.

    var C = {
        // console wrapper
        debug: true, // global debug on|off
        quietDismiss: false, // may want to just drop, or alert instead
        log: function() {
            if (!C.debug) return false;
    
            if (typeof console == 'object' && typeof console.log != "undefined") {
                console.log.apply(this, arguments); 
            }
            else {
                if (!C.quietDismiss) {
                    var result = "";
                    for (var i = 0, l = arguments.length; i < l; i++)
                        result += arguments[i] + " ("+typeof arguments[i]+") ";
    
                    alert(result);
                }
            }
        }
    }; // end console wrapper.
    
    // example data and object
    var foo = "foo", bar = document.getElementById("divImage");
    C.log(foo, bar);
    
    // to surpress alerts on IE w/o a console:
    C.quietDismiss = true;
    C.log("this won't show if no console");
    
    // to disable console completely everywhere:
    C.debug = false;
    C.log("this won't show ever");
    

提交回复
热议问题