Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Google's Closure to compile JavaScript

Google just released Closure, which is a compiler to minify JavaScript.

On the product site, it says "The Closure Compiler has also been integrated with Page Speed".

How do I use Page Speed to compile my web pages JavaScript with Closure?

(Or, is there a web site that I can simply paste in my JavaScript to have closure minify it?

like image 352
Ted Avatar asked Nov 07 '09 04:11

Ted


People also ask

Does Google have a compiler?

The Closure Compiler is a tool for making JavaScript download and run faster.

What is a closure function in JavaScript?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

What is the closure library used for?

Closure Library is a powerful, low-level JavaScript library designed for building complex and scalable web applications. It is used by many Google web applications, such as Google Search, Gmail, Google Docs, Google+, Google Maps, and others. For more information, visit the Google Developers or GitHub sites.


1 Answers

For a single file it's simple

java -jar $path_to_jar/compiler.jar --js input_file.js \
          --js_output_file output_file.js

For a multi-file project you can use calcdeps.py in combination with the compiler.jar

#!/bin/sh$
$CALCDEPS_PATH=/path/to_calcdeps  #directory containing calcdeps.py
$JAR_PATH=/path/to_jar            #directory containing compiler.jar
$CLOSURE_PATH=/path/to_closure    #contains directory "closure"
$CALCDEPS_PATH/calcdeps.py --path $CLOSURE_PATH \
                           --path . \
                           --compiler_jar $JAR_PATH/compiler.jar \
                           --input main_project_file.js \
                           --output_mode compiled \
                           > compiled_project_file.js

That way compiler gives meaningful information about type errors, etc. Type errors can be caught at compile time because compiler.jar uses certain JSDoc comments for type information.

Extra compiler flags can be passed to calcdeps.py along with -f or --compiler_flags options

If you want to use advanced optimizations set

--compiler_flags "--compilation_level=ADVANCED_OPTIMIZATIONS"

notice the double quotes and the equal sign - had to use that format in bash

like image 71
Evgeny Avatar answered Sep 18 '22 15:09

Evgeny