An Ant Task to Comment Out console.log Calls from JavaScript Files

As someone who started out doing JavaScript in the 1990s, I’ve been through the dark ages of debugging. Alerts, logging application data into DOM elements, etc. After having been through all that doom, I’m clearly a fan of console.log. I use it all the time. I bet you do too. It’s super useful.

The one downside? Leaving calls to console.log into code that’s being tested (as in, QA) or is destined for production (as in, emergency bug fix.) With Firebug or a similar tool running, you’re fine. Without it?

"console" is not defined.

I’ve seen this more times recently than I care to admit.

One way to to “fix” it is to test if console is defined and if it’s not, catch all the calls and redirect them to something quiet. This is hideous, but I’m going to share it anyway.

try {
	console.log("console");
}
catch(e){
	console={
		log: function(){
			return;
		}
	}
} 

UGLY. I don’t like it. Thing is, it works, so it might float your boat.

A nicer solution is to build a safety valve into your build script. I use Ant for this stuff, but there are other options out there. This example comments out the calls, using a simple regular expression, the global flag and a back reference. You could clearly delete them altogether or run the commented script through something like YUI compressor at a later stage in your build script to fully clean up your files.

<?xml version="1.0"?>
<project name="console.logathon" default="hide_console" basedir=".">
<target name="copy" >
<copy todir="publish">
<fileset dir="src">
</fileset>
</copy>
</target>
<target name="hide_console" depends="copy">
<replaceregexp match="(console.log\(.*\))" replace="/\*\1\*/" flags="g" file="publish/_assets/scripts/base.js" />
</target>
</project>

And there you have it. No more errors.

Leave a Reply

Your email address will not be published. Required fields are marked *