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

后端 未结 2 2020
攒了一身酷
攒了一身酷 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:29

    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}
    

提交回复
热议问题