AutomaticPrefetchPlugin.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /** @type {{context: string | null, request: string}[] | null} */
  27. let lastModules = null;
  28. compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => {
  29. lastModules = [];
  30. for (const m of compilation.modules) {
  31. if (m instanceof NormalModule) {
  32. lastModules.push({
  33. context: m.context,
  34. request: m.request
  35. });
  36. }
  37. }
  38. });
  39. compiler.hooks.make.tapAsync(
  40. "AutomaticPrefetchPlugin",
  41. (compilation, callback) => {
  42. if (!lastModules) return callback();
  43. asyncLib.forEach(
  44. lastModules,
  45. (m, callback) => {
  46. compilation.addModuleChain(
  47. m.context || compiler.context,
  48. new PrefetchDependency(`!!${m.request}`),
  49. callback
  50. );
  51. },
  52. err => {
  53. lastModules = null;
  54. callback(err);
  55. }
  56. );
  57. }
  58. );
  59. }
  60. }
  61. module.exports = AutomaticPrefetchPlugin;