Search code examples
javascriptjqueryantgoogle-closure-compiler

Can't compile javascript using ant and closure compiler because of Jquery's $ is undeclared


I am trying to get Google Closure Compiler to work to compile my javascript code that uses Jquery but i keep getting variable $ is undeclared is there a way to get it to see the $ variable. Is there a way for closure Compiler to see the Jquery library but not compile it. here is my ant script

<?xml version="1.0"?>
<project basedir="." default="compile">

<taskdef name="jscomp" classname="com.google.javascript.jscomp.ant.CompileTask"
       classpath="build/compiler.jar"/>

<target name="compile">

<jscomp compilationLevel="simple" warning="verbose" 
        debug="false" output="output/file.js">

  <sources dir="${basedir}/src">
    <file name="js.js"/><!-- the file I'm trying to compile -->
  </sources>

</jscomp>

</target>

</project>

My Jquery library is called min.js and its in the src folder with js.js

I'm sure this is a easy question but I'm just missing something. Thanks in advance!


Solution

  • You need to include the jQuery externs. Each major version of jQuery has its own extern file. You can find them at http://code.google.com/p/closure-compiler/source/browse/#svn%2Ftrunk%2Fcontrib%2Fexterns

    Once you've downloaded the appropriate extern, here's how you would reference it while compiling:

    <?xml version="1.0"?>
    <project basedir="." default="compile">
    
    <taskdef name="jscomp" classname="com.google.javascript.jscomp.ant.CompileTask"
           classpath="build/compiler.jar"/>
    
    <target name="compile">
    
    <jscomp compilationLevel="simple" warning="verbose" 
        debug="false" output="output/file.js">
    
      <sources dir="${basedir}/src">
        <file name="js.js"/><!-- the file I'm trying to compile -->
      </sources>
    
      <externs dir="${basedir}/src">
        <file name="jquery-1.7.js"/>
      </externs>
    </jscomp>
    
    </target>