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

你说的曾经没有我的故事 提交于 2019-11-28 11:34:23

问题


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.



来源:https://stackoverflow.com/questions/27845705/is-there-a-way-to-have-requirejs-modules-depend-on-code-loaded-with-script

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