Search code examples
javascriptrequirejsamd

How to write an AMD module for use in pages without RequireJS?


I need to re-structure an existing AMD module to make it both usable by pages with/without RequireJS presented. How should I do it, and is there any example code? Preferably, it would be a way without polluting the global namespace, though not a strict requirement.


Solution

  • This is not a bad idea at all, quite often JS libs are required to support a AMD/non AMD environment. Here is one variation of the solution:

    !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
    
    });
    

    The only downside is you can't request other dependencies, so this would only be useful in stand alone libraries, like the ones below