How do I export a global variable from Require.js?

后端 未结 2 2022
攒了一身酷
攒了一身酷 2020-12-06 07:07

I\'m trying to make an external library using Require.js. Thanks to Require.js not compiling single js file correctly and Require.js (almond.js) Timing Off I\'ve figured ou

2条回答
  •  执笔经年
    2020-12-06 07:37

    Calls to require() are async, meaning the return value of the function that you pass as argument is not returned by require() itself. Your issue could be solved in different ways, the RequireJS way is defining your code in a module and requiring it as a dependency:

    // mymodule.js
    define([], function() {
        window.Foo = {someValue: 1};
        return {someValue: 2};
    });
    
    // main.js
    require(['mymodule'], function (mymodule) {
        console.log(window.Foo); // {someValue: 1}
        console.log(mymodule); // {someValue: 2}
    });
    

提交回复
热议问题