开发者

Do any of these javascript minifiers remove debug statements?

It would be nice if I could put debug/console log statements in my javascript, then have a js minifier开发者_JAVA技巧/compacter remove these when it compiles.

Does this exist?


Not that I'm aware of, though Google's Closure Compiler will allow you to accomplish something similar if you wish:

/** @define {boolean} */
var DEBUG_MODE = true;

var debug;
if (DEBUG_MODE) {
    /** @param {...} args */
    debug = function(args) { console.log.apply(console, arguments); }
} else {
    /** @param {...} args */
    debug = function(args) {}
}

debug('foo', {a: 5});

If you set DEBUG_MODE to false (you can even do this on the command-line if you wish), then when advanced optimizations are enabled (you must do some work if you want to use these, but they're handy), the empty implementation of debug will be used instead, which will cause calls to it to be "inlined" (optimized out of existence).

You could extend this to have more complicated debugging functions than the above (which simply forwards to console.log); for instance you could make one that accepted a function argument that is called in debug mode, and not called outside of debug mode.


None of the major minifiers implement that, I think its because its not part of any standard (they are undefined in Internet Explorer for example). They expect that you might have declared your own debug/javascript function.


In Perl with JavaScript::Minifier

#!/usr/bin/perl -w
use strict;
use JavaScript::Minifier qw(minify);

open(INFILE, $ARGV[0]) or die;
open(OUTFILE, ">$ARGV[1]") or die;
my $minJs =  minify(input => *INFILE,  stripDebug => 1);
$minJs =~ s#console.log\(.*\);##g;
$minJs =~ s#alert\(.*\);##g;
print OUTFILE $minJs;
close(INFILE);
close(OUTFILE); 

example usage: ./jsMinifier.pl js.js js-min.js

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜