Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

amd - Is there a way to have RequireJS modules depend on code loaded with <script>?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...