LoaderPlugin.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const LoaderDependency = require("./LoaderDependency");
  7. class LoaderPlugin {
  8. apply(compiler) {
  9. compiler.plugin("compilation", (compilation, params) => {
  10. const normalModuleFactory = params.normalModuleFactory;
  11. compilation.dependencyFactories.set(LoaderDependency, normalModuleFactory);
  12. });
  13. compiler.plugin("compilation", (compilation) => {
  14. compilation.plugin("normal-module-loader", (loaderContext, module) => {
  15. loaderContext.loadModule = function loadModule(request, callback) {
  16. const dep = new LoaderDependency(request);
  17. dep.loc = request;
  18. compilation.addModuleDependencies(module, [
  19. [dep]
  20. ], true, "lm", false, (err) => {
  21. if(err) return callback(err);
  22. if(!dep.module) return callback(new Error("Cannot load the module"));
  23. if(dep.module.building) dep.module.building.push(next);
  24. else next();
  25. function next(err) {
  26. if(err) return callback(err);
  27. if(dep.module.error) return callback(dep.module.error);
  28. if(!dep.module._source) throw new Error("The module created for a LoaderDependency must have a property _source");
  29. let source, map;
  30. const moduleSource = dep.module._source;
  31. if(moduleSource.sourceAndMap) {
  32. const sourceAndMap = moduleSource.sourceAndMap();
  33. map = sourceAndMap.map;
  34. source = sourceAndMap.source;
  35. } else {
  36. map = moduleSource.map();
  37. source = moduleSource.source();
  38. }
  39. if(dep.module.fileDependencies) {
  40. dep.module.fileDependencies.forEach((dep) => loaderContext.addDependency(dep));
  41. }
  42. if(dep.module.contextDependencies) {
  43. dep.module.contextDependencies.forEach((dep) => loaderContext.addContextDependency(dep));
  44. }
  45. return callback(null, source, map, dep.module);
  46. }
  47. });
  48. };
  49. });
  50. });
  51. }
  52. }
  53. module.exports = LoaderPlugin;