You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.7 KiB

4 years ago
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const path = require("path");
  7. module.exports = class MainFieldPlugin {
  8. constructor(source, options, target) {
  9. this.source = source;
  10. this.options = options;
  11. this.target = target;
  12. }
  13. apply(resolver) {
  14. const target = resolver.ensureHook(this.target);
  15. resolver
  16. .getHook(this.source)
  17. .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => {
  18. if (request.path !== request.descriptionFileRoot) return callback();
  19. if (request.alreadyTriedMainField === request.descriptionFilePath)
  20. return callback();
  21. const content = request.descriptionFileData;
  22. const filename = path.basename(request.descriptionFilePath);
  23. let mainModule;
  24. const field = this.options.name;
  25. if (Array.isArray(field)) {
  26. let current = content;
  27. for (let j = 0; j < field.length; j++) {
  28. if (current === null || typeof current !== "object") {
  29. current = null;
  30. break;
  31. }
  32. current = current[field[j]];
  33. }
  34. if (typeof current === "string") {
  35. mainModule = current;
  36. }
  37. } else {
  38. if (typeof content[field] === "string") {
  39. mainModule = content[field];
  40. }
  41. }
  42. if (!mainModule) return callback();
  43. if (this.options.forceRelative && !/^\.\.?\//.test(mainModule))
  44. mainModule = "./" + mainModule;
  45. const obj = Object.assign({}, request, {
  46. request: mainModule,
  47. alreadyTriedMainField: request.descriptionFilePath
  48. });
  49. return resolver.doResolve(
  50. target,
  51. obj,
  52. "use " +
  53. mainModule +
  54. " from " +
  55. this.options.name +
  56. " in " +
  57. filename,
  58. resolveContext,
  59. callback
  60. );
  61. });
  62. }
  63. };