Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for removing console.log and other debug code from your release JavaScript?

I've seen some of the console wrappers that stop errors in browser with a console and more advanced ones that enable logging in older browsers. But none that I've seen help switch on and off the debug code.

At the moment I do a find and replace to comment out debug code. There must be a better way?

I'm using Combres which uses YUI to minify the JavaScript. I've seen some posts that mention using double semi colons to mark lines to be removed in the minification process. Is this a hack or good practice?

like image 351
moefinley Avatar asked Sep 05 '12 10:09

moefinley


People also ask

How do I get rid of console logging?

Just change the flag DEBUG to override the console. log function. This should do the trick.

How do I debug without console log?

Console logging works, but there's a better way. Instead of console. logging and restarting every time you want to debug, you can instead use Chrome DevTools (right click + inspect). Perhaps you're already using it to view and modify HTML/CSS elements, monitor console logs, and measure network performance.

Does console log slow down JavaScript?

Of course, console. log() will reduce your program's performance since it takes computational time.


2 Answers

Probably you should have your own wrapper around console.log() and log your debug info via that wrapper. That way you can replace that single function with an empty function once you deploy to production so the console won't flood with debugging info. You can also replace the actual console.log function with an empty function, but that would prevent any Javascript from outputting to console, not just yours.

like image 102
lanzz Avatar answered Sep 18 '22 12:09

lanzz


If you look at how the YUI Framework does it, they actually use a regex and generate 3 files from source. One that has the logging -debug, one that has the logging stripped out, just the file name, and a minified version with no logging. Then you can set a global config to say which version you want. I've worked that way in the past and works nicely.

like image 41
Kevin Avatar answered Sep 22 '22 12:09

Kevin