How to find out if AMD javascript library supports

So, I began to learn how to use requirejs and combine it with some other javascript libraries available. As far as I understand, you need to pin all libraries that do not correspond to compatibility with the asynchronous module (AMD) , but in addition to searching in the library code for "require", is there an easier way to find out which libraries support AMD and which do not? As an example, I know that jquery supports AMD, but jqueryui does not, and I only know this because "someone told me."

+7
javascript amd
source share
2 answers

This is how jQuery announces its AMD. This is just a bunch of if statements. If libraries do not have library.AMD === true , then there is no way to check it from the library itself.

 if ( typeof module === "object" && module && typeof module.exports === "object" ) { module.exports = jQuery; } else { window.jQuery = window.$ = jQuery; if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } 

However, there is a way to check already loaded modules. This answer says that you can check require.s.contexts._.defined , which is an object containing a mapping of names and already loaded modules.

For example, if I loaded jQuery (which AMD has by default) on a page that also has RequireJS, the jquery property will exist in this object and contain the same jQuery object as the global one. Then you can compare. The following will return true :

 require.s.contexts._.defined.jquery === jQuery require.s.contexts._.defined.jquery === $ 

However, this assumes that you know the name of the module and / or is global for comparison. This may not work in all cases. For example, the jQuery user interface is not just one big piece of code. This is a bunch of plugins hosted under jquery-ui.js . There is a possibility that either they can be called collectively, or a module for each widget. The jQuery user interface does not even have a global one.

+3
source share

You will look for the format AMD define() calls in the sources, where they usually come in three flavors:

  • The AMD module is not defined, where you need to configure the gasket in RequireJS;
  • Additional AMD support, where there is usually some sniffing for define() dependencies in the globals below;
  • AMD's top-notch module where everything is wrapped when define() called.

It's nice to note that you will get an error if you mistakenly try to fake an AMD module, or load a script as an AMD module that never calls define() to create it.

+2
source share

All Articles