Search code examples
javascriptbrowserrequirejsamd

Expose AMD module globally when not in a RequireJS environment


I am attempting to convert a classic JavaScript "class" into an AMD module. However, I also need to keep exporting the class into the global namespace because some legacy code needs it. I've tried this, however, the global object is not created. What am I doing wrong?

define('VisitorManager', function () {

    var VisitorManager = function () {

        "use strict";

        // ...
    };


    VisitorManager.prototype.hasExistingChat = function () {
        // ...
    };


    //expose globally
    this.VisitorManager = VisitorManager;

    //return AMD module
    return VisitorManager;

});

Solution

  • To expose your module globally, you need to register it in the global object.

    In the browser the global object is window:

    window.VisitorManager = VisitorManager;
    

    In a Node.js environment the global object is called GLOBAL:

    GLOBAL.VisitorManager = VisitorManager;
    

    To use the class in both a legacy environment and with RequireJS, you can use this trick:

    (function() {
    
        var module = function() {
    
            var VisitorManager = function() {
                "use strict";
    
                // ...
            };
    
            // Return the class as an AMD module.
            return VisitorManager;
        };
    
        if (typeof define === "function" && typeof require === "function") {
            // If we are in a RequireJS environment, register the module.
            define('VisitorManager', module);
        } else {
            // Otherwise, register it globally.
            // This registers the class itself:
            window.VisitorManager = module();
    
            // If you want to great a global *instance* of the class, use this:
            // window.VisitorManager = new (module())();
        }
    
    })();