pirosikick's diary

君のハートにunshift

grunt-useminでライセンス表記を残す

クライアントサイドJavaScriptのライセンス管理 | GREE Engineers' Blog

これを見てgrunt-useminで難読化されたコードを見たらやっぱりライセンス表記まで削除されていた。。orz

で、grunt-license-saverを使おうかなと思ったんだけど、ソース内に@license http://hogehoge.com/license.jsonって追加するのどうしようと思っていたら、下記記事を発見。

grunt.js - UglifyJSで、できるだけライセンスコメントを残して圧縮する - Qiita

uglifyjsならば自分で関数を書いてどのコメントを残すのかの制御が可能とのこと。しかも、grunt-license-saverと同等のものが既にこの記事に書いてある!ありがたい!!

で、grunt-useminはデフォルトだと(たぶん他の使うとかはできないと思うけど)grunt-contrib-uglifyを使って難読化しているので、preserveCommentsオプションがuglifyjsのcommentsオプションと同等のものになる。

// Gruntfile.js

// ここはそのまま上記記事から持ってくる
// see http://qiita.com/shinnn/items/57327006390f2181f550
var licenseRegexp = /^\!|^@preserve|^@cc_on|\bMIT\b|\bMPL\b|\bGPL\b|\(c\)|License|Copyright|three\.js/mi;

var isLicenseComment = (function() {
  var _prevCommentLine = 0;

  return function(node, comment) {
    if (licenseRegexp.test(comment.value) ||
        comment.line === 1 ||
        comment.line === _prevCommentLine + 1) {
      _prevCommentLine = comment.line;
      return true;
    }

    _prevCommentLine = 0;
    return false;
  };
})();

module.exports = function (grunt) {
    // show elapsed time at the end
    require('time-grunt')(grunt);
    // load all grunt tasks
    require('load-grunt-tasks')(grunt);

    grunt.initConfig({

// 略

        // preserveCommentsに上で定義した関数を渡す
        uglify: {
          options: {
            preserveComments: isLicenseComment
          }
        },

// 略

    });
};

新たに発覚した問題

three.jsを使っているのだがソース内にライセンス表記がない。正確に言うと// three.js - http://github.com/mrdoob/three.jsと書いているのだが、上記の正規表現three.jsと書いてもコメントが残らず困っている。。 誰か解決方法を知っていたら教えて下さい。