Jeśli masz do czynienia tylko z przeglądarki (nie node.js), to tylko kilka linii, aby wsparcie biblioteki zarówno AMD i non-AMD.
Na przykład here is the file from jQuery that does it, z których wszystkie, ale cztery są komentarze:
// Execute the factory to produce jQuery
var jQuery = factory(window);
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if (typeof define === "function" && define.amd) {
define("jquery", [], function() {
return jQuery;
});
}
I bardzo podobny fragment z Knockout można znaleźć here:
} else if (typeof define === 'function' && define['amd']) {
// [2] AMD anonymous module
define(['exports'], factory);
}
Należy pamiętać, że jQuery przyjmuje podejście named module a nokaut używa anonimowego modułu. jQuery również pozostawia $
i jQuery
w globalnej przestrzeni nazw, even when AMD is detected, natomiast Knockout (i prawdopodobnie wiele innych) robi , a nie umieszcza cokolwiek w globalnej przestrzeni nazw po wykryciu AMD. Są plusy i minusy każdego podejścia, co ilustruje poniższe pytania:
See [wspierające zarówno CommonJS i AMD] (http://stackoverflow.com/questions/ 13673346/support-both-commonjs-and-amd), a także kod źródłowy wielu popularnych bibliotek, takich jak jQuery i Knockout, które obsługują zarówno AMD, jak i nie AMD – explunit
UMD, wygląda na to, że próbuje naprawić każdy przypadek, dodając wiele złożoności . Czy istnieje najlepsza praktyka, która jest prostsza i bardziej elastyczna? –