PrefetchPlugin.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const PrefetchDependency = require("./dependencies/PrefetchDependency");
  7. /** @typedef {import("./Compiler")} Compiler */
  8. const PLUGIN_NAME = "PrefetchPlugin";
  9. class PrefetchPlugin {
  10. /**
  11. * Creates an instance of PrefetchPlugin.
  12. * @param {string} context context or request if context is not set
  13. * @param {string=} request request
  14. */
  15. constructor(context, request) {
  16. if (request) {
  17. this.context = context;
  18. this.request = request;
  19. } else {
  20. this.context = null;
  21. this.request = context;
  22. }
  23. }
  24. /**
  25. * Applies the plugin by registering its hooks on the compiler.
  26. * @param {Compiler} compiler the compiler instance
  27. * @returns {void}
  28. */
  29. apply(compiler) {
  30. compiler.hooks.compilation.tap(
  31. PLUGIN_NAME,
  32. (compilation, { normalModuleFactory }) => {
  33. compilation.dependencyFactories.set(
  34. PrefetchDependency,
  35. normalModuleFactory
  36. );
  37. }
  38. );
  39. compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
  40. compilation.addModuleChain(
  41. this.context || compiler.context,
  42. new PrefetchDependency(this.request),
  43. (err) => {
  44. callback(err);
  45. }
  46. );
  47. });
  48. }
  49. }
  50. module.exports = PrefetchPlugin;