Exclude debug JavaScript code during minification

守給你的承諾、 提交于 2019-12-27 17:18:28

问题


I'm looking into different ways to minify my JavaScript code including the regular JSMin, Packer, and YUI solutions. I'm really interested in the new Google Closure Compiler, as it looks exceptionally powerful.

I noticed that Dean Edwards packer has a feature to exclude lines of code that start with three semicolons. This is handy to exclude debug code. For instance:

;;;     console.log("Starting process");

I'm spending some time cleaning up my codebase and would like to add hints like this to easily exclude debug code. In preparation for this, I'd like to figure out if this is the best solution, or if there are other techniques.

Because I haven't chosen how to minify yet, I'd like to clean the code in a way that is compatible with whatever minifier I end up going with. So my questions are these:

  1. Is using the semicolons a standard technique, or are there other ways to do it?

  2. Is Packer the only solution that provides this feature?

  3. Can the other solutions be adapted to work this way as well, or do they have alternative ways of accomplishing this?

  4. I will probably start using Closure Compiler eventually. Is there anything I should do now that would prepare for it?


回答1:


here's the (ultimate) answer for closure compiler :

/** @const */
var LOG = false;
...
LOG && log('hello world !'); // compiler will remove this line
...

this will even work with SIMPLE_OPTIMIZATIONS and no --define= is necessary !




回答2:


Here's what I use with Closure Compiler. First, you need to define a DEBUG variable like this:

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

It's using the JS annotation for closure, which you can read about in the documentation.

Now, whenever you want some debug-only code, just wrap it in an if statement, like so:

if (DEBUG) {
  console.log("Running in DEBUG mode");
}

When compiling your code for release, add the following your compilation command: --define='DEBUG=false' -- any code within the debug statement will be completely left out of the compiled file.




回答3:


A good solution in this case might be js-build-tools which supports 'conditional compilation'.

In short you can use comments such as

// #ifdef debug
var trace = debug.getTracer("easyXDM.Rpc");
trace("constructor");
// #endif

where you define a pragma such as debug.

Then when building it (it has an ant-task)

//this file will not have the debug code
<preprocess infile="work/easyXDM.combined.js" outfile="work/easyXDM.js"/>
//this file will        
<preprocess infile="work/easyXDM.combined.js" outfile="work/easyXDM.debug.js" defines="debug"/>



回答4:


If you use the Closure Compiler in Advanced mode, you can do something like:

if (DEBUG) console.log = function() {}

Then the compiler will remove all your console.log calls. Of course you need to --define the variable DEBUG in the command line.

However, this is only for Advanced mode. If you are using Simple mode, you'll need to run a preprocessor on your source file.

Why not consider the Dojo Toolkit? It has built-in comment-based pragma's to include/exclude sections of code based on a build. Plus, it is compatible with the Closure Compiler in Advanced mode (see link below)!

http://dojo-toolkit.33424.n3.nabble.com/file/n2636749/Using_the_Dojo_Toolkit_with_the_Closure_Compiler.pdf?by-user=t




回答5:


Even though its an old question. I stumbled upon the same issue today and found that it can be achieved using CompilerOptions.

I followed this thread.

We run the compiler, from Java, on our server before sending the code to the client. This worked for us in Simple mode.

private String compressWithClosureCompiler(final String code) {
    final Compiler compiler = new Compiler();
    final CompilerOptions options = new CompilerOptions();
    Logger.getLogger("com.google.javascript.jscomp").setLevel(Level.OFF);
    if (compressRemovesLogging) {
        options.stripNamePrefixes = ImmutableSet.of("logger");
        options.stripNameSuffixes = ImmutableSet.of("debug", "dev", "info", "error",
                "warn", "startClock", "stopClock", "dir");
    }
    CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

    final JSSourceFile extern = JSSourceFile.fromCode("externs.js", "");
    final JSSourceFile input = JSSourceFile.fromCode("input.js", code);
    compiler.compile(extern, input, options);
    return compiler.toSource();
}

It will remove all the calls to logger.debug, logger.dev...etc.etc




回答6:


If you're using UglifyJS2, you can use the drop_console argument to remove console.* functions.




回答7:


Adding logic to every place in your code where you are logging to the console makes it harder to debug and maintain.

If you are already going to add a build step for your production code, you could always add another file at the top that turns your console methods into noop's.

Something like:

console.log = console.debug = console.info = function(){};

Ideally, you'd just strip out any console methods, but if you are keeping them in anyway but not using them, this is probably the easiest to work with.




回答8:


I am with @marcel-korpel. Isn't perfect but works. Replace the debug instructions before minification. The regular expression works in many places. Watch out unenclosed lines.

/console\.[^;]*/gm

Works on:

;;;     console.log("Starting process");
console.log("Starting process");
console.dir("Starting process");;;;;
console.log("Starting "+(1+2)+" processes"); iamok('good');
console.log('Message ' +
    'with new line'
);
console.group("a");
console.groupEnd();
swtich(input){
    case 1 : alert('ok'); break;
    default: console.warn("Fatal error"); break;
}

Don't works:

console.log("instruction without semicolon")
console.log("semicolon in ; string");



回答9:


I haven't looked into minification so far, but this behaviour could be accomplished using a simple regular expression:

s/;;;.*//g

This replaces everything in a line after (and including) three semicolons with nothing, so it's discarded before minifying. You can run sed (or a similar tool) before running your minification tool, like this:

sed 's/;;;.*//g' < infile.js > outfile.js

BTW, if you're wondering whether the packed version or the minified version will be 'better', read this comparison of JavaScript compression methods.




回答10:


I've used following self-made stuf:

// Uncomment to enable debug messages
// var debug = true;

function ShowDebugMessage(message) {
    if (debug) {
        alert(message);
    }
}

So when you've declared variable debug which is set to true - all ShowDebugMessage() calls would call alert() as well. So just use it in a code and forget about in place conditions like ifdef or manual commenting of the debug output lines.




回答11:


I use this in my React apps:

if (process.env.REACT_APP_STAGE === 'PROD')
  console.log = function no_console() {};

In other words, console.log will return nothing on prod enviroment.



来源:https://stackoverflow.com/questions/2934509/exclude-debug-javascript-code-during-minification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!