DelegatedModuleFactoryPlugin.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 || ["", ".js"];
  17. }
  18. apply(normalModuleFactory) {
  19. const scope = this.options.scope;
  20. if(scope) {
  21. normalModuleFactory.plugin("factory", factory => (data, callback) => {
  22. const dependency = data.dependencies[0];
  23. const request = dependency.request;
  24. if(request && request.indexOf(scope + "/") === 0) {
  25. const innerRequest = "." + request.substr(scope.length);
  26. let resolved;
  27. if(innerRequest in this.options.content) {
  28. resolved = this.options.content[innerRequest];
  29. return callback(null, new DelegatedModule(this.options.source, resolved, this.options.type, innerRequest, request));
  30. }
  31. for(let i = 0; i < this.options.extensions.length; i++) {
  32. const extension = this.options.extensions[i];
  33. const requestPlusExt = innerRequest + extension;
  34. if(requestPlusExt in this.options.content) {
  35. resolved = this.options.content[requestPlusExt];
  36. return callback(null, new DelegatedModule(this.options.source, resolved, this.options.type, requestPlusExt, request + extension));
  37. }
  38. }
  39. }
  40. return factory(data, callback);
  41. });
  42. } else {
  43. normalModuleFactory.plugin("module", module => {
  44. if(module.libIdent) {
  45. const request = module.libIdent(this.options);
  46. if(request && request in this.options.content) {
  47. const resolved = this.options.content[request];
  48. return new DelegatedModule(this.options.source, resolved, this.options.type, request, module);
  49. }
  50. }
  51. return module;
  52. });
  53. }
  54. }
  55. }
  56. module.exports = DelegatedModuleFactoryPlugin;