简体   繁体   中英

Google Closure Compiler Service is giving invalid code

I am using Closure Compiler at https://closure-compiler.appspot.com/ to obfuscate/minfy my JS code, but there goes something wrong. I set up a page with a script to recreate the problem.

My HTML5 code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>title</title>
    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js">
    </script>
  </head>
  <body>
    <p>text</p>    
    <script src="script.js"></script>
  </body>
</html>

My JS code:

$("p").text("val changed");
$("p").velocity({left: 60},{duration: 2000});

That code is working, no errors. Then I want to minify/obfuscate it, so I go to https://closure-compiler.appspot.com

I include the url's of jQuery and Velocity.js and set the optimization to advanced.

Code:

// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// @code_url http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js
// @code_url http://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js
// ==/ClosureCompiler==

$("p").text("val changed");
$("p").velocity({left: 60},{duration: 2000});

Then I wait a few seconds till it is compiled, then a long block of code is generated and I copy it into script.min.js. After that I change my HTML document slightly:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>title</title>
  </head>
  <body>
    <p>text</p>    
    <script src="script.min.js"></script>
  </body>
</html>

Then I open the my HTML page and I get the following error:

Uncaught ReferenceError: $ is not defined

But... I included the jQuery and Velocity.js libraries and they are also compiled. What have I done wrong?

Please help my, it's important.

Thanks in advance!

Make sure you read Which Compilation Level is Right For Me?

In short, ADVANCED_OPTIMIZATIONS can only be used with libraries that support it. The jQuery source does not (you have to use it with externs).

You should be using SIMPLE_OPTIMIZATIONS level which is roughly equivalent to other compressing compilers like UglifyJS and is safe for most code.

SIMPLE_OPTIMIZATIONS will rename variables that are not in the global scope. If you wrap your code in an anonymous function, you'll see this behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM