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:
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?
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);
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);
}