ModulesInHierarchicalDirectoriesPlugin.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const forEachBail = require("./forEachBail");
  7. const getPaths = require("./getPaths");
  8. /** @typedef {import("./Resolver")} Resolver */
  9. /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
  10. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  11. module.exports = class ModulesInHierarchicalDirectoriesPlugin {
  12. /**
  13. * @param {string | ResolveStepHook} source source
  14. * @param {string | Array<string>} directories directories
  15. * @param {string | ResolveStepHook} target target
  16. */
  17. constructor(source, directories, target) {
  18. this.source = source;
  19. this.directories = /** @type {Array<string>} */ ([]).concat(directories);
  20. this.target = target;
  21. }
  22. /**
  23. * @param {Resolver} resolver the resolver
  24. * @returns {void}
  25. */
  26. apply(resolver) {
  27. const target = resolver.ensureHook(this.target);
  28. resolver
  29. .getHook(this.source)
  30. .tapAsync(
  31. "ModulesInHierarchicalDirectoriesPlugin",
  32. (request, resolveContext, callback) => {
  33. const fs = resolver.fileSystem;
  34. const addrs = getPaths(/** @type {string} */ (request.path))
  35. .paths.map(p => {
  36. return this.directories.map(d => resolver.join(p, d));
  37. })
  38. .reduce((array, p) => {
  39. array.push.apply(array, p);
  40. return array;
  41. }, []);
  42. forEachBail(
  43. addrs,
  44. /**
  45. * @param {string} addr addr
  46. * @param {(err?: null|Error, result?: null|ResolveRequest) => void} callback callback
  47. * @returns {void}
  48. */
  49. (addr, callback) => {
  50. fs.stat(addr, (err, stat) => {
  51. if (!err && stat && stat.isDirectory()) {
  52. /** @type {ResolveRequest} */
  53. const obj = {
  54. ...request,
  55. path: addr,
  56. request: "./" + request.request,
  57. module: false
  58. };
  59. const message = "looking for modules in " + addr;
  60. return resolver.doResolve(
  61. target,
  62. obj,
  63. message,
  64. resolveContext,
  65. callback
  66. );
  67. }
  68. if (resolveContext.log)
  69. resolveContext.log(
  70. addr + " doesn't exist or is not a directory"
  71. );
  72. if (resolveContext.missingDependencies)
  73. resolveContext.missingDependencies.add(addr);
  74. return callback();
  75. });
  76. },
  77. callback
  78. );
  79. }
  80. );
  81. }
  82. };