Skip to content

Instantly share code, notes, and snippets.

@sunnylost
Created August 19, 2014 10:39
Show Gist options
  • Save sunnylost/47525e34fde3c7e1c42b to your computer and use it in GitHub Desktop.
Save sunnylost/47525e34fde3c7e1c42b to your computer and use it in GitHub Desktop.
Build.js
var fs = require('fs'),
through = require('through2'),
uglify = require('uglify-js');
var BASE = './script-ss/',
DEST = './script-min/',
SPECIAL_TAG = '/*common*/';
var modules = [];
function r(module) {
modules.push("'" + module + "'");
return {};
}
/**
* 转换旧的 AMD 格式代码
*/
function transform(file) {
var that = this;
if(!file.indexOf(SPECIAL_TAG)) {
var path = that._readableState.pipes.path;
moduleName = path.replace(DEST, '').replace('.js', '');
var lines = file.split(/\n/g),
prefix = '',
suffix = '});',
rrequire = /\brequire\b/,
rcomma = /,/g;
lines.forEach(function(line) {
if(rrequire.test(line)) {
try {
(new Function('require', line.replace(rcomma, ';')))(r);
} catch(e) {
console.log('----- ERROR -----');
console.log(line);
}
}
});
prefix = 'fml.define("' + moduleName + '", [' + modules.join(',') + '], function(require, exports) {';
modules.length = 0;
file = prefix + lines.join('\n') + suffix;
}
this.push(file);
}
function compress(file) {
if(file) {
try {
this.push(uglify.minify(file, {
fromString: true
}).code);
} catch(e) {
//console.log(e)
}
}
}
function read(base) {
fs.readdir(base, function(err, files) {
if(err) return console.error(err);
files.forEach(function(file) {
var path = base + file,
stat = fs.statSync(path),
dest = path.replace(BASE, DEST);
if(stat.isDirectory()) {
fs.existsSync(dest) || fs.mkdirSync(dest);
read(path + '/');
} else {
var rs = fs.createReadStream(path);
rs.setEncoding('utf-8');
rs.pipe(through.obj(transform))
//.pipe(through.obj(compress))
.pipe(fs.createWriteStream(dest));
}
})
});
}
read(BASE);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment