dackdive's blog

新米webエンジニアによる技術ブログ。JavaScript(React), Salesforce, Python など

Google Closure CompilerとかGoogle Closure LibraryなどのClosure Tools概要まとめ

Google Closure ○○ シリーズが多くてわからん、となったのでメモ。
主に Closure Compiler と Closure Library を中心に。

総称として Closure Tools と呼ぶらしいです。ここにまとまってます。

またソースコードはすべて GitHub で公開されている模様。

https://github.com/google?utf8=%E2%9C%93&q=closure&type=&language=

Google Closure Compiler

The Closure Compiler is a tool for making JavaScript download and run faster. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.

JS の型チェックや圧縮、最適化などをやってくれるコンパイラ
半角スペースなどを取り除いたり変数名を省略することで JS を圧縮してくれるのに加え、JSDoc 形式のアノテーションを記述するとコンパイル時に型のチェックなども行ってくれます。

GitHub

https://github.com/google/closure-compiler

インストール方法

いくつか選択肢がある。
(参考: https://developers.google.com/closure/compiler/https://github.com/google/closure-compiler/ の Getting Started)

  1. Java アプリ (.jar) として提供されているものをダウンロードして使う (最新版のダウンロードリンクはこちら)
  2. web アプリが https://closure-compiler.appspot.com/home にあるので、コンパイルしたいコードを貼り付けて web 上でコンパイルする
  3. REST API として提供されているものを使う (参考)
  4. npm パッケージとして提供されているものを使う https://www.npmjs.com/package/google-closure-compiler

その他、Maven のプラグインもある らしいがよくわからない。

使い方

ここでは、4 の npm パッケージを使うものとして進めます。

$ npm install google-closure-compiler

素の ./node_modules/.bin/google-closure-compiler を叩いてもいいですが、オプションとして渡すパラメータもあるので npm script を書いておきます。

"scripts": {
  "build": "google-closure-compiler --js=main.js --js_output_file=build.js"
}

--jsコンパイル対象のファイル、 --js_output_fileコンパイル後の出力先を指定します。

サンプルとなるファイルを書いてみます。

サンプル1 (単純な例)

function hello() {
  alert('hello');
}

結果1 (コンパイル後の JS)

function hello(){alert("hello")};

サンプル2 (アノテーションによる型チェック)

/** @const {number}**/
var foo = 100;

foo = 200;

/** @define {string} **/
var greeting = 'hello';

greeting = 100;

結果2 (ビルド実行時の様子)

$ npm run build
main.js:4: WARNING - constant foo assigned a value more than once.
Original definition at main.js:2
foo = 200;
^^^^^^^^^

main.js:9: WARNING - constant greeting assigned a value more than once.
Original definition at main.js:7
greeting = 100;
^^^^^^^^^^^^^^

0 error(s), 2 warning(s)

error と warning の違いはわかってません。


リファレンス

Google Closure Library

The Closure Library is a broad, well-tested, modular, and cross-browser JavaScript library. You can pull just what you need from a large set of reusable UI widgets and controls, and from lower-level utilities for DOM manipulation, server communication, animation, data structures, unit testing, rich-text editing, and more.

DOM 操作のための API やら豊富な UI コンポーネントやらが含まれているライブラリ。
APIhttps://google.github.io/closure-library/api/ に一覧が載っているが多すぎて全容を把握できない。


GitHub

https://github.com/google/closure-library


インストール方法

GitHub の README を見る限り、こちらも npm でインストールできるようです。

$ npm install google-closure-library


使い方

先ほど npm でインストールできるといったものの、 require() で読み込めるようにするには何らかのビルドツールと組み合わせて使う方法があり、かつ closure compiler でコンパイルする方法がまだよくわかっていないため
リポジトリを手動でクローンしたものを使ってサンプルを書いてみます。

ここの通り。
Getting Started with the Closure Library  |  Closure Library  |  Google Developers

$ git clone https://github.com/google/closure-library

JS (hello.js)

goog.require('goog.dom');
goog.require('goog.dom.TagName');

function sayHi() {
  var newHeader = goog.dom.createDom(goog.dom.TagName.H1, {'style': 'background-color:#EEE'},
    'Hello world!');
  goog.dom.appendChild(document.body, newHeader);
}

HTML

<html>
  <head>
    <script src="closure-library/closure/goog/base.js"></script>
    <script src="hello.js"></script>
  </head>
  <body onload="sayHi()">
  </body>
</html>

結果

f:id:dackdive:20181126165452p:plain

goog.require() で必要なモジュールをインポートして使うのが基本らしい。
注意点として、 goog.require() は指定したモジュールを読み込むための <script> タグをドキュメントに挿入するという挙動になっているので、 goog.require() してるスクリプトとインポートしたモジュールを使用するスクリプトを同じスクリプト内で実行してはいけない。

<script src="closure-library/closure/goog/base.js"></script>
<script>
  // DON'T DO THIS.
  goog.require('goog.dom');
  var newHeader = goog.dom.createDom(goog.dom.TagName.H1);
</script>


リファレンス

Google Closure Templates

Closure Templates is a client-side and server-side templating system used to build dynamic and reusable HTML and UI elements. (中略) It supports Java and JavaScript and uses a language-neutral expression syntax and data model.

テンプレートエンジン。JavaJavaScript もサポートしているとな。


GitHub

https://github.com/google/closure-templates


インストール方法

GitHub の README を見ると、これも npm で提供されてるようです。
https://www.npmjs.com/package/google-closure-templates

ただし上の2つと異なり Getting Started には npm でのインストール方法は記載されていなかったので、標準の導入方法ではない...?


使い方

クライアント側のサンプルとして、
Hello World Using JavaScript  |  Closure Templates  |  Google Developers
を読んでみます。

※なお、サイトから各リンクをクリックすると軒並み 404 になるので、GitHub の README に記載されてるリンクを開いた方がいいです

Closure Library のときと同じく、npm パッケージは使わず
https://dl.google.com/closure-templates/closure-templates-for-javascript-latest.zip から最新版の closure-templates をダウンロードしてそれを使います。

テンプレートファイルの拡張子は .soy らしい。

simple.soy

{namespace examples.simple}

/**
 * Says hello to the world.
 */
{template .helloWorld}
  Hello world!
{/template}

こいつをダウンロードした zip に入っている SoyToJsSrcCompiler.jar というファイルでコンパイルすると JS ファイルが生成されるらしい。

$ java -jar SoyToJsSrcCompiler.jar --outputPathFormat simple.js --srcs simple.soy

これを読み込む HTML ファイル側は

<!DOCTYPE html>
<html>
<head>
  <title>The Hello Wolrd of Closure Templates</title>
  <script src="soyutils.js"></script>
  <script src="simple.js"></script>
</head>
<body>
  <script type="text/javascript">
    // Exercise the .helloWorld template
    document.write(examples.simple.helloWorld());
  </script>
</body>
</html>

結果

f:id:dackdive:20181126183132p:plain


Google Closure Linter

しょっぱなに Closure Linter is deprecated と書いてあるのでスルー。

https://github.com/google/closure-linter

Please note that the closure linter is deprecated. Esp. if you use ES6 features, the tool will not work for you.

Google Closure Stylesheets

CSS を拡張した言語。
公式リファレンスサイトはなく GitHubリポジトリに飛ばされる。


GitHub

https://github.com/google/closure-stylesheets


インストール方法・使い方

jar ファイルをダウンロードしてくる方式。
時間の都合上試してない。

おまけ: ClosureBuilder

これは調べてる過程で発見したもので、上に挙げた Closure Library に含まれるツールの一部っぽいです。
Closure Library のリポジトリ内に closure/bin/build/closurebuilder.py というスクリプトがあります。

The closurebuilder.py tool, located in closure/bin/build, is a tool to help build compiled JavaScript files. It scans your files and the Closure Library files and can calculate orderings of script files in dependency order. It can output either the scripts' filenames or their contents in dependency order, or can pass the files along to the Closure Compiler to produce a compiled version.

JS のコンパイル? Closure Compiler もあるのに?という感じもしますがよくわからない。
むしろ Closure Compiler と併用する場合の実行方法とかまで書かれている。

まとめとよくわからないこと

とりあえず一通り手を動かして試してみました。ソースはここに置いておきます。
https://github.com/zaki-yama/google-closure-tools-sample

各ツールの概要はわかったけど一歩踏み込んだ使い方とかはまだまだですね。

以下、今回だけではわからなかったこと: