如何在没有RequireJS的页面中编写AMD模块?

gsk*_*lee 10 javascript amd requirejs

我需要重新构建一个现有的AMD模块,使其可以在有/不带RequireJS的页面中使用.我该怎么做,是否有任何示例代码?优选地,它将是一种不污染全局命名空间的方式,尽管不是严格的要求.

Sim*_*ith 7

这根本不是一个坏主意,通常需要JS库来支持AMD /非AMD环境.以下是解决方案的一种变体:

!function (name, definition) {
    if (typeof module != 'undefined') module.exports = definition()
    else if (typeof define == 'function' && define.amd) define(name, definition)
    else this[name] = definition()
}('reqwest', function () {

    // Module here

});
Run Code Online (Sandbox Code Playgroud)

唯一的缺点是你不能请求其他依赖项,所以这只适用于独立的库,如下所示