RequireJS 管理大型模块

RequireJS managing large modules

直到现在我才考虑使用 RequireJS 和 AMD 模块。 到目前为止 - 所有的事情都是通过几个全局变量和自调用函数来管理的。

例如,我的模块的外观:

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;
});

但我想将其拆分为多个文件。我不想使用连接文件的构建工具。

我想要的是一个必需的模块 - HugeModule,它将解决 HugeModule.somePrototypeFunctionsHugeModule.SubModule 的所有依赖关系(这将解决 HugeModule.SubModule.someOtherPrototypeFunctions)

我该如何解决?

首先是一个重要的警告:您尝试做的事情并不适合 ES6 classes 的工作方式。如果您要编写 ES6 classes 或使用具有类似于 ES6 的 class 语法的语言编写(例如,TypeScript 具有 classes 是 ES6 + 类型注释) ,您将 运行 不得不解决 class 语法或 运行 转译问题。考虑将您的 HugeModule 重构为多个较小的 class 以避免这些问题。 (有关 TypeScript 上下文中问题的讨论,请参阅 here。)

如果上面的警告不是问题,您可以通过像下面这样组织代码来实现您的目标。我已成功使用此模式多年。

HugeModule.js 只是组合了 class 的部分,并为其余代码提供了外观:

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

HugeModuleCore.js 创建 class 并在其上创建一些 "core" 方法:

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.
});