Google的js壓縮與最佳化工具: Getting Started with the Closure Compiler Application

來源:互聯網
上載者:User
文章目錄
  • Next Steps

https://developers.google.com/closure/compiler/docs/gettingstarted_app

 

Getting Started with the Closure Compiler ApplicationThe Hello World of the Closure Compiler Application

The Closure Compiler application is a Java command-line utility that compresses, optimizes, and looks for mistakes in your JavaScript. To try out the Closure Compiler application with a simple JavaScript program, follow the steps below.

To work through this exercise you need the Java Runtime Environment version 6.

  1. Download the Closure Compiler package

    Create a working directory called closure-compiler.

    Download the Closure Compiler compiler.jar file and save it in closure-compiler.

  2. Create a JavaScript file

    Create a file named hello.js containing the following JavaScript:

    // A simple function.
    function hello(longName){
      alert('Hello, '+ longName);
    }
    hello('New User');

    Save this file in the closure-compiler directory.

  3. Compile the JavaScript file

    Run the following command from the closure-compiler directory:

    java -jar compiler.jar --js hello.js --js_output_file hello-compiled.js

    This command creates a new file called hello-compiled.js, which contains the following JavaScript:

    function hello(a){alert("Hello, "+a)}hello("New User");

    Note that the compiler has stripped comments, whitespace and an unnecessary semi-colon. The compiler has also replaced the parameter name longName with the shorter name a. The result is a much smaller JavaScript file.

    To confirm that the compiled JavaScript code still works correctly, include hello-compiled.js in an HTML file like this one:

    <html>
    <head><title>Hello World</title></head>
    <body>
    <scriptsrc="hello-compiled.js"></script>
    </body>
    </html>

    Load the HTML file in a browser, and you should see a friendly greeting!

Next Steps

This example illustrates only the most simple optimizations performed by the Closure Compiler. To learn more about the compiler's capabilities, read Advanced Compilation and Externs.

To learn more about other flags and options for the Closure Compiler, execute the jar with the --help flag:

java -jar compiler.jar --help

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.