Dreams
Dreams

Reputation: 8506

How to write a function to disable console.log and can be required in other react file?

Below is my static.js file:

var Helper = {
    console.log: function(){
    },

    Login: function(){
        var name;
        var password;
        //rest of the code
    }
}

module.exports = Helper;

And below is my test.js file:

var Helper = require('./static.js');
console.log("Test");

And I got some error from this line console.log: function(){} in static.js file.

What I want is nothing will show on terminal even I console.log('Test') because I write function(){} for console.log.

Is anything I did wrong?

Upvotes: 0

Views: 1279

Answers (3)

Kirill Rogovoy
Kirill Rogovoy

Reputation: 591

You have this error because you're trying to create an object with a key console.log, but it is a syntax violation when using object literal syntax, because . dot is a special symbol.

Even if it worked, you wouldn't achieve what you want, since console.log is a global function and you are working with just a custom created object.

What you actually want to do is to silence the global function like this console.log = function() {};. Beware, however, that you won't be able to restore the old behaviour if you didn't save the original function: var oldConsoleLog = console.log.

There is also a module for it.

Upvotes: 0

Dreams
Dreams

Reputation: 8506

I just figured out how to fix this problem.

I rewrite the function like below..

DisableConsole: function(DEBUG){
    if(!DEBUG){
        if(!window.console) window.console = {};
        var methods = ["log", "debug", "warn", "info"];
        for(var i=0;i<methods.length;i++){
            console[methods[i]] = function(){};
        }
    }
}

and require this static.js file in my top component which mean every component under this main component will also include this static.js.

and call this function in the very beginning.

AppHelpers.DisableConsole(false);

Upvotes: 1

Govind Samrow
Govind Samrow

Reputation: 10189

Just overwrite console.log function in your script:

console.log = function() {};

Overwrite other log function too:

window.console.log = window.console.debug = window.console.info = window.console.error = function () {
    return false;
}

Upvotes: 1

Related Questions