Last active
June 12, 2016 12:22
-
-
Save allbinmani/a5bf161ee213551f25a7d64a723279b8 to your computer and use it in GitHub Desktop.
Grunt task to replace file names for require-statements with shorter names, reducing final file size slighty.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Grunt task to replace file names for require-statements with shorter names | |
* reducing final file size slighty. | |
* | |
* (C) 2016 mattias@allbinary, All Binary AB | |
* | |
* Example configuration: | |
* shortify_js: { | |
* build: { | |
* options: { | |
* prefix: '' // use a prefix for filenames | |
* }, | |
* files: [ | |
* {expand: true, cwd: 'build/js/', src: 'app.js', dest: './'}, | |
* ] | |
* } | |
* } | |
*/ | |
grunt.registerMultiTask('shortify_js', function() { | |
var pfx = this.data && this.data.options ? this.data.options.prefix || '' : ''; | |
function shortify(str) { | |
var requires = {}; | |
var nn = 0; | |
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
function allocName() { | |
return pfx + (chars[ ((nn++)%chars.length) ] + (nn > chars.length ? (Math.floor(nn/chars.length)) : '')); | |
} | |
str.replace(/require\(([^\)]*)/g, function(a,b) { | |
b = b.replace(/['"]/g, ''); // un-quote | |
if(typeof requires[b] === 'undefined') { | |
requires[b] = allocName(); | |
} | |
}); | |
var keys = Object.keys(requires); | |
keys.filter(function(r) { | |
// require('xyz'); | |
var re1 = new RegExp("require\\('"+r+"'", 'g'); | |
str = str.replace(re1, "require('"+requires[r]+"'"); | |
// require("xyz"); | |
var re2 = new RegExp('require\\("'+r+'"', 'g'); | |
str = str.replace(re2, 'require("'+requires[r]+'"'); | |
// "xyz":<num> | |
var re3 = new RegExp('"'+r+'":([0-9]*)', 'g'); | |
str = str.replace(re3, '"'+requires[r]+'":$1'); | |
}); | |
return str; | |
} | |
var files = this.files; | |
for(var i=0; i < files.length; i++) { | |
var file = files[i]; | |
var content = grunt.file.read(file.src[0], { encoding: null }).toString(); | |
var len1 = content.length; | |
var res = shortify(content); | |
grunt.file.write(file.dest, res.content); | |
var saved = len1 - res.length; | |
grunt.log.writeln('wrote ' + file.dest + ' from ' + file.src[0] + ', saving ' + saved + ' bytes'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment