2

Possible Duplicate:
jQuery compiled with Google Closure Compiler

My markup:

<script src="http://somecdn.com/jquery-1.4.2.min.js"></script>
<script src="/js/mycode.closure_compiled.js"></script>

My code:

goog.provide("mycode");

mycode.foo = function () {
    jQuery("#ajaxSpinner").show();
    jQuery.get("/ajax/foo", function () { /* ... */ });
}

I want to compile my code with advanced optimizations using the Google Closure Compiler.

How do I achieve the following?

  1. The compiler should not rename "jQuery" and "jQuery.get".
  2. The compiler should not throw Errors or Warnings (eg. "unknown type 'jQuery'").
Community
  • 1
  • 1
Julius Eckert
  • 1,481
  • 4
  • 16
  • 24
  • jQuery isn't extern compatible out of the box, so you can't use the `--externs` argument like you need here...you need an extern compatible build of jQuery, I'm not sure if anyone's done such yet. – Nick Craver Jul 26 '10 at 11:52
  • I know you want advance optimizations, but as a reference you could do a simple optimization at this site: http://closureoptimizer.com/ – Mottie Jul 26 '10 at 14:41

2 Answers2

4

You will have to use externs. these are files that tell the compiler which symbols in your code come from external code and therefor shouldn't be renamed. Basically you will have to specify an extern with the --externs flag. Some third-party extern files like jQuery are available at the project source code.

Jan
  • 8,011
  • 3
  • 38
  • 60
  • 3
    This is the correct way to do this - command line example: java -jar compiler.jar --externs jquery-1.6.js --js jquery-1.6.2.js --js test.js --compilation_level ADVANCED_OPTIMIZATIONS --js_output_file output.js – Chris Moschini Oct 19 '11 at 23:08
  • 1
    Grand! But jQuery file should not be compiled. Command line example [updated]: java -jar compiler.jar --externs jquery-1.6.js --js test.js --compilation_level ADVANCED_OPTIMIZATIONS --js_output_file output.js – German Latorre Feb 07 '12 at 11:31
0

jQuery is not compatible with the Closure Compiler in Advanced mode. In fact, out of the popular JavaScript libraries, only the Dojo Toolkit is compatible (see link below).

http://dojo-toolkit.33424.n3.nabble.com/file/n2636749/Using_the_Dojo_Toolkit_with_the_Closure_Compiler.pdf?by-user=t

However, if you just want to use jQuery with Closure Compiler Advanced mode without renaming, there is a trick that I've developed over time:

  • Provide your library file (i.e. jquery.js) as an "extern" to the compiler

The Compiler will not rename anything used by jQuery. Of course, your own code should always be Closure compatible. Also, your compiled output may still not work correct, and there may be a few obscure bugs you need to tackle.

In fact, this was how I used to use Dojo with Closure Advanced mode before I finally got sick of it and made the necessary modifications to get Dojo compatible.

Stephen Chung
  • 14,497
  • 1
  • 35
  • 48