如何使用 requirejs 覆盖供应商库

How to override a vendor library with requirejs

我使用 Marionette.js 框架,我需要重写 Marionette.TemplateCache 模块的一个函数,但不更新 marionette.js 文件。 所以,我为此创建了一个新模块:

    define(['marionette'], function (Marionette) {
    'use strict';

    _.extend(Marionette.TemplateCache.prototype, {
        loadTemplate: function(templateId){

            var template = templateId;

            if (!template || template.length === 0){
                throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
            }

            return template;
        }
    });
    return Marionette;
});

但是,我不知道如何配置我的 requirejs main,因为当我加载 Marionette.js 框架时,我的模块会覆盖 Marionette.js.

你知道怎么做吗?

谢谢。

乔纳森。

您可以将为原始库定义的路径重命名为类似 marionette-core 的路径,并按如下方式更新您的模块

define(['marionette-core'], function (Marionette) {
'use strict';

   _.extend(Marionette.TemplateCache.prototype, {
    loadTemplate: function(templateId){

        var template = templateId;

        if (!template || template.length === 0){
            throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
        }

        return template;
    }
  });

  return Marionette;
});

现在将模块的路径定义为 marionette

所以现在当您需要 marionette 时,require.js 将加载原始 marionette 和 return 您的自定义实例。

此外,如有必要,您仍然可以使用 marionette-core 在其他地方加载原始库