AliasPlugin.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. function startsWith(string, searchString) {
  7. const stringLength = string.length;
  8. const searchLength = searchString.length;
  9. // early out if the search length is greater than the search string
  10. if (searchLength > stringLength) {
  11. return false;
  12. }
  13. let index = -1;
  14. while (++index < searchLength) {
  15. if (string.charCodeAt(index) !== searchString.charCodeAt(index)) {
  16. return false;
  17. }
  18. }
  19. return true;
  20. }
  21. module.exports = class AliasPlugin {
  22. constructor(source, options, target) {
  23. this.source = source;
  24. this.options = Array.isArray(options) ? options : [options];
  25. this.target = target;
  26. }
  27. apply(resolver) {
  28. const target = resolver.ensureHook(this.target);
  29. resolver
  30. .getHook(this.source)
  31. .tapAsync("AliasPlugin", (request, resolveContext, callback) => {
  32. const innerRequest = request.request || request.path;
  33. if (!innerRequest) return callback();
  34. for (const item of this.options) {
  35. if (
  36. innerRequest === item.name ||
  37. (!item.onlyModule && startsWith(innerRequest, item.name + "/"))
  38. ) {
  39. if (
  40. innerRequest !== item.alias &&
  41. !startsWith(innerRequest, item.alias + "/")
  42. ) {
  43. const newRequestStr =
  44. item.alias + innerRequest.substr(item.name.length);
  45. const obj = Object.assign({}, request, {
  46. request: newRequestStr
  47. });
  48. return resolver.doResolve(
  49. target,
  50. obj,
  51. "aliased with mapping '" +
  52. item.name +
  53. "': '" +
  54. item.alias +
  55. "' to '" +
  56. newRequestStr +
  57. "'",
  58. resolveContext,
  59. (err, result) => {
  60. if (err) return callback(err);
  61. // Don't allow other aliasing or raw request
  62. if (result === undefined) return callback(null, null);
  63. callback(null, result);
  64. }
  65. );
  66. }
  67. }
  68. }
  69. return callback();
  70. });
  71. }
  72. };