7, Mar 2013
Introducing Google Closure
How to Get it
Sounds great right? Lets get cracking! Firstly we need to go download the Compiler from the Google Developers Site; scroll down to the bottom of the page and click the 'Download the application' link. I'm going to set-up the compiler in /opt on my server. You can do the same:
sudo mkdir /opt/closure cd /opt/closure sudo unzip path/to/compiler-latest.zip sudo chmod a+r *
That's all there is to it! You should be able to run the command below now as a regular user:
java -jar /opt/closure/compiler.jar --help
How to Use it
java -jar /opt/closure/compiler.jar --js script1.js --js script2.js --js script3.js
java -jar /opt/closure/compiler.jar --js script1.js --js script2.js --js script3.js --js_output_file scripts-compiled.js
If you got some errors when you ran the compiler, then you've already seen another massive benefit that the Closure Compiler provides: detailed error information. The compiler will output the file and line of any errors that it encounters as it processes your files, as well as a helpful message on how to fix them. Not only does it notify you of syntax errors, but it will also tell you of any common issues that are present.
My personal favourite - something that has cost me quite a lot of time trying to figure out in the past - is that the Closure Compiler will throw an error on trailing commas in arrays. This is something that I've noticed many developers tend forget about. An example of the problem in action would be this array:
var arr = [1,2,3,];
This will cause you no problems at all until you attempt to load the page in Internet Explorer 8 or less. At that point you'll find an error about an Expected identifier. There are many other issues in your code that the Closure Compiler will detect and inform you of. Some of the examples that I've run into are:
- If you have JSDoc style annotations in a comment, but forgot to start the comment block correctly
- If you use reserved words as a variable or function; eg. var.class or var.delete()
Integrating the Closure Compiler in your Build Process
Now that we know how to create our compiled version of our code base it's time to start using it. We don't want to be using the compiled version during development, as we then lose the fidelity gained by having multiple files when debugging (also full variable names and accurate line numbers), additionally you would have to recompile your scripts whenever you make a change. So we need to have a configuration setting to toggle the use of the compiled scripts inside our application:
cd <workspace>/js java -jar /opt/closure/compiler.jar --js script1.js --js script2.js --js script3.js --js_output_file scripts-compiled.js
That's all there is to it! If there are any errors generated by the Closure Compiler the build will fail, preventing potentially broken code from reaching production.
Have Something to Say?
Questions? Comments? Concerns? Let me know what you’re thinking.