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

I saw some of the console shells that stop errors in the browser using the console and more advanced ones that allow logging in older browsers. But none of what I've seen helps turn debugging code on or off.

I am currently finding and replacing the comment code for debugging. Should there be a better way?

I use Combres, which uses YUI to minimize JavaScript. I saw several posts mentioning the use of double half-columns for marking strings that need to be removed in the minimization process. Is it hacking or good practice?

+7
source share
4 answers

You should probably have your own shell around console.log() and log your debugging information through this shell. Thus, you can replace this single function with an empty function after deployment to production so that the console does not flood debugging information. You can also replace the actual console.log function with an empty function, but this will prevent any Javascript from being output to the console, not just you.

+2
source

If you look at how the YUI Framework works, they actually use regex and generate 3 files from the source. The one that has logging -debug, the one that has the log disabled, is just the file name and the short version without logging. Then you can set the global configuration to say which version you want. I have worked this way in the past and it works great.

+1
source

Define your own debugging function that will wrap around console.log or anything else you want, and make sure the minifier can easily determine if it is non-op if you make it empty. After that, as soon as you comment on the body out function, most minifiers should find that there is nothing to call or embed and completely remove references to your function.

Here is an example:

 (function() { function debug() { console.log(arguments) } function main() { debug(123) alert("This is production code!") debug(456) } main() })() 

I put it in an anonymous function to limit the scope of the debug and did not allow it to be bound to the window - this allows the minifier to easily decide whether it is necessary or not. When I embed this code in the online GCC , I get:

 (function(){function a(){console.log(arguments)}a(123);alert("This is production code!");a(456)})(); 

But as soon as I add // to console.log to make debug empty, GCC compiles it into:

 (function(){alert("This is production code!")})(); 

... completely removes all traces of debugging code!

+1
source

Use Y.log () instead, and then you can use the gallery-log filter to filter the log messages that you want to print.

0
source

All Articles