ExtensionAliasPlugin.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const forEachBail = require("./forEachBail");
  7. /** @typedef {import("./Resolver")} Resolver */
  8. /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
  9. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  10. /** @typedef {{ alias: string|string[], extension: string }} ExtensionAliasOption */
  11. module.exports = class ExtensionAliasPlugin {
  12. /**
  13. * @param {string | ResolveStepHook} source source
  14. * @param {ExtensionAliasOption} options options
  15. * @param {string | ResolveStepHook} target target
  16. */
  17. constructor(source, options, target) {
  18. this.source = source;
  19. this.options = options;
  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. const { extension, alias } = this.options;
  29. resolver
  30. .getHook(this.source)
  31. .tapAsync("ExtensionAliasPlugin", (request, resolveContext, callback) => {
  32. const requestPath = request.request;
  33. if (!requestPath || !requestPath.endsWith(extension)) return callback();
  34. const resolve = (alias, callback) => {
  35. resolver.doResolve(
  36. target,
  37. {
  38. ...request,
  39. request: `${requestPath.slice(0, -extension.length)}${alias}`,
  40. fullySpecified: true
  41. },
  42. `aliased from extension alias with mapping '${extension}' to '${alias}'`,
  43. resolveContext,
  44. callback
  45. );
  46. };
  47. const stoppingCallback = (err, result) => {
  48. if (err) return callback(err);
  49. if (result) return callback(null, result);
  50. // Don't allow other aliasing or raw request
  51. return callback(null, null);
  52. };
  53. if (typeof alias === "string") {
  54. resolve(alias, stoppingCallback);
  55. } else if (alias.length > 1) {
  56. forEachBail(alias, resolve, stoppingCallback);
  57. } else {
  58. resolve(alias[0], stoppingCallback);
  59. }
  60. });
  61. }
  62. };