DelegatedModuleFactoryPlugin.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. // options.source
  8. // options.type
  9. // options.context
  10. // options.scope
  11. // options.content
  12. // options.associatedObjectForCache
  13. class DelegatedModuleFactoryPlugin {
  14. constructor(options) {
  15. this.options = options;
  16. options.type = options.type || "require";
  17. options.extensions = options.extensions || ["", ".js", ".json", ".wasm"];
  18. }
  19. apply(normalModuleFactory) {
  20. const scope = this.options.scope;
  21. if (scope) {
  22. normalModuleFactory.hooks.factorize.tapAsync(
  23. "DelegatedModuleFactoryPlugin",
  24. (data, callback) => {
  25. const [dependency] = data.dependencies;
  26. const { request } = dependency;
  27. if (request && request.startsWith(`${scope}/`)) {
  28. const innerRequest = "." + request.slice(scope.length);
  29. let resolved;
  30. if (innerRequest in this.options.content) {
  31. resolved = this.options.content[innerRequest];
  32. return callback(
  33. null,
  34. new DelegatedModule(
  35. this.options.source,
  36. resolved,
  37. this.options.type,
  38. innerRequest,
  39. request
  40. )
  41. );
  42. }
  43. for (let i = 0; i < this.options.extensions.length; i++) {
  44. const extension = this.options.extensions[i];
  45. const requestPlusExt = innerRequest + extension;
  46. if (requestPlusExt in this.options.content) {
  47. resolved = this.options.content[requestPlusExt];
  48. return callback(
  49. null,
  50. new DelegatedModule(
  51. this.options.source,
  52. resolved,
  53. this.options.type,
  54. requestPlusExt,
  55. request + extension
  56. )
  57. );
  58. }
  59. }
  60. }
  61. return callback();
  62. }
  63. );
  64. } else {
  65. normalModuleFactory.hooks.module.tap(
  66. "DelegatedModuleFactoryPlugin",
  67. module => {
  68. const request = module.libIdent(this.options);
  69. if (request) {
  70. if (request in this.options.content) {
  71. const resolved = this.options.content[request];
  72. return new DelegatedModule(
  73. this.options.source,
  74. resolved,
  75. this.options.type,
  76. request,
  77. module
  78. );
  79. }
  80. }
  81. return module;
  82. }
  83. );
  84. }
  85. }
  86. }
  87. module.exports = DelegatedModuleFactoryPlugin;