用nodejs寫的一個簡單項目打包工具
更新時間:2013年05月11日 17:02:54 作者:
項目是模塊加載的,類似require.js的用法,所以簡單寫了一個js打包工具
項目的模塊加載和定義部分代碼是這樣的:
復制代碼 代碼如下:
XX.define('ns',['tool/cookie'],function(){
});
//或者
XX.define('ns.ns2','tool/cookie,tool/abc',function(){
})
//或者
XX.define('ns',function(){
})
所用到的js打包工具就是掃描文件,然后匹配出來需要加載的模塊,然后先加載模塊代碼。
主要的nodejs打包工具代碼如下:
復制代碼 代碼如下:
//通用模塊
var Util = require('util'),
FS = require('fs'),
getDeps = require('./getDeps'),
Uglify = require('./uglify/uglify-js'),
removeBOMChar = require('./removeBOM').removeBOMChar,
PATH =require('path');
var packagedObj = {};//是否已經(jīng)打包過
module.exports = function(filePath, rootPath, opts){
opts = opts || {};
var str = jscombo(filePath,rootPath);
if(opts.unzip){
return str;
}else{
return Uglify(str);
}
};
function jscombo(filePaths, rootPath){
if(Util.isArray(filePaths)){
return filePaths.map(function(filePath){
filePath = PATH.join(rootPath,filePath);
//只打包一次
if(packagedObj[filePath]){
return '';
}
packagedObj[filePath] = 1;
//是否存在
if(FS.existsSync(filePath)){
//異步讀取內(nèi)容
var str = FS.readFileSync(filePath, 'utf-8');
//移出BOM頭
str = removeBOMChar(str);
var result = getDeps(str, rootPath);
var content = result.content;
content = '//'+filePath+'\n'+content;
//遞歸打包
if(result.list){
return jscombo(result.list, rootPath) + content;
}
//返回內(nèi)容
return content;
}else{
//文件不存在錯誤信息
console.error('jsCombo Error: ' + filePath + ' does not exsist! the path is:'+rootPath);
return ';alert("' + filePath + ' does not exsist!");';
}
}).join(';\n');
}else{
return jscombo([filePaths],rootPath);
}
}
對于nodejs之前一直沒認真學習,都是邊查文檔,編寫的,所以代碼很青澀~
相關(guān)文章
JS中JSON.parse(JSON.stringify())實現(xiàn)深拷貝
深拷貝就是完全拷貝一份新的對象,本文主要介紹了JS中JSON.parse(JSON.stringify())實現(xiàn)深拷貝,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-08-08json-lib出現(xiàn)There is a cycle in the hierarchy解決辦法
如果需要解析的數(shù)據(jù)間存在級聯(lián)關(guān)系,而互相嵌套引用,在hibernate中極容易嵌套而拋出net.sf.json.JSONException: There is a cycle in the hierarchy異常。2010-02-02