Closure Compilerを使う!

Closure Compiler Service API

最終更新:

aias-closurecompiler

- view
管理者のみ編集可

トップページ >

Closure Compiler Service API

Closure Compiler Service APIはClosure Compilerの機能をWeb-APIとして提供します。この方式ではユーザプログラムは直接APIサーバとHTTP-POST通信を行い、処理結果を受け取れるようになります。

Closure Compiler Service UIは短いコードを使ってCompilerを試してみる分にはとても良いアプリケーションです。しかしあなたがJavaScriptのコンパイルプロセスを自動化したいと考えていたり、あるいはコンパイル処理を(IDEの拡張機能のようなかたちで)ビルドプロセスの一部として組み込みたいと考えているのであれば、Closure Compiler Service APIの利用は検討する価値があります。

以下では簡単なアプリケーションを作成しながら、何段階かに分けてAPIの使い方を説明します。

目次:

APIサーバのURL

Closure Compiler Service APIへのリクエストは、下記のURLへ送信してください。

最も単純なサンプルアプリケーション

手はじめに、formを使ってAPIサーバへリクエストを送るアプリケーションを作成してみます。Closure Compiler Service APIをformから呼出すのは実際の利用方法としてはやや不自然ですが、HTTP-POSTによる通信の様子を確認するにはこのやり方が最も簡単です。

  1. 下のHTMLをコピーペーストして closure_compiler_test.html というファイルを作成してください。

     <html>
     <body>
       <form action="http://closure-compiler.appspot.com/compile" method="POST">
       <p>Type JavaScript code to optimize here:</p>
       <textarea name="js_code" cols="50" rows="5">
       function hello(name) {
         // Greets the user
         alert('Hello, ' + name);
       }
       hello('New user');
       </textarea>
       <input type="hidden" name="compilation_level" value="WHITESPACE_ONLY">
       <input type="hidden" name="output_format" value="text">
       <input type="hidden" name="output_info" value="compiled_code">
       <br><br>
       <input type="submit" value="Optimize">
       </form>
     </body>
     </html>

    上のformでは4つの必須パラメータが設定されています。(各パラメータの詳細はこちらを参照してください)中でも重要なのは次の2つです。

    • js_code

      処理対象となるJavaScriptコードを指定します。このようにコード文字列を直接送信する方法の他に、JSファイルのURLから入力コードを指定することもできます。後者についてはこちらで詳しく説明します。

    • compilation_level

      コンパイルレベルを指定します。この例では最も圧縮率の低い WHITESPACE_ONLY が設定されていますが、より強力にコードの短縮を行いたいのであれば、 SIMPLE_OPTIMIZATIONS ADVANCED_OPTIMIZATIONS を試してみてください。

  2. closure_compiler_test.html をブラウザで開きます。
  3. Optimize ボタンをクリックしコードをClosure Compiler Service APIへ送ると、下のようなコードがAPIサーバから返却されてくるはずです。返却されるコードはオリジナルコードからコメントと空白・改行を削除したもので、機能はオリジナルと同じですがサイズはかなり小さくなっています:

    function hello(name){alert("Hello, "+name)}hello(){"New user"};

APIとの通信

次に、プログラムが直にHTTP通信を行うサンプルプログラムを示します:

  • 以下のサンプルはPythonで記述されています。ただし構造自体はごく単純ですので、理解するのにPythonの言語的な知識は特に必要ありません。
#!/usr/bin/python2.4


import httplib, urllib, sys


# Define the parameters for the POST request and encode them in
# a URL-safe format.

params = urllib.urlencode([
    ('js_code', sys.argv[1]),
    ('compilation_level', 'WHITESPACE_ONLY'),
    ('output_format', 'text'),
    ('output_info', 'compiled_code'),
  ])


# Always use the following value for the Content-type header.

headers = { "Content-type": "application/x-www-form-urlencoded" }
conn = httplib.HTTPConnection('closure-compiler.appspot.com')
conn.request('POST', '/compile', params, headers)
response = conn.getresponse()
data = response.read()
print data
conn.close

このスクリプトはコマンドライン引数として渡されたJavaScriptをコンパイルし、処理されたコードを出力します。上のコードをコピーペーストして compile.py というファイル名で保存、ファイルのパーミッションを変更して実行権限を付与した後、以下のコマンドを実行してください。

$ python compile.py 'alert("hello");// This comment should be stripped'

  • 注意: Windows環境でこのプログラムを実行するには、Pythonのインストールが必要です。詳細はこちらを参照してください。
    コマンドはAPIから返却されたコンパイル済みコードを出力します。このサンプルでは WHITESPACE_ONLY レベルが設定されているので、Compilerはコメントを取り除く以外は何もしません。

    alert("hello");

このスクリプトについて、注意すべき点をいくつか挙げておきます。

  • HTTPConnection オブジェクトの request メソッドに渡されるパラメータは、 urllib.urlencode によって事前に全てURLエンコードされています。変数 params の値は次のような文字列です:

    js_code=alert%28%22hello%22%29%3B%2F%2F+This+comment+should+be+stripped&output_info=compiled_code&out=text&compilation_level=WHITESPACE_ONLY

  • リクエストの Content-type ヘッダは常に application/x-www-form-urlencoded でなければなりません。

JavaScriptファイルをAPIに渡すには

上の例ではコマンドライン引数としてJavaScript文字列をプログラムに渡していました。しかし実業務で使われるJavaScriptコード(その長さは2、3行などすぐに超えてしまうでしょう)を扱うには、この方式はやや無理が有るように思われます。このようなケースでは、 code_url パラメータを使って処理したいJavaScriptファイルのURLを指定するのがよいでしょう。

例として、次のJavaScriptプログラムを取り上げます:

/**
 * A simple script for adding a list of notes to a page. The list diplays
 * the text of each note under its title.
 */


/**
 * Creates the DOM structure for a note and adds it to the document.
 */

function makeNoteDom(noteTitle, noteContent, noteContainer) {


  // Create DOM structure to represent the note.

  var headerElement = document.createElement('div');
  var headerText = document.createTextNode(noteTitle);
  headerElement.appendChild(headerText);

  var contentElement = document.createElement('div');
  var contentText = document.createTextNode(noteContent);
  contentElement.appendChild(contentText);

  var newNote = document.createElement('div');
  newNote.appendChild(headerElement);
  newNote.appendChild(contentElement);


  // Add the note's DOM structure to the document.

  noteContainer.appendChild(newNote);
}


/**
 * Iterates over a list of note data objects and creates a DOM
 */

function makeNotes(data, noteContainer) {
  for (var i = 0; i < data.length; i++) {
    makeNoteDom(data[i].title, data[i].content, noteContainer);
  }
}

function main() {
  var noteData = [
    {title: 'Note 1', content: 'Content of Note 1'},
    {title: 'Note 2', content: 'Content of Note 2'}];
  var noteListElement = document.getElementById('notes');
  makeNotes(noteData, noteListElement);
}

main();

このプログラムをひとかたまりの大きな文字列としてAPIに渡すより、ファイル名を指定するだけの方が便利です。それには以下のようにします:

  1. 上のコードをファイルに保存します。
  2. そのファイルをWEBからアクセス可能な場所(あなたのWebサーバなど)に置きます。
  3. APIとの通信で作ったデモを修正し、 js_code code_url に置き換えます。

    params = urllib.urlencode([
        ('code_url', sys.argv[1]), # <--- This parameter has a new name!
        ('compilation_level', 'WHITESPACE_ONLY'),
        ('output_format', 'text'),
        ('output_info', 'compiled_code'),
      ])

  4. 以下のコマンドを実行すると、 http://example.com/yourJs.js というURLがClosure Compilerに渡されます。Compilerは指定されたURLからファイルを取得してコンパイルし、その結果を返却します。

    $ python compile.py http://example.com/yourJs.js

1つのリクエストの中に複数の code_url パラメータを含めることができます:

params = urllib.urlencode([
    ('code_url', http://example.com/yourJsPart1.js),
    ('code_url', http://example.com/yourJsPart2.js),
    ('compilation_level', 'WHITESPACE_ONLY'),
    ('output_format', 'text'),
    ('output_info', 'compiled_code'),
  ])

ファイルは指定順に結合されてから、1つのコードとしてコンパイルされます。尚、 code_url js_code も1つのリクエスト内で同時に使用できます。

データサイズの制限

Closure Compiler Service APIに送信できるデータのサイズには、以下の2種類の制限が設けられています。

  • POSTデータのサイズの合計は200,000バイトまで

    クライアントがAPIに送信するPOSTデータのサイズは200,000バイト以内でなければなりません。この制限を超過した場合はサーバエラー 8:POST data too large. が返却されます。
    もし js_code パラメータで送信しているソースコードの量が多い場合は、ファイルに分離した上でそれを code_url パラメータで参照するようにしてください。

  • コードの総量は1,024,000バイトまで

    APIが1回のリクエストで処理できるコードの総量は1,024,000バイトとされています。ここでいうコードの総量とは、 code_url 及び externs_url に指定された全てのファイル内のコード、 js_code 及び js_externs に指定された全てのコード文字列の合計を指します。 この制限を超過した場合はサーバエラー 9:File too large. が返却されます。

    このエラーが発生する場合は、ローカルマシン上でのClosure Compiler Applicationの使用を検討してください。


目安箱バナー