PrefetchPlugin.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. /** @import Compiler from "./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. /** @type {string | null} */
  18. this.context = context;
  19. /** @type {string} */
  20. this.request = request;
  21. } else {
  22. this.context = null;
  23. this.request = context;
  24. }
  25. }
  26. /**
  27. * Applies the plugin by registering its hooks on the compiler.
  28. * @param {Compiler} compiler the compiler instance
  29. * @returns {void}
  30. */
  31. apply(compiler) {
  32. compiler.hooks.compilation.tap(
  33. PLUGIN_NAME,
  34. (compilation, { normalModuleFactory }) => {
  35. compilation.dependencyFactories.set(
  36. PrefetchDependency,
  37. normalModuleFactory
  38. );
  39. }
  40. );
  41. compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
  42. compilation.addModuleChain(
  43. this.context || compiler.context,
  44. new PrefetchDependency(this.request),
  45. (err) => {
  46. callback(err);
  47. }
  48. );
  49. });
  50. }
  51. }
  52. module.exports = PrefetchPlugin;