Using the Google Closure Compiler

Possible duplicate:
jQuery compiled using the Google Closure Compiler

I am using jQuery and I have all my JS code in the application.js file. When I compile "application.js" with the Google Closure compiler (using optional parameters), I get the js file without errors and warnings. However, I cannot use the file on my page, I get an error loading the page that says: "TypeError: Result of the expression" $ ("div.tile"). D '[undefined] is not a function. "

My question is Can I compile a js file that uses jQuery?

+6
jquery google-closure google-closure-compiler
source share
3 answers

Yes, if you want to include the jQuery file in your other file.

Yes, if you use simple mode.

Otherwise, no.

+1
source share

You can also use advanced mode if you specify that your js file uses jQuery by specifying an "extern" file for jQuery. This way, the closure compiler will not change your jQuery function calls inside your javascript.

java -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js_output_file application.js --externs jquery-1.4.4.externs.js 

Here you can find some of the jQuery extern files: http://code.google.com/p/closure-compiler/source/browse/trunk/contrib/externs/

+16
source share

You must tell the Closure compiler that you are not optimizing.

I do this with the online compiler ( http://closure-compiler.appspot.com/home ) by adding the externs_url parameter. When you enter your code in an online compiler, it automatically adds a header similar to this, but without the default externs_url parameter.

 // ==ClosureCompiler== // @output_file_name default.js // @compilation_level ADVANCED_OPTIMIZATIONS // @externs_url https://closure-compiler.googlecode.com/git/contrib/externs/jquery-1.9.js // ==/ClosureCompiler== 

You can see which external files are currently available at https://code.google.com/p/closure-compiler/source/browse/contrib/externs/ . They have most versions of jQuery.

To do this using the downloadable Java version of the compiler, you can simply pass the -externs_url paramater parameter to cli or load the extern file you need and pass that file name with the -externs paramater parameter, as in Palmerli's answer.

If you are wondering why you cannot just enable advanced optimization, read http://code.google.com/closure/compiler/docs/api-tutorial3.html

+8
source share

All Articles