loadLoader.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. "use strict";
  2. const LoaderLoadingError = require("./LoaderLoadingError");
  3. let url;
  4. function handleResult(loader, module, callback) {
  5. if (typeof module !== "function" && typeof module !== "object") {
  6. return callback(
  7. new LoaderLoadingError(
  8. `Module '${loader.path}' is not a loader (export function or es6 module)`
  9. )
  10. );
  11. }
  12. loader.normal = typeof module === "function" ? module : module.default;
  13. loader.pitch = module.pitch;
  14. loader.raw = module.raw;
  15. if (
  16. typeof loader.normal !== "function" &&
  17. typeof loader.pitch !== "function"
  18. ) {
  19. return callback(
  20. new LoaderLoadingError(
  21. `Module '${loader.path}' is not a loader (must have normal or pitch function)`
  22. )
  23. );
  24. }
  25. callback();
  26. }
  27. function loadLoader(loader, callback) {
  28. if (loader.type === "module") {
  29. try {
  30. if (url === undefined) url = require("url");
  31. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  32. const loaderUrl = url.pathToFileURL(loader.path);
  33. // Use `eval` so older parsers (and the main module resolver) don't
  34. // need to recognize the dynamic `import()` syntax at load time.
  35. // eslint-disable-next-line no-eval
  36. const modulePromise = eval(
  37. `import(${JSON.stringify(loaderUrl.toString())})`
  38. );
  39. modulePromise.then((module) => {
  40. handleResult(loader, module, callback);
  41. }, callback);
  42. } catch (err) {
  43. callback(err);
  44. }
  45. return;
  46. }
  47. let loadedModule;
  48. try {
  49. loadedModule = require(loader.path);
  50. } catch (err) {
  51. // It is possible for node to choke on a require if the FD descriptor
  52. // limit has been reached. Give it a chance to recover by deferring.
  53. if (err instanceof Error && err.code === "EMFILE") {
  54. return setImmediate(loadLoader, loader, callback);
  55. }
  56. return callback(err);
  57. }
  58. return handleResult(loader, loadedModule, callback);
  59. }
  60. module.exports = loadLoader;