如果專案有自己的一套模塊加載約定,那麼打包工具其實並不難寫:掃描入口檔、正則抓出依賴、遞歸合併、最後可選壓縮。這裡記錄一版能用但青澀的實作。
先定義好代碼裡模塊聲明的樣子,打包工具才有東西可掃:
複製代碼 代碼如下:
XX.define('ns',['tool/cookie'],function(){
});
//或者
XX.define('ns.ns2','tool/cookie,tool/abc',function(){
})
//或者
XX.define('ns',function(){
})
工具的做法是:讀檔 → 去掉 BOM 頭 → 用正則匹配出依賴清單 → 先遞歸打包依賴 → 再拼上當前檔案內容。用一個 packagedObj 對象記錄已處理路徑,避免循環依賴導致的無限遞歸與重複輸出。
複製代碼 代碼如下:
//通用模塊
var Util = require('util'),
FS = require('fs'),
getDeps = require('./getDeps'),
Uglify = require('./uglify/uglify-js'),
removeBOMChar = require('./removeBOM').removeBOMChar,
PATH =require('path');
var packagedObj = {};//是否已經打包過
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)){
//異步讀取內容
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;
}
//返回內容
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);
}
}
readFileSync 是為了邏輯簡單,打包是一次性任務,同步反而更好讀。作者自己也坦言,Node 是邊查文檔邊寫的,代碼還很青澀。真要在生產環境使用,起碼還得補上:循環依賴檢測、快取失效、並行讀檔,以及一套正經的單元測試。但它作為「打包工具到底在做什麼」的最小可讀範例,是足夠的。