Google Closure Compilerとは
Google Closure Compiler はJavaScriptコードの圧縮を行うツールです。もともとはJavaで実装されていたものですが、今回それをNodeやJavascriptで実行できるようにコンパイルしたとのこと。
This isn’t a rewrite of Closure in JavaScript. Instead, we compile the Java source to JS to run under Node, or even inside a plain old browser.
https://developers.googleblog.com/2016/08/closure-compiler-in-javascript.html より
インストール手順
npmに登録されているので以下のコマンドでインストールできます
| 1 | npm install --save google-closure-compiler | 
Gruntの設定
Gruntを使ってClosure Compilerを実行してみます。
まずはgrunt-cliのインストール
| 1 | npm install -g grunt-cli | 
次にプロジェクトにGruntをインストール
| 1 | npm install -save grunt | 
次にGruntfile.jsを作成します。ファイルの中身は以下。public/javascripts/default.jsに書かれているファイルを圧縮してpublic/javascripts/default.min.jsに保存するように記述されています。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | module.exports = function(grunt) {     require('google-closure-compiler').grunt(grunt);     grunt.initConfig({         'closure-compiler': {             my_target: {                 files: {                     'public/javascripts/default.min.js': ['public/javascripts/default.js']                 },                 options: {                     compilation_level: 'SIMPLE',                     language_in: 'ECMASCRIPT5_STRICT',                     create_source_map: 'dest/output.min.js.map',                     output_wrapper: '(function(){\n%output%\n}).call(this)\n//# sourceMappingURL=output.min.js.map'                 }             }         }     });     grunt.registerTask('default', ['closure-compiler']); }; | 
Gruntを実行する
以下のコマンドでGruntを実行します。
| 1 | grunt | 
元となるJavaScriptソース
| 1 2 3 4 5 6 7 8 9 | (function($){     $(function(){         $('.button-collapse').sideNav();         $('.parallax').parallax();         //$(".activator").bind("load", function () { $(this).fadeIn(); });     }); // end of document ready })(jQuery); // end of jQuery name space | 
Google Closure Compiler 実行後に生成されたファイル
| 1 2 3 4 | (function(){ (function(a){a(function(){a(".button-collapse").sideNav();a(".parallax").parallax()})})(jQuery); }).call(this) //# sourceMappingURL=output.min.js.map | 
(パーサーとしては)不要な改行が削除されていることがわかります。
npmで導入できるので手軽で良いですね。