Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack loader equivalent of requirejs plugin load with XMLHttpRequest

I have a pair of requirejs plugins, that I'd like to replace with a webpack loader.

define('firstLoader', {
  load: function (name, parentRequire, onload, config) {
    var xhr = new XMLHttpRequest();
    
    xhr.addEventListener('load', function () {onload(this.responseText);});
    xhr.addEventListener('error', onload.error);
    xhr.addEventListener('abort', onload.error);

    var url = '...' + name;
    xhr.open('GET', url);
    xhr.send()
  }
})

define('jsonLoader', {
  load: function (name, parentRequire, onload, config) {
    //This is the nasty part.
    req(['firstLoader!' + name], function (text) {
      try {
        onload(JSON.parse(text));
      }
      catch (err) {
        onload.error(err);
      }
    })
  }
});

The biggest problems are the lack of promises for the async request and the dynamic require. Is there a way around this without transpilation (with `System.load) or additional libraries (bluebird, etc.)?

Edit

So I've taken a crack at this, and now I'm getting an error

Module not found: Error: Can't resolve 'future/url'

when I go to require('jsonLoader!future/url'). Does webpack allow loaders to operate at runtime? Here's the updated code.

firstPlugin.js

module.exports = function loadAsync (content, callback) {
      var host = document.location.host
      var url = host + '...' + name
      xhr.addEventListener("load", function () {callback(null, this.responseText)})
      xhr.open("GET", url)
      xhr.send()
    }
}

jsonPlugin.js

module.exports = function (content, callback) {
  require('firstPlugin!' + content, function (result) {
      callback(null, JSON.parse(result))
  })
}
like image 943
wegry Avatar asked Mar 14 '16 20:03

wegry


Video Answer


1 Answers

Require and Webpack are just fundamentally different patterns. They both relate to 'modules' and 'loading', but otherwise...

In general, Webpack is purely a compile/build-time tool. So, no, its loaders can't operate at runtime. However, Webpack can create multiple bundles at build-time, which you can call/download separately at runtime. Depending on how you want to call those additional bundles (from inside a module, or from a particular 'page') the Webpack concepts you're interested in are Code Splitting and Entry Points.

like image 56
XML Avatar answered Sep 29 '22 23:09

XML