ModulesInHierarchicalDirectoriesPlugin.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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").ResolveStepHook} ResolveStepHook */
  10. module.exports = class ModulesInHierarchicalDirectoriesPlugin {
  11. /**
  12. * @param {string | ResolveStepHook} source source
  13. * @param {string | Array<string>} directories directories
  14. * @param {string | ResolveStepHook} target target
  15. */
  16. constructor(source, directories, target) {
  17. this.source = source;
  18. this.directories = /** @type {Array<string>} */ ([]).concat(directories);
  19. this.target = target;
  20. }
  21. /**
  22. * @param {Resolver} resolver the resolver
  23. * @returns {void}
  24. */
  25. apply(resolver) {
  26. const target = resolver.ensureHook(this.target);
  27. resolver
  28. .getHook(this.source)
  29. .tapAsync(
  30. "ModulesInHierarchicalDirectoriesPlugin",
  31. (request, resolveContext, callback) => {
  32. const fs = resolver.fileSystem;
  33. const addrs = getPaths(request.path)
  34. .paths.map(p => {
  35. return this.directories.map(d => resolver.join(p, d));
  36. })
  37. .reduce((array, p) => {
  38. array.push.apply(array, p);
  39. return array;
  40. }, []);
  41. forEachBail(
  42. addrs,
  43. (addr, callback) => {
  44. fs.stat(addr, (err, stat) => {
  45. if (!err && stat && stat.isDirectory()) {
  46. const obj = {
  47. ...request,
  48. path: addr,
  49. request: "./" + request.request,
  50. module: false
  51. };
  52. const message = "looking for modules in " + addr;
  53. return resolver.doResolve(
  54. target,
  55. obj,
  56. message,
  57. resolveContext,
  58. callback
  59. );
  60. }
  61. if (resolveContext.log)
  62. resolveContext.log(
  63. addr + " doesn't exist or is not a directory"
  64. );
  65. if (resolveContext.missingDependencies)
  66. resolveContext.missingDependencies.add(addr);
  67. return callback();
  68. });
  69. },
  70. callback
  71. );
  72. }
  73. );
  74. }
  75. };