var path = require('path');
var fs = require('fs');
var vm = require('vm');
var os = require('os');
/**
* 格式化缩进的个数
*/
function toindent(indent) {
var s = [];
for (var i = 0; i < indent; i) {
s.push('\t');
}
return s.join('');
}
/**
* 将数组对象转换成原始字符串
*/
function array2string(arr, indent) {
var s = ['[', os.eol], hasprop = false;
for (var i = 0; i < arr.length; i) {
if (!hasprop) {
hasprop = true;
}
s.push(toindent(indent 1));
var item = arr[i];
var itemtp = typeof(item);
if (itemtp === 'object') {
if (item instanceof array) {
s.push(array2string(item, indent 1));
} else {
s.splice(s.length - 2, 2);
s.push(object2strng(item, indent).trim());
}
} else {
s.push(json.stringify(item));
}
s.push(',');
s.push(os.eol);
}
if (hasprop) {
s.splice(s.length - 2, 1);
}
s.push(toindent(indent));
s.push(']');
return s.join('');
}
/**
* 将对象转换成原始字符串
*/
function object2strng(obj, indent) {
var s = ['{', os.eol], hasprop = false;
for (var o in obj) {
if (!hasprop) {
hasprop = true;
}
s.push(toindent(indent 1));
s.push(json.stringify(o));
s.push(':');
var tp = typeof(obj[o]);
if (tp === 'object') {
if (obj[o] instanceof array) {
s.push(array2string(obj[o], indent 1));
} else {
s.push(object2strng(obj[o], indent 1));
}
} else if (tp === 'function') {
s.push(obj[o].tostring());
} else {
s.push(json.stringify(obj[o]));
}
s.push(',');
s.push(os.eol);
}
if (hasprop) {
s.splice(s.length - 2, 1);
}
s.push(toindent(indent));
s.push('}');
return s.join('');
}
//提取正式代码里的requirejs的配置字符串,并动态执行转换成json对象; 修改相关的值信息为下边的打包操作做准备; 并将配置信息再转成字符串形式写到临时文件下
var mainpath = path.resolve(process.cwd(), '../js/main.js');
var maincontent = fs.readfilesync(mainpath, 'utf-8').replace(/(requirejs\.config\()?([^)]]*)(\);)?/gm, '$2');
vm.runinthiscontext('var maincfg= ' maincontent);//将提取的字符串转成maincfg对象
maincfg.baseurl = '/static/js/dist/lib';
var nmaincfgstr = 'requirejs.config(' object2strng(maincfg, 0) ');';//重新生成main.js配置文件,为下边的打包做准备
var buildpath = path.resolve(process.cwd(), './main.js');
fs.writefilesync(buildpath, nmaincfgstr);
console.log('write temp file main.js fininshed');
//打包的配置信息
var buildjson = {
appdir: '../js',
baseurl: 'lib',
mainconfigfile: './main.js',
dir: '../js/dist',
modules: [{
'name': '../main',
include: []
}]
};
for (var p in maincfg.paths) {//这里提取所有的依赖模块,打包时放到main.js文件下
buildjson.modules[0].include.push(p);
}
var buildpath = path.resolve(process.cwd(), './build_main.json');
fs.writefilesync(buildpath, object2strng(buildjson, 0));//生成打包配置文件
console.log('wirte temp file build_main.json fininshed');
写一批处理文件build.bat
@echo off
node build.js
node r.js -o build_main.json
@pause
执行就可以了
posted on 2016-11-01 16:24
simone 阅读(3745)
评论(0) 编辑 收藏 所属分类:
nodejs