AliasFieldPlugin.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. var DescriptionFileUtils = require("./DescriptionFileUtils");
  6. var createInnerCallback = require("./createInnerCallback");
  7. var getInnerRequest = require("./getInnerRequest");
  8. function AliasFieldPlugin(source, field, target) {
  9. this.source = source;
  10. this.field = field;
  11. this.target = target;
  12. }
  13. module.exports = AliasFieldPlugin;
  14. AliasFieldPlugin.prototype.apply = function(resolver) {
  15. var target = this.target;
  16. var field = this.field;
  17. resolver.plugin(this.source, function(request, callback) {
  18. if(!request.descriptionFileData) return callback();
  19. var innerRequest = getInnerRequest(resolver, request);
  20. if(!innerRequest) return callback();
  21. var fieldData = DescriptionFileUtils.getField(request.descriptionFileData, field);
  22. if(typeof fieldData !== "object") {
  23. if(callback.log) callback.log("Field '" + field + "' doesn't contain a valid alias configuration");
  24. return callback();
  25. }
  26. var data1 = fieldData[innerRequest];
  27. var data2 = fieldData[innerRequest.replace(/^\.\//, "")];
  28. var data = typeof data1 !== "undefined" ? data1 : data2;
  29. if(data === innerRequest) return callback();
  30. if(data === undefined) return callback();
  31. if(data === false) {
  32. var ignoreObj = Object.assign({}, request, {
  33. path: false
  34. });
  35. return callback(null, ignoreObj);
  36. }
  37. var obj = Object.assign({}, request, {
  38. path: request.descriptionFileRoot,
  39. request: data
  40. });
  41. resolver.doResolve(target, obj, "aliased from description file " + request.descriptionFilePath + " with mapping '" + innerRequest + "' to '" + data + "'", createInnerCallback(function(err, result) {
  42. if(arguments.length > 0) return callback(err, result);
  43. // Don't allow other aliasing or raw request
  44. callback(null, null);
  45. }, callback));
  46. });
  47. };