AutomaticPrefetchPlugin.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const asyncLib = require("async");
  7. const PrefetchDependency = require("./dependencies/PrefetchDependency");
  8. const NormalModule = require("./NormalModule");
  9. class AutomaticPrefetchPlugin {
  10. apply(compiler) {
  11. compiler.plugin("compilation", (compilation, params) => {
  12. const normalModuleFactory = params.normalModuleFactory;
  13. compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory);
  14. });
  15. let lastModules = null;
  16. compiler.plugin("after-compile", (compilation, callback) => {
  17. lastModules = compilation.modules
  18. .filter(m => m instanceof NormalModule)
  19. .map(m => ({
  20. context: m.context,
  21. request: m.request
  22. }));
  23. callback();
  24. });
  25. compiler.plugin("make", (compilation, callback) => {
  26. if(!lastModules) return callback();
  27. asyncLib.forEach(lastModules, (m, callback) => {
  28. compilation.prefetch(m.context || compiler.context, new PrefetchDependency(m.request), callback);
  29. }, callback);
  30. });
  31. }
  32. }
  33. module.exports = AutomaticPrefetchPlugin;