Skip to content

Instantly share code, notes, and snippets.

@shinnn
Created December 11, 2013 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinnn/7914727 to your computer and use it in GitHub Desktop.
Save shinnn/7914727 to your computer and use it in GitHub Desktop.
UglifyJSで、できるだけライセンスコメントを残して圧縮する ref: http://qiita.com/shinnn/items/57327006390f2181f550
var isLicenseComment = (function() {
// ライセンスコメントかどうか判定する正規表現
var licenseRegexp = /^\!|^@preserve|^@cc_on|\bMIT\b|\bMPL\b|\bGPL\b|\(c\)|License|Copyright/mi;
// 直前にライセンスコメントが現れた行を保存する内部変数
var _prevCommentLine = 0;
// 実際に`comment`オプションで実行されるのはこの関数
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;
};
})();
"use strict";
var UglifyJS = require("uglify-js");
var licenseRegexp = /^\!|^@preserve|^@cc_on|\bMIT\b|\bMPL\b|\bGPL\b|\(c\)|License|Copyright/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;
};
})();
var minified = UglifyJS.minify("file.js", {
output: {
comments: isLicenseComment
}
}).code;
console.log(minified);
// example.js
// (c) John Smith | MIT License
// http://examplelibrary.com/
// anonymous function
(function(win, doc){
var string = 'Hello World! :' + doc.title;
// output greeting message
console.log(string);
}(window, document));
// example.js
// (c) John Smith | MIT License
// http://examplelibrary.com/
!function(o,l){var n="Hello World! :"+l.title;console.log(n)}(window,document);
'use strict'
module.exports = (grunt) ->
grunt.loadNpmTasks 'grunt-contrib-uglify'
grunt.loadNpmTasks 'grunt-contrib-concat'
grunt.loadNpmTasks 'grunt-contrib-clean'
licenseRegexp = /^\!|^@preserve|^@cc_on|\bMIT\b|\bMPL\b|\bGPL\b|\(c\)|License|Copyright/mi
isLicenseComment = do ->
_prevCommentLine = 0
(node, comment) ->
if licenseRegexp.test(comment.value) or
comment.line is 1 or
comment.line is _prevCommentLine + 1
_prevCommentLine = comment.line
return true
_prevCommentLine = 0
false
grunt.initConfig
uglify:
target:
options:
preserveComments: isLicenseComment
files: [
expand: true
flatten: true
cwd: 'path/to/src'
src: ["**/*.js"]
dest: 'tmp/'
]
concat:
script:
src: ['tmp/*.js']
dest: 'path/to/build/app.js'
clean:
tmpfiles: ['tmp']
grunt.registerTask 'default' [
'uglify'
'concat'
'clean'
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment