AutomaticPrefetchPlugin.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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("neo-async");
  7. const NormalModule = require("./NormalModule");
  8. const PrefetchDependency = require("./dependencies/PrefetchDependency");
  9. /** @typedef {import("./Compiler")} Compiler */
  10. class AutomaticPrefetchPlugin {
  11. /**
  12. * Apply the plugin
  13. * @param {Compiler} compiler the compiler instance
  14. * @returns {void}
  15. */
  16. apply(compiler) {
  17. compiler.hooks.compilation.tap(
  18. "AutomaticPrefetchPlugin",
  19. (compilation, { normalModuleFactory }) => {
  20. compilation.dependencyFactories.set(
  21. PrefetchDependency,
  22. normalModuleFactory
  23. );
  24. }
  25. );
  26. let lastModules = null;
  27. compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => {
  28. lastModules = [];
  29. for (const m of compilation.modules) {
  30. if (m instanceof NormalModule) {
  31. lastModules.push({
  32. context: m.context,
  33. request: m.request
  34. });
  35. }
  36. }
  37. });
  38. compiler.hooks.make.tapAsync(
  39. "AutomaticPrefetchPlugin",
  40. (compilation, callback) => {
  41. if (!lastModules) return callback();
  42. asyncLib.forEach(
  43. lastModules,
  44. (m, callback) => {
  45. compilation.addModuleChain(
  46. m.context || compiler.context,
  47. new PrefetchDependency(`!!${m.request}`),
  48. callback
  49. );
  50. },
  51. err => {
  52. lastModules = null;
  53. callback(err);
  54. }
  55. );
  56. }
  57. );
  58. }
  59. }
  60. module.exports = AutomaticPrefetchPlugin;