FileExistsPlugin.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./Resolver")} Resolver */
  7. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  8. module.exports = class FileExistsPlugin {
  9. /**
  10. * @param {string | ResolveStepHook} source source
  11. * @param {string | ResolveStepHook} target target
  12. */
  13. constructor(source, target) {
  14. this.source = source;
  15. this.target = target;
  16. }
  17. /**
  18. * @param {Resolver} resolver the resolver
  19. * @returns {void}
  20. */
  21. apply(resolver) {
  22. const target = resolver.ensureHook(this.target);
  23. const fs = resolver.fileSystem;
  24. resolver
  25. .getHook(this.source)
  26. .tapAsync("FileExistsPlugin", (request, resolveContext, callback) => {
  27. const file = request.path;
  28. if (!file) return callback();
  29. fs.stat(file, (err, stat) => {
  30. // Combine the two miss branches: a stat failure and a
  31. // "not a file" result share the same handling — record the
  32. // path on `missingDependencies`, log the right reason, then
  33. // bail. The error-message ternary picks the wording that
  34. // matched the failing condition.
  35. if (err || !stat || !stat.isFile()) {
  36. if (resolveContext.missingDependencies) {
  37. resolveContext.missingDependencies.add(file);
  38. }
  39. if (resolveContext.log) {
  40. resolveContext.log(
  41. err || !stat
  42. ? `${file} doesn't exist`
  43. : `${file} is not a file`,
  44. );
  45. }
  46. return callback();
  47. }
  48. if (resolveContext.fileDependencies) {
  49. resolveContext.fileDependencies.add(file);
  50. }
  51. resolver.doResolve(
  52. target,
  53. request,
  54. `existing file: ${file}`,
  55. resolveContext,
  56. callback,
  57. );
  58. });
  59. });
  60. }
  61. };