admin管理员组

文章数量:1279117

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 a better way. It would be ideal if there was some javascript preprocessor to remove this.

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 a better way. It would be ideal if there was some javascript preprocessor to remove this.

Share Improve this question asked Sep 13, 2011 at 6:29 jhchenjhchen 14.8k14 gold badges65 silver badges91 bronze badges 3
  • @wukong Except it's ... JavaScript :-) – user166390 Commented Sep 13, 2011 at 6:35
  • 4 What about using a test-framework and a debugger? :-) Don't even let that console.assert get in there! – user166390 Commented Sep 13, 2011 at 6:36
  • 4 I do that too but found asserts really useful catching errors very early by enforcing expected state wherever I can – jhchen Commented Sep 13, 2011 at 18:13
Add a ment  | 

3 Answers 3

Reset to default 5

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

uglifyjs [input files] --press 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 piled with the above mand:

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();

...piles 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.

本文标签: javascriptRemove consoleassert in production codeStack Overflow