RequireEnsurePlugin.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RequireEnsureDependency = require("./RequireEnsureDependency");
  7. const RequireEnsureItemDependency = require("./RequireEnsureItemDependency");
  8. const RequireEnsureDependenciesBlockParserPlugin = require("./RequireEnsureDependenciesBlockParserPlugin");
  9. const {
  10. JAVASCRIPT_MODULE_TYPE_AUTO,
  11. JAVASCRIPT_MODULE_TYPE_DYNAMIC
  12. } = require("../ModuleTypeConstants");
  13. const {
  14. evaluateToString,
  15. toConstantDependency
  16. } = require("../javascript/JavascriptParserHelpers");
  17. /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
  18. /** @typedef {import("../Compiler")} Compiler */
  19. /** @typedef {import("../javascript/JavascriptParser")} Parser */
  20. const PLUGIN_NAME = "RequireEnsurePlugin";
  21. class RequireEnsurePlugin {
  22. /**
  23. * Apply the plugin
  24. * @param {Compiler} compiler the compiler instance
  25. * @returns {void}
  26. */
  27. apply(compiler) {
  28. compiler.hooks.compilation.tap(
  29. PLUGIN_NAME,
  30. (compilation, { normalModuleFactory }) => {
  31. compilation.dependencyFactories.set(
  32. RequireEnsureItemDependency,
  33. normalModuleFactory
  34. );
  35. compilation.dependencyTemplates.set(
  36. RequireEnsureItemDependency,
  37. new RequireEnsureItemDependency.Template()
  38. );
  39. compilation.dependencyTemplates.set(
  40. RequireEnsureDependency,
  41. new RequireEnsureDependency.Template()
  42. );
  43. /**
  44. * @param {Parser} parser parser parser
  45. * @param {JavascriptParserOptions} parserOptions parserOptions
  46. * @returns {void}
  47. */
  48. const handler = (parser, parserOptions) => {
  49. if (
  50. parserOptions.requireEnsure !== undefined &&
  51. !parserOptions.requireEnsure
  52. )
  53. return;
  54. new RequireEnsureDependenciesBlockParserPlugin().apply(parser);
  55. parser.hooks.evaluateTypeof
  56. .for("require.ensure")
  57. .tap(PLUGIN_NAME, evaluateToString("function"));
  58. parser.hooks.typeof
  59. .for("require.ensure")
  60. .tap(
  61. PLUGIN_NAME,
  62. toConstantDependency(parser, JSON.stringify("function"))
  63. );
  64. };
  65. normalModuleFactory.hooks.parser
  66. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  67. .tap(PLUGIN_NAME, handler);
  68. normalModuleFactory.hooks.parser
  69. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  70. .tap(PLUGIN_NAME, handler);
  71. }
  72. );
  73. }
  74. }
  75. module.exports = RequireEnsurePlugin;