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

不打扰是莪最后的温柔 提交于 2019-11-27 23:10:06

If you follow James' instructions here, you can easily produce a library designed as a bundle of RequireJS modules that someone can load synchronously.

I've got a github repository illustrating the whole thing. The salient points:

  • The main module exports Foo to the global space:

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

    It also returns a value that is exported by the start fragment as Bar (that's the line that says root.Bar = factory();). So it illustrates two ways to export to the global space.

  • The wrapper code used by r.js starts main with the synchronous form of require:

    require(`main`);
    

If you load it, you'll see the following output:

outside
loaded modC
inside
out in the HTML!
value of window.Foo: Object {someValue: 1}
value of window.Bar: Object {someValue: 2}

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}
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!