loadLoader.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var LoaderLoadingError = require("./LoaderLoadingError");
  2. var url;
  3. module.exports = function loadLoader(loader, callback) {
  4. if(loader.type === "module") {
  5. try {
  6. if(url === undefined) url = require("url");
  7. var loaderUrl = url.pathToFileURL(loader.path);
  8. var modulePromise = eval("import(" + JSON.stringify(loaderUrl.toString()) + ")");
  9. modulePromise.then(function(module) {
  10. handleResult(loader, module, callback);
  11. }, callback);
  12. return;
  13. } catch(e) {
  14. callback(e);
  15. }
  16. } else {
  17. try {
  18. var module = require(loader.path);
  19. } catch(e) {
  20. // it is possible for node to choke on a require if the FD descriptor
  21. // limit has been reached. give it a chance to recover.
  22. if(e instanceof Error && e.code === "EMFILE") {
  23. var retry = loadLoader.bind(null, loader, callback);
  24. if(typeof setImmediate === "function") {
  25. // node >= 0.9.0
  26. return setImmediate(retry);
  27. } else {
  28. // node < 0.9.0
  29. return process.nextTick(retry);
  30. }
  31. }
  32. return callback(e);
  33. }
  34. return handleResult(loader, module, callback);
  35. }
  36. };
  37. function handleResult(loader, module, callback) {
  38. if(typeof module !== "function" && typeof module !== "object") {
  39. return callback(new LoaderLoadingError(
  40. "Module '" + loader.path + "' is not a loader (export function or es6 module)"
  41. ));
  42. }
  43. loader.normal = typeof module === "function" ? module : module.default;
  44. loader.pitch = module.pitch;
  45. loader.raw = module.raw;
  46. if(typeof loader.normal !== "function" && typeof loader.pitch !== "function") {
  47. return callback(new LoaderLoadingError(
  48. "Module '" + loader.path + "' is not a loader (must have normal or pitch function)"
  49. ));
  50. }
  51. callback();
  52. }