Is there a way to have RequireJS modules depend on

2019-01-29 04:15发布

问题:

I am in a project where we are in the process of developing a widget system. I will try not to go into too much detail about this, but in this system widgets must be able to specify its dependencies. We have accomplished this by allowing widgets to specify its 3rd party dependencies using RequireJS.

Widgets are used in in-house developed apps. These apps do not use RequireJS for their own dependencies, they merely include RequireJS for the sake of the widgets.

Now, let's say that I have a widget that wants to use the library X. X is a library that specifies an AMD dependency on jQuery (the AMD module jquery). Now, jQuery is included in every in-house developed app (it's a core part of our apps), so this shouldn't be a problem. However, since jQuery is not loaded via RequireJS (it's loaded manually via a script tag before RequireJS is included), the AMD module is never registered, and library X fails to load because it can't find the jquery module.

How do I make library X find the AMD module jquery, even though jQuery is not loaded using RequireJS? I suspect using RequireJS shims (http://requirejs.org/docs/api.html#config-shim) in some way can resolve this, but I have not figured out how yet. Any help is greatly appreciated.

回答1:

The way to do it is like this:

define('jquery', [], function () {
    return jQuery;
});

This just takes the jQuery normally loaded through script and makes it available as a RequireJS module

The same principle also works with any other library loaded before RequireJS and which exports itself as a symbol in the global space: just create a fake module for it that merely returns the symbol the library exports in the global space.

You could put that code in a separate file called jquery.js and have the define be define([], function () { (without the module name) but I don't see much benefit to doing that. I prefer to call define with the module name as in my first snippet above and put the definition just before my call to require.config.



标签: requirejs amd