PrefetchPlugin.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. * @param {string} context context or request if context is not set
  12. * @param {string=} request request
  13. */
  14. constructor(context, request) {
  15. if (request) {
  16. this.context = context;
  17. this.request = request;
  18. } else {
  19. this.context = null;
  20. this.request = context;
  21. }
  22. }
  23. /**
  24. * Apply the plugin
  25. * @param {Compiler} compiler the compiler instance
  26. * @returns {void}
  27. */
  28. apply(compiler) {
  29. compiler.hooks.compilation.tap(
  30. PLUGIN_NAME,
  31. (compilation, { normalModuleFactory }) => {
  32. compilation.dependencyFactories.set(
  33. PrefetchDependency,
  34. normalModuleFactory
  35. );
  36. }
  37. );
  38. compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
  39. compilation.addModuleChain(
  40. this.context || compiler.context,
  41. new PrefetchDependency(this.request),
  42. err => {
  43. callback(err);
  44. }
  45. );
  46. });
  47. }
  48. }
  49. module.exports = PrefetchPlugin;