您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

AutomaticPrefetchPlugin.js 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 PrefetchDependency = require("./dependencies/PrefetchDependency");
  8. const NormalModule = require("./NormalModule");
  9. /** @typedef {import("./Compiler")} Compiler */
  10. class AutomaticPrefetchPlugin {
  11. /**
  12. * Apply the plugin
  13. * @param {Compiler} compiler Webpack Compiler
  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 = compilation.modules
  29. .filter(m => m instanceof NormalModule)
  30. .map((/** @type {NormalModule} */ m) => ({
  31. context: m.context,
  32. request: m.request
  33. }));
  34. });
  35. compiler.hooks.make.tapAsync(
  36. "AutomaticPrefetchPlugin",
  37. (compilation, callback) => {
  38. if (!lastModules) return callback();
  39. asyncLib.forEach(
  40. lastModules,
  41. (m, callback) => {
  42. compilation.prefetch(
  43. m.context || compiler.context,
  44. new PrefetchDependency(m.request),
  45. callback
  46. );
  47. },
  48. callback
  49. );
  50. }
  51. );
  52. }
  53. }
  54. module.exports = AutomaticPrefetchPlugin;