You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.3 KiB

4 years ago
  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. class DelegatedModuleFactoryPlugin {
  13. constructor(options) {
  14. this.options = options;
  15. options.type = options.type || "require";
  16. options.extensions = options.extensions || [
  17. "",
  18. ".wasm",
  19. ".mjs",
  20. ".js",
  21. ".json"
  22. ];
  23. }
  24. apply(normalModuleFactory) {
  25. const scope = this.options.scope;
  26. if (scope) {
  27. normalModuleFactory.hooks.factory.tap(
  28. "DelegatedModuleFactoryPlugin",
  29. factory => (data, callback) => {
  30. const dependency = data.dependencies[0];
  31. const request = dependency.request;
  32. if (request && request.indexOf(scope + "/") === 0) {
  33. const innerRequest = "." + request.substr(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 factory(data, callback);
  67. }
  68. );
  69. } else {
  70. normalModuleFactory.hooks.module.tap(
  71. "DelegatedModuleFactoryPlugin",
  72. module => {
  73. if (module.libIdent) {
  74. const request = module.libIdent(this.options);
  75. if (request && 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;