DelegatedModuleFactoryPlugin.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const DelegatedModule = require("./DelegatedModule");
  7. /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
  8. // options.source
  9. // options.type
  10. // options.context
  11. // options.scope
  12. // options.content
  13. // options.associatedObjectForCache
  14. class DelegatedModuleFactoryPlugin {
  15. constructor(options) {
  16. this.options = options;
  17. options.type = options.type || "require";
  18. options.extensions = options.extensions || ["", ".js", ".json", ".wasm"];
  19. }
  20. /**
  21. * @param {NormalModuleFactory} normalModuleFactory the normal module factory
  22. * @returns {void}
  23. */
  24. apply(normalModuleFactory) {
  25. const scope = this.options.scope;
  26. if (scope) {
  27. normalModuleFactory.hooks.factorize.tapAsync(
  28. "DelegatedModuleFactoryPlugin",
  29. (data, callback) => {
  30. const [dependency] = data.dependencies;
  31. const { request } = dependency;
  32. if (request && request.startsWith(`${scope}/`)) {
  33. const innerRequest = "." + request.slice(scope.length);
  34. let resolved;
  35. if (innerRequest in this.options.content) {
  36. resolved = this.options.content[innerRequest];
  37. return callback(
  38. null,
  39. new DelegatedModule(
  40. this.options.source,
  41. resolved,
  42. this.options.type,
  43. innerRequest,
  44. request
  45. )
  46. );
  47. }
  48. for (let i = 0; i < this.options.extensions.length; i++) {
  49. const extension = this.options.extensions[i];
  50. const requestPlusExt = innerRequest + extension;
  51. if (requestPlusExt in this.options.content) {
  52. resolved = this.options.content[requestPlusExt];
  53. return callback(
  54. null,
  55. new DelegatedModule(
  56. this.options.source,
  57. resolved,
  58. this.options.type,
  59. requestPlusExt,
  60. request + extension
  61. )
  62. );
  63. }
  64. }
  65. }
  66. return callback();
  67. }
  68. );
  69. } else {
  70. normalModuleFactory.hooks.module.tap(
  71. "DelegatedModuleFactoryPlugin",
  72. module => {
  73. const request = module.libIdent(this.options);
  74. if (request) {
  75. if (request in this.options.content) {
  76. const resolved = this.options.content[request];
  77. return new DelegatedModule(
  78. this.options.source,
  79. resolved,
  80. this.options.type,
  81. request,
  82. module
  83. );
  84. }
  85. }
  86. return module;
  87. }
  88. );
  89. }
  90. }
  91. }
  92. module.exports = DelegatedModuleFactoryPlugin;