NormalModuleReplacementPlugin.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { join, dirname } = require("./util/fs");
  7. /** @typedef {import("./Compiler")} Compiler */
  8. /** @typedef {function(TODO): void} ModuleReplacer */
  9. class NormalModuleReplacementPlugin {
  10. /**
  11. * Create an instance of the plugin
  12. * @param {RegExp} resourceRegExp the resource matcher
  13. * @param {string|ModuleReplacer} newResource the resource replacement
  14. */
  15. constructor(resourceRegExp, newResource) {
  16. this.resourceRegExp = resourceRegExp;
  17. this.newResource = newResource;
  18. }
  19. /**
  20. * Apply the plugin
  21. * @param {Compiler} compiler the compiler instance
  22. * @returns {void}
  23. */
  24. apply(compiler) {
  25. const resourceRegExp = this.resourceRegExp;
  26. const newResource = this.newResource;
  27. compiler.hooks.normalModuleFactory.tap(
  28. "NormalModuleReplacementPlugin",
  29. nmf => {
  30. nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => {
  31. if (resourceRegExp.test(result.request)) {
  32. if (typeof newResource === "function") {
  33. newResource(result);
  34. } else {
  35. result.request = newResource;
  36. }
  37. }
  38. });
  39. nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => {
  40. const createData = result.createData;
  41. if (resourceRegExp.test(createData.resource)) {
  42. if (typeof newResource === "function") {
  43. newResource(result);
  44. } else {
  45. const fs = compiler.inputFileSystem;
  46. if (
  47. newResource.startsWith("/") ||
  48. (newResource.length > 1 && newResource[1] === ":")
  49. ) {
  50. createData.resource = newResource;
  51. } else {
  52. createData.resource = join(
  53. fs,
  54. dirname(fs, createData.resource),
  55. newResource
  56. );
  57. }
  58. }
  59. }
  60. });
  61. }
  62. );
  63. }
  64. }
  65. module.exports = NormalModuleReplacementPlugin;