[Grunt & Yeoman] grunt-contrib-uglify で JavaScript ファイルの結合・難読化・圧縮をする
grunt-contrib-uglify で、JavaScript を minify する。
[markdown]
> * [gruntjs/grunt-contrib-uglify · GitHub](https://github.com/gruntjs/grunt-contrib-uglify)
## インストール
“`prettyprinted
% npm install grunt-contrib-uglify –save-dev
“`
## Gruntfile
下記で、タブインデント・改行を除き、難読化する。
grunt.initConfig の一部のみ抜粋。
“`
banner: ‘/*! <%= pkg.name %> <%= pkg.version %>\n’+
‘<%= grunt.template.today("yyyy-mm-dd HH:MM:ss Z") %> */\n’
# grunt-contrib-uglify
uglify:
options:
banner: ‘<%= banner %>‘
build:
files: [
src: ‘<%= pkg.path.src %>/javascripts/*.js’,
dest: ‘<%= pkg.path.dist %>/javascripts/<%= pkg.name %>.min.js’
]
“`
また、入力に複数ファイルを指定、出力を1ファイルにすることで、結合もできる。
### banner
ファイルの始めにコメントを追加する(上記の通り)。
“`
/*! gruntSample 0.0.1
2013-11-25 13:47:57 GMT+0900 */
“`
### mangle
変数を短いものに変えてくれるよう。
#### false
“`
function hoge(){“use strict”;var foo=” hoge fuga”;console.log(foo)}
“`
#### true
“`
function hoge(){“use strict”;var a=” hoge fuga”;console.log(a)}
“`
### compress
冗長になっている書き方を短くまとめてくれるよう。
#### false
“`
/*! gruntSample 0.0.1
2013-11-25 13:51:56 GMT+0900 */
$(function() {
$(“#back-to-top”).hide();
$(window).scroll(function() {
if ($(this).scrollTop() > 60) {
$(“#back-to-top”).fadeIn();
} else {
$(“#back-to-top”).fadeOut();
}
});
$(“#back-to-top a”).click(function() {
$(“body,html”).animate({
scrollTop: 0
}, 500);
return false;
});
});
function hoge() {
“use strict”;
var foo = ” hoge fuga”;
console.log(foo);
}
hoge();
“`
#### true
“`
/*! gruntSample 0.0.1
2013-11-25 13:47:57 GMT+0900 */
function hoge() {
“use strict”;
var foo = ” hoge fuga”;
console.log(foo);
}
$(function() {
$(“#back-to-top”).hide(), $(window).scroll(function() {
$(this).scrollTop() > 60 ? $(“#back-to-top”).fadeIn() : $(“#back-to-top”).fadeOut();
}), $(“#back-to-top a”).click(function() {
return $(“body,html”).animate({
scrollTop: 0
}, 500), !1;
});
}), hoge();
“`
### beautify
上記のように、読みやすい形式に改行・インデントを付けて整形する。
### report
ファイルを minify, gzip した場合のサイズを教えてくれる。
“`
options:
report: ‘gzip’
“`
“`
% grunt uglify
Running “uglify:build” (uglify) task
File “./dist/javascripts/gruntSample.min.js” created.
Original: 609 bytes.
Minified: 377 bytes.
Gzipped: 137 bytes.
Done, without errors.
“`
gzip などへのarchive化は、別途 grunt-contrib-compress を使う。
> * [gruntjs/grunt-contrib-compress · GitHub](https://github.com/gruntjs/grunt-contrib-compress)
> * [Grunt: JavaScript や CSS を gzip する | deadwood](https://www.d-wood.com/blog/2013/12/03_5071.html)
### sourceMap
sourceMap を利用する場合のオプションもある。
> * [ファールス: Source Maps を使ってみた](http://mohsenreza.blogspot.jp/2012/03/source-maps.html)
[/markdown]