2017-04-12 71 views
0

現在我只考慮使用RequireJS和AMD模塊。到目前爲止 - 所有的事情都通過幾個全局變量和自我調用函數進行管理。RequireJS管理大型模塊

例如,我的模塊將如何looke這樣的:

function HugeModule() { 
    //usage = new HugeModule(); 
}; 
HugeModule.prototype.functionX = function() { 
    //Lets say - around 50 functions for HugeModule prototype 
}; 

HugeModule.SubModule = function() { 
    //usage = new HugeModule.SubModule(); 
    //And here could be multiple subModules like this 
}; 
HugeModule.SubModule.prototype.functionX = function() { 
    //Lets say - around 20 functions for HugeModule.SubModule prototype 
}; 

現在我會寫像這樣,我將至少有4檔之間的分裂是:

//HugeModule.js 
var HugeModule = (function() { 
    function HugeModule() { 
     //usage = new HugeModule(); 
    }; 
    return HugeModule; 
})(); 
//HugeModule.somePrototypeFunctions.js 
(function() { 
    HugeModule.prototype.functionX = function() { 
     //Lets say - around 50 functions for HugeModule prototype 
    }; 
})(); 
//HugeModule.SubModule.js 
(function() { 
    HugeModule.SubModule = function() { 
     //usage = new HugeModule.SubModule(); 
     //And here could be multiple subModules like this 
    }; 
})(); 
//HugeModule.SubModule.someOtherPrototypeFunctions.js 
(function() {  
    HugeModule.SubModule.prototype.functionX = function() { 
     //Lets say - around 20 functions for HugeModule.SubModule prototype 
    }; 
})(); 

我會真的很想用AMD模塊和RequireJS編寫這些模塊,我有一個基本的想法應該如何編寫,但我不確定 - 我將如何在多個模塊之間分割它們。

我可以寫這樣的:

define([], function() { 
    function HugeModule() { 
     //usage = new HugeModule(); 
    }; 
    HugeModule.prototype.functionX = function() { 
     //Lets say - around 50 functions for HugeModule prototype 
    }; 
    return HugeModule; 
}); 

,但我想它的多個文件之間的分裂。我不想使用連接文件的構建工具。

我想是一個requirable模塊 - HugeModule,它會解決所有的依賴關係HugeModule.somePrototypeFunctionsHugeModule.SubModule(和這樣就解決了HugeModule.SubModule.someOtherPrototypeFunctions dependencie)

我應該如何解決這個問題?

回答

1

首先一個重要的警告:你所要做的並不能很好地適應ES6的工作方式。如果您要編寫ES6類或使用類似於ES6的類語法編寫語言(例如TypeScript,其類爲ES6 +類型註釋),您將遇到必須解決類語法或遇到轉譯問題。考慮將你的HugeModule重構爲多個小類以避免這些問題。 (請參閱here以獲得關於TypeScript上下文中問題的討論。)

如果上述警告不是問題,則可以通過按以下方式組織代碼來實現目標。我已經成功使用了這種模式多年。

HugeModule.js只是結合了一流的零部件,爲代碼的其餘部分提供了一個門面:

define(["./HugeModuleCore", "./HugeModuleA", "./HugeModuleB"], function (HugeModuleCore) { 
    return HugeModuleCore; 
}); 

HugeModuleCore.js創建類,並創建它的一些「核心」的方法:

define([], function() { 
    function HugeModule() { 
    }; 

    HugeModule.prototype.someCoreFunction = function() { 
    }; 

    return HugeModule; 
}); 

HugeModuleA.js在覈心中增加了一些類別的方法:

define(["./HugeModuleCore"], function (HugeModule) { 
    HugeModule.prototype.someFunction = function() { 
    }; 

    // You don't really need to return anything here. 
}); 

HugeModuleB.js在覈心中增加了一些其他類別的方法:

define(["./HugeModuleCore"], function (HugeModule) { 
    HugeModule.prototype.someOtherFunction = function() { 
    }; 

    // You don't really need to return anything here. 
});