Friday, March 6, 2009

dojo builds and regexp

Just saw a tweet fly by which made me think of a possible blog entry.

I'm more inclined to use Firebug and console.* statements to debug my client side dojo code. I find it easier than rebuilding my code base every time I want to make a change. The one downside to this is my client side code has console statements scattered throughout the code, thus making my the download heavier.

So, as part of my build process, I use the following code to strip out all console.* statements and replace them with a semi-colon.


my @generated_files = (
"htdocs/my-build/$revision/dojo/dojo/main.js",
"htdocs/my-build/$revision/dojo/dojo/registration.js",
"htdocs/my-build/$revision/dojo/dojo/poller.js",
"htdocs/my-build/$revision/dojo/dojo/extras.js"
);
foreach my $generatedFileName (@generated_files) {
my $in_file = $generatedFileName;
my $out_file = $generatedFileName . ".stripped.js";
open DATA, "$in_file" or die "can't open $in_file $!";
my @file_lines = ;
close (DATA);
open DATAOUT, ">$out_file" or die "can't open $out_file $!";
foreach my $line (@file_lines) {
$line =~ s/(?<!:)console\.(?:warn|log|error|con|info)(\((?:(?>[^()]+)|(?{1}))*\));/;/gi;
print DATAOUT "$line";
}
close (DATAOUT);
}


The good people over at http://regexadvice.com/ helped me out with that expression and saved me ~5KB after GZIP compression - not too shabby.

This regular expression does not filter every console.* statement out of your code. For example if the regexp parser encounters:


test ? console.warn("Success") : console.warn("Failure");


it will not strip it down to:


test ? ; : ; ;


As that isn't valid JavaScript.

I'm pretty sure this problem could be fixed for the latest and greatest versions of dojo with a new parameter which you can pass automatically to the build script, but I'm still on 1.0.2 so I'll continue with this until I upgrade to 1.3.

No comments:

Post a Comment