AliasPlugin.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. /** @typedef {string | string[] | false} Alias */
  9. /** @typedef {{ alias: Alias, name: string, onlyModule?: boolean }} AliasOption */
  10. const { aliasResolveHandler, compileAliasOptions } = require("./AliasUtils");
  11. /**
  12. * When `alias` is given as an array, the targets are tried in priority
  13. * order and the first matching one wins. Tried-and-failed higher-priority
  14. * targets are recorded on `resolveContext.missingDependencies` (via the
  15. * downstream `FileExistsPlugin`) so that a consumer's watcher can
  16. * invalidate the resolve once one of them appears. The winning target is
  17. * recorded on `resolveContext.fileDependencies`; its removal triggers
  18. * re-resolution, at which point the fallback target is returned.
  19. *
  20. * Callers that cache successful resolves (e.g. webpack's `unsafeCache`)
  21. * are responsible for invalidating those entries when the tracked
  22. * dependencies change -- otherwise a stale path may survive across
  23. * rebuilds even though this plugin itself would return the correct
  24. * fallback on a fresh resolve.
  25. */
  26. module.exports = class AliasPlugin {
  27. /**
  28. * @param {string | ResolveStepHook} source source
  29. * @param {AliasOption | AliasOption[]} options options
  30. * @param {string | ResolveStepHook} target target
  31. */
  32. constructor(source, options, target) {
  33. this.source = source;
  34. this.options = Array.isArray(options) ? options : [options];
  35. this.target = target;
  36. }
  37. /**
  38. * @param {Resolver} resolver the resolver
  39. * @returns {void}
  40. */
  41. apply(resolver) {
  42. const target = resolver.ensureHook(this.target);
  43. const compiled = compileAliasOptions(resolver, this.options);
  44. resolver
  45. .getHook(this.source)
  46. .tapAsync("AliasPlugin", (request, resolveContext, callback) => {
  47. aliasResolveHandler(
  48. resolver,
  49. compiled,
  50. target,
  51. request,
  52. resolveContext,
  53. callback,
  54. );
  55. });
  56. }
  57. };