NormalModuleReplacementPlugin.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. class NormalModuleReplacementPlugin {
  8. constructor(resourceRegExp, newResource) {
  9. this.resourceRegExp = resourceRegExp;
  10. this.newResource = newResource;
  11. }
  12. apply(compiler) {
  13. const resourceRegExp = this.resourceRegExp;
  14. const newResource = this.newResource;
  15. compiler.hooks.normalModuleFactory.tap(
  16. "NormalModuleReplacementPlugin",
  17. nmf => {
  18. nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => {
  19. if (!result) return;
  20. if (resourceRegExp.test(result.request)) {
  21. if (typeof newResource === "function") {
  22. newResource(result);
  23. } else {
  24. result.request = newResource;
  25. }
  26. }
  27. return result;
  28. });
  29. nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => {
  30. if (!result) return;
  31. if (resourceRegExp.test(result.resource)) {
  32. if (typeof newResource === "function") {
  33. newResource(result);
  34. } else {
  35. result.resource = path.resolve(
  36. path.dirname(result.resource),
  37. newResource
  38. );
  39. }
  40. }
  41. return result;
  42. });
  43. }
  44. );
  45. }
  46. }
  47. module.exports = NormalModuleReplacementPlugin;