NormalModuleReplacementPlugin.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 {import("./util/fs").InputFileSystem} InputFileSystem */
  9. /** @typedef {function(import("./NormalModuleFactory").ResolveData): void} ModuleReplacer */
  10. class NormalModuleReplacementPlugin {
  11. /**
  12. * Create an instance of the plugin
  13. * @param {RegExp} resourceRegExp the resource matcher
  14. * @param {string|ModuleReplacer} newResource the resource replacement
  15. */
  16. constructor(resourceRegExp, newResource) {
  17. this.resourceRegExp = resourceRegExp;
  18. this.newResource = newResource;
  19. }
  20. /**
  21. * Apply the plugin
  22. * @param {Compiler} compiler the compiler instance
  23. * @returns {void}
  24. */
  25. apply(compiler) {
  26. const resourceRegExp = this.resourceRegExp;
  27. const newResource = this.newResource;
  28. compiler.hooks.normalModuleFactory.tap(
  29. "NormalModuleReplacementPlugin",
  30. nmf => {
  31. nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => {
  32. if (resourceRegExp.test(result.request)) {
  33. if (typeof newResource === "function") {
  34. newResource(result);
  35. } else {
  36. result.request = newResource;
  37. }
  38. }
  39. });
  40. nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => {
  41. const createData = result.createData;
  42. if (
  43. resourceRegExp.test(/** @type {string} */ (createData.resource))
  44. ) {
  45. if (typeof newResource === "function") {
  46. newResource(result);
  47. } else {
  48. const fs =
  49. /** @type {InputFileSystem} */
  50. (compiler.inputFileSystem);
  51. if (
  52. newResource.startsWith("/") ||
  53. (newResource.length > 1 && newResource[1] === ":")
  54. ) {
  55. createData.resource = newResource;
  56. } else {
  57. createData.resource = join(
  58. fs,
  59. dirname(fs, /** @type {string} */ (createData.resource)),
  60. newResource
  61. );
  62. }
  63. }
  64. }
  65. });
  66. }
  67. );
  68. }
  69. }
  70. module.exports = NormalModuleReplacementPlugin;