Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing console.log with closure compiler

I'd like to make my JS code production ready by stripping out all console.log("blah blah") debugging statements. I'm confused by this popular SO answer (code below) on how to do this using Google's closure compiler, a popular JS minifier/compiler.

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

//this will even work with `SIMPLE_OPTIMALIZATIONS` and no `--define=` is necessary !

Two questions:

  1. Multiples files: How does the above code work with multiple files (basic example below)? It has to be in a closure, right? Doesn't this then mean you have to put this code on each page? Also, doesn't it also then mean you have to change all the variables you want to be global from var foo='bar' to var window.foo='bar'; inside these closures on each page?

  2. Minor issue: Shouldn't it be console.log('...') rather than log('...') because log() gives an error? Am I missing something obvious here?

<script src='/assets/js/file1.js'></script> <script src='/assets/js/file2.js'></script>

contents of file1.js:

var foo='bar';
console.log("foo"+foo);

contents of file2.js

var baz='bazzy';
console.log("baz"+baz);
like image 947
tim peterson Avatar asked Sep 16 '13 21:09

tim peterson


People also ask

Can you delete console log?

Use the short cut Ctrl + L to clear the console. Use the clear log button on the top left corner of the chrome dev tools console to clear the console.

What is the function of closure compiler?

The Closure Compiler is a tool for making JavaScript download and run faster. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left.


1 Answers

If you have your code split up into multiple files, I would think you'd want to have a build process that joins them into one immediately invoked function. Then your var LOG = false; can just be included once at the top.

If by "each page", you mean that you have separate JavaScript files per page that aren't meant to be joined together, then yes, you'd need to have that code at the top of each, but then you're also not taking as much advantage of Closure Compiler.

Regarding globals, yes, you'd need to use window when setting, though I would hope you're defining only one global.

The use of log() implies that someone defined a log() function so that it's less verbose.

function log() {
    return console.log.apply(console, arguments);
}
like image 197
user2736012 Avatar answered Sep 29 '22 02:09

user2736012