AliasFieldPlugin.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const DescriptionFileUtils = require("./DescriptionFileUtils");
  7. const getInnerRequest = require("./getInnerRequest");
  8. module.exports = class AliasFieldPlugin {
  9. constructor(source, field, target) {
  10. this.source = source;
  11. this.field = field;
  12. this.target = target;
  13. }
  14. apply(resolver) {
  15. const target = resolver.ensureHook(this.target);
  16. resolver
  17. .getHook(this.source)
  18. .tapAsync("AliasFieldPlugin", (request, resolveContext, callback) => {
  19. if (!request.descriptionFileData) return callback();
  20. const innerRequest = getInnerRequest(resolver, request);
  21. if (!innerRequest) return callback();
  22. const fieldData = DescriptionFileUtils.getField(
  23. request.descriptionFileData,
  24. this.field
  25. );
  26. if (typeof fieldData !== "object") {
  27. if (resolveContext.log)
  28. resolveContext.log(
  29. "Field '" +
  30. this.field +
  31. "' doesn't contain a valid alias configuration"
  32. );
  33. return callback();
  34. }
  35. const data1 = fieldData[innerRequest];
  36. const data2 = fieldData[innerRequest.replace(/^\.\//, "")];
  37. const data = typeof data1 !== "undefined" ? data1 : data2;
  38. if (data === innerRequest) return callback();
  39. if (data === undefined) return callback();
  40. if (data === false) {
  41. const ignoreObj = Object.assign({}, request, {
  42. path: false
  43. });
  44. return callback(null, ignoreObj);
  45. }
  46. const obj = Object.assign({}, request, {
  47. path: request.descriptionFileRoot,
  48. request: data
  49. });
  50. resolver.doResolve(
  51. target,
  52. obj,
  53. "aliased from description file " +
  54. request.descriptionFilePath +
  55. " with mapping '" +
  56. innerRequest +
  57. "' to '" +
  58. data +
  59. "'",
  60. resolveContext,
  61. (err, result) => {
  62. if (err) return callback(err);
  63. // Don't allow other aliasing or raw request
  64. if (result === undefined) return callback(null, null);
  65. callback(null, result);
  66. }
  67. );
  68. });
  69. }
  70. };