Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove console.assert in production code

Tags:

javascript

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.

like image 914
jhchen Avatar asked Sep 13 '11 06:09

jhchen


3 Answers

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!

like image 112
Anko Avatar answered Oct 05 '22 07:10

Anko


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

like image 45
kapex Avatar answered Oct 05 '22 08:10

kapex


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

like image 34
chelmertz Avatar answered Oct 05 '22 08:10

chelmertz