您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

MainFieldPlugin.js 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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.getHook(this.source).tapAsync("MainFieldPlugin", (request, resolveContext, callback) => {
  16. if(request.path !== request.descriptionFileRoot) return callback();
  17. if(request.alreadyTriedMainField === request.descriptionFilePath) return callback();
  18. const content = request.descriptionFileData;
  19. const filename = path.basename(request.descriptionFilePath);
  20. let mainModule;
  21. const field = this.options.name;
  22. if(Array.isArray(field)) {
  23. let current = content;
  24. for(let j = 0; j < field.length; j++) {
  25. if(current === null || typeof current !== "object") {
  26. current = null;
  27. break;
  28. }
  29. current = current[field[j]];
  30. }
  31. if(typeof current === "string") {
  32. mainModule = current;
  33. }
  34. } else {
  35. if(typeof content[field] === "string") {
  36. mainModule = content[field];
  37. }
  38. }
  39. if(!mainModule) return callback();
  40. if(this.options.forceRelative && !/^\.\.?\//.test(mainModule))
  41. mainModule = "./" + mainModule;
  42. const obj = Object.assign({}, request, {
  43. request: mainModule,
  44. alreadyTriedMainField: request.descriptionFilePath
  45. });
  46. return resolver.doResolve(target, obj, "use " + mainModule + " from " + this.options.name + " in " + filename, resolveContext, callback);
  47. });
  48. }
  49. };