how does webpack import from external url

后端 未结 1 1436
星月不相逢
星月不相逢 2021-01-04 12:10

I am using webpack to manage my react application. Now I want to import a dependency from this url:



        
相关标签:
1条回答
  • 2021-01-04 12:47

    In the future you should be able to use dynamic requires via System.import. Webpack 2 will support them natively.

    System.import('<url>')
      .then(function() {
        console.log('Loaded!');
      });
    

    If you don't want to wait for it, you could use a script loading library.

    Example:

    Install:

    npm install little-loader --save
    

    Use:

    import load from 'little-loader';
    
    load('<url>', function(err){
    
    })
    

    Or do it manually

    function load(url) {
      return new Promise(function(resolve, reject) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.src = url;
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      })
    }
    
    load('<url>')
      .then(function() {
        console.log('Loaded!');
      })
      .catch(function(err) {
        console.error('Something went wrong!', err);
      })
    
    0 讨论(0)
提交回复
热议问题