Use AMD defined module within 3rd party, non-AMD library

泪湿孤枕 提交于 2019-12-24 02:13:12

问题


I have a library - call it SomeLib - which is defined to support various module loaders:

(function(global, factory) {
    if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory();
    } else {
        global.UriTemplate = factory();
    }
})(this, function() {
   ...
   // returns constructor function
});

I can easily load it with RequireJS like

require.config({
  paths: {
    'theLibrary: '../path/to/the/lib'
  }
});

Then I have another 3rd-party library - call it AnotherLib - which internally uses SomeLib like

var the Lib = new SomeLib(...);

That means SomeLib has to be available globally.

AnotherLib is just a plain JavaScript module function

(function(){
  // the code
})();

It is not compliant with particular module loaders.

When I include AnotherLib with RequireJS, I do something like

require.config({
  paths: {
    'theLibrary: '../path/to/the/lib',
    'anotherLib: '../path/to/anotherLib'
  },
  shim: {
     'anotherLib: [
        'theLibrary'
     ]
  }
});

The problem is that I get a undefined exception on the line within AnotherLib where it instantiates SomeLib (new SomeLib(...)). This is because SomeLib is not defined on the global object but rather published as an AMD module which AnotherLib doesn't "require".

Can I solve this somehow, or does AnotherLib have to be AMD compliant and properly require SomeLib.


回答1:


The best thing would be to get an AMD-compliant library or to make the library AMD compliant. The latter option would entail modifying the source manually or having a build step that turns the non-AMD-compliant code into a real AMD module. How to do this depends on how the library is designed.

An method that would work with any library is to deliberately leak the symbol that the library requires into the global space:

  1. Make anotherLib be dependent on a new module, which you could call SomeLib-leak.

  2. Create the new module. This definition does not have to be in a separate file. I usually place such "glue" modules before my call to require.config. The module would be like this:

    define('SomeLib-leak', ['SomeLib'], function (SomeLib) {
        window.SomeLib = SomeLib;
    });
    

    I do purposely have define set the module name here. Usually, you don't want to call have define set the module name but for "glue" modules that are placed like I indicated above, this is necessary.

By the time anotherLib is loaded, SomeLibrary will be in the global space.



来源:https://stackoverflow.com/questions/27154030/use-amd-defined-module-within-3rd-party-non-amd-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!