开发者

Remove console.assert in production code

I'm using console.assert to test/debug but I'd like to remove this in production code. I'm basically overwriting console.assert to be a noop function right now but wondering if there's开发者_StackOverflow中文版 a better way. It would be ideal if there was some javascript preprocessor to remove this.


UglifyJS2 does this easily: When running the uglifyjs command, enable the compressor and tell it to discard console.* calls:

uglifyjs [input files] --compress drop_console

Quick example:

function doSomething() {
    console.log("This is just a debug message.");
    process.stdout.write("This is actual app code.\n");
}
doSomething();

... gives this when compiled with the above command:

function doSomething(){process.stdout.write("This is actual app code.\n")}doSomething();

This might be an UglifyJS2 bug, but be careful about side effects in those calls!

function doSomething() {
    var i = 0;
    console.log("This is just a debug message." + (++i));
    process.stdout.write("This is actual app code." + i + "\n");
}
doSomething();

...compiles to

function doSomething(){var i=0;process.stdout.write("This is actual app code."+i+"\n")}doSomething();

... which writes i as 0 instead of 1!


Try Closure Compiler, in advanced mode it removes empty functions (and much more).


Another tool is UglifyJS which is used with nodejs. It's fast and got a lot of options for you to check out.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜