Reputation: 11445
I have console.log all over the place. Removing them all is not good as I might need them again. Is there way I can do something like this for entire react app?
if(env === 'production'){
console.log= function(){}
}
Upvotes: 23
Views: 30458
Reputation: 213
In your index.js file you can simply replace console.log method with an empty function that does nothing. In Node or Frontend app, this should be placed in the file where the application starts from.
if (process.env.NODE_ENV === 'production') {
console.log = () => {}
console.error = () => {}
console.debug = () => {}
}
Now throughout the application in production environment console.log() calls will print nothing. For all other environments, the usual console.log will work as expected.
Upvotes: 7
Reputation: 49
if (process.env.ENVIRONMENT !== "development") {
var console = {};
console.log = function () {};
}
Upvotes: 0
Reputation: 471
In your index.js
file, check if you're running in dev or production mode.
Disable console.log if you're in production mode.
if (process.env.NODE_ENV !== "development")
console.log = () => {};
Upvotes: 27
Reputation: 9
export function consoleLog() {
const args = [...arguments];
for (let i = 0; i < args.length; i++) {
console.log(args[i]);
}
}
save this is a file somewhere, then search all of your files for console.log and replace with consoleLog and make sure you import it at the top of each file where you want to use it.
When you build your production bundle you can simply change it to...
export function consoleLog() {
// const args = [...arguments];
// for (let i = 0; i < args.length; i++) {
// console.log(args[i]);
// }
}
Upvotes: 0
Reputation: 13105
Given you are using React, it is likely that you are already using babel as a part of your build process.
You can use this babel plugin to remove all the console.* function invocations in the build phase.
Upvotes: 19
Reputation: 7382
A much safer way is to not use console.log
and go with a custom logger implementation that you can turn off when needed.
To get you going with something, you can use the excellent debug npm package that makes it easy to turn off globally or selectively and it works on both nodejs server side and client side.
Upvotes: 5