MainFieldPlugin.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. var path = require("path");
  6. function MainFieldPlugin(source, options, target) {
  7. this.source = source;
  8. this.options = options;
  9. this.target = target;
  10. }
  11. module.exports = MainFieldPlugin;
  12. MainFieldPlugin.prototype.apply = function(resolver) {
  13. var target = this.target;
  14. var options = this.options;
  15. resolver.plugin(this.source, function mainField(request, callback) {
  16. if(request.path !== request.descriptionFileRoot) return callback();
  17. var content = request.descriptionFileData;
  18. var filename = path.basename(request.descriptionFilePath);
  19. var mainModule;
  20. var field = options.name;
  21. if(Array.isArray(field)) {
  22. var current = content;
  23. for(var j = 0; j < field.length; j++) {
  24. if(current === null || typeof current !== "object") {
  25. current = null;
  26. break;
  27. }
  28. current = current[field[j]];
  29. }
  30. if(typeof current === "string") {
  31. mainModule = current;
  32. }
  33. } else {
  34. if(typeof content[field] === "string") {
  35. mainModule = content[field];
  36. }
  37. }
  38. if(!mainModule) return callback();
  39. if(options.forceRelative && !/^\.\.?\//.test(mainModule))
  40. mainModule = "./" + mainModule;
  41. var obj = Object.assign({}, request, {
  42. request: mainModule
  43. });
  44. return resolver.doResolve(target, obj, "use " + mainModule + " from " + options.name + " in " + filename, callback);
  45. });
  46. };