当不在RequireJS环境中时,全局暴露AMD模块

Expose AMD module globally when not in a RequireJS environment

本文关键字:全局 暴露 AMD 模块 RequireJS 环境      更新时间:2023-09-26

我正在尝试将经典JavaScript "类"转换为AMD模块。但是,我还需要继续将类导出到全局名称空间,因为一些遗留代码需要它。我尝试过this,但是全局对象没有创建。我做错了什么?

define('VisitorManager', function () {
    var VisitorManager = function () {
        "use strict";
        // ...
    };

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

    //expose globally
    this.VisitorManager = VisitorManager;
    //return AMD module
    return VisitorManager;
});

要全局公开你的模块,你需要在全局对象中注册它。

在浏览器中,全局对象是window:

window.VisitorManager = VisitorManager;

在Node.js环境中,全局对象被称为GLOBAL:

GLOBAL.VisitorManager = VisitorManager;

要在遗留环境和RequireJS中使用该类,您可以使用以下技巧:

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