How do I use Google Closure compiler to remove unused JavaScript code?

有些话、适合烂在心里 提交于 2019-12-04 03:28:43

There are two ways to remove/exclude unused code from your combined output script:

  • The first, involves using ADVANCED_OPTIMIZATIONS compilation level (refer to Advanced Compilation and Externs for detailed explanation and usage)
  • The second, is to allow the compiler to manage dependencies (i.e. using the --manage_closure_dependencies compilation flag

Of the two options, using the --manage_closure_dependencies flag to remove unused code is less granular (i.e. excludes code at a file level), but it does allow you to remain at SIMPLE_OPTIMIZATIONS compilation level. In either case, you will have to include the url to jQuery and jQueryUI scripts and your code that consumes the jQuery Slider from your page-something like this (1st option):

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @code_url http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js
// @code_url http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.js
// ==/ClosureCompiler==

// ADD YOUR CODE HERE

Hope this helps.

First as a beginner I suggest you try simple optimization. Because it works without any configuration and yields great results. Don't be mislead by the name. Simple optimization offers better savings than any other compression tool out there. Advanced level can be your next step but it's a little more complicated.

As for using the compiler. My advice is to pack all your scripts into one javascript file, upload it to your website so it will have an url, pass it to the online complier. Then you click Add and Compile and you're done.

In the right hand side the compiled code you'll see. Also a file named default.js will be created and you can downloaded.

Next step is to rename it to your needs, then upload to your server, change the .js reference in the HTML and you're pretty much done. Have fun!

Closure Compiler's ADVANCED_OPTIMIZATION currently isn't capable of pulling apart jQuery. jQuery efforts to minimize itself using clever runtime expansion, various aliasing, and function serving different purposes depending on the parameters passed all work together to make jQuery opaque to the compiler. That said, proper Closure Compiler ADVANCED_OPTIMIZATION support is high on the jQuery teams wish-list for jQuery 1.8.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!