Can I use an ES6/2015 module import to set a reference in 'global' scope?

前端 未结 6 1161
温柔的废话
温柔的废话 2021-01-31 03:22

I have this situation where I am trying to import an existing library, which I\'ll call troublesome (using Webpack/Babel FWIW) and it has a global reference to

6条回答
  •  北海茫月
    2021-01-31 03:46

    I've had a similar issue using jspm and dygraphs. The way i solved it was to use dynamic loading like you attempted using System.import but the important part was to chain-load each consecutive "part" using System.import again inside the promise onfulfillment handler (then) after setting the global namespace variable. In my scenario I actually had to have several import steps separated between then handlers.

    The reason it didn't work with jspm, and probably why it didn't work for you as well is that the import ... from ... syntax is evaluated before any code, and definitely before System.import which of async.

    In your case it could be as simple as:

    import jQuery from 'jquery';
    
    window.jQuery = jQuery;
    System.import('troublesome').then(troublesome => {
     // Do something with it...
    });
    

    Also note that the System module loader recommendation has been left out of the final ES6 specification, and a new loader spec is being drafted.

提交回复
热议问题