NormalModuleReplacementPlugin.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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.plugin("normal-module-factory", (nmf) => {
  16. nmf.plugin("before-resolve", (result, callback) => {
  17. if(!result) return callback();
  18. if(resourceRegExp.test(result.request)) {
  19. if(typeof newResource === "function") {
  20. newResource(result);
  21. } else {
  22. result.request = newResource;
  23. }
  24. }
  25. return callback(null, result);
  26. });
  27. nmf.plugin("after-resolve", (result, callback) => {
  28. if(!result) return callback();
  29. if(resourceRegExp.test(result.resource)) {
  30. if(typeof newResource === "function") {
  31. newResource(result);
  32. } else {
  33. result.resource = path.resolve(path.dirname(result.resource), newResource);
  34. }
  35. }
  36. return callback(null, result);
  37. });
  38. });
  39. }
  40. }
  41. module.exports = NormalModuleReplacementPlugin;