トップページ >
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の使い方を説明します。
目次:
Closure Compiler Service APIへのリクエストは、下記のURLへ送信してください。
手はじめに、formを使ってAPIサーバへリクエストを送るアプリケーションを作成してみます。Closure Compiler Service APIをformから呼出すのは実際の利用方法としてはやや不自然ですが、HTTP-POSTによる通信の様子を確認するにはこのやり方が最も簡単です。
<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つです。
function hello(name){alert("Hello, "+name)}hello(){"New user"};
次に、プログラムが直にHTTP通信を行うサンプルプログラムを示します:
#!/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'
alert("hello");
このスクリプトについて、注意すべき点をいくつか挙げておきます。
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
上の例ではコマンドライン引数として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に渡すより、ファイル名を指定するだけの方が便利です。それには以下のようにします:
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'),
])
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種類の制限が設けられています。
クライアントがAPIに送信するPOSTデータのサイズは200,000バイト以内でなければなりません。この制限を超過した場合はサーバエラー
8:POST data too large.
が返却されます。
もし
js_code
パラメータで送信しているソースコードの量が多い場合は、ファイルに分離した上でそれを
code_url
パラメータで参照するようにしてください。
APIが1回のリクエストで処理できるコードの総量は1,024,000バイトとされています。ここでいうコードの総量とは、 code_url 及び externs_url に指定された全てのファイル内のコード、 js_code 及び js_externs に指定された全てのコード文字列の合計を指します。 この制限を超過した場合はサーバエラー 9:File too large. が返却されます。
このエラーが発生する場合は、ローカルマシン上でのClosure Compiler Applicationの使用を検討してください。