RequireEnsurePlugin.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. evaluateToString,
  11. toConstantDependency
  12. } = require("../javascript/JavascriptParserHelpers");
  13. class RequireEnsurePlugin {
  14. apply(compiler) {
  15. compiler.hooks.compilation.tap(
  16. "RequireEnsurePlugin",
  17. (compilation, { normalModuleFactory }) => {
  18. compilation.dependencyFactories.set(
  19. RequireEnsureItemDependency,
  20. normalModuleFactory
  21. );
  22. compilation.dependencyTemplates.set(
  23. RequireEnsureItemDependency,
  24. new RequireEnsureItemDependency.Template()
  25. );
  26. compilation.dependencyTemplates.set(
  27. RequireEnsureDependency,
  28. new RequireEnsureDependency.Template()
  29. );
  30. const handler = (parser, parserOptions) => {
  31. if (
  32. parserOptions.requireEnsure !== undefined &&
  33. !parserOptions.requireEnsure
  34. )
  35. return;
  36. new RequireEnsureDependenciesBlockParserPlugin().apply(parser);
  37. parser.hooks.evaluateTypeof
  38. .for("require.ensure")
  39. .tap("RequireEnsurePlugin", evaluateToString("function"));
  40. parser.hooks.typeof
  41. .for("require.ensure")
  42. .tap(
  43. "RequireEnsurePlugin",
  44. toConstantDependency(parser, JSON.stringify("function"))
  45. );
  46. };
  47. normalModuleFactory.hooks.parser
  48. .for("javascript/auto")
  49. .tap("RequireEnsurePlugin", handler);
  50. normalModuleFactory.hooks.parser
  51. .for("javascript/dynamic")
  52. .tap("RequireEnsurePlugin", handler);
  53. }
  54. );
  55. }
  56. }
  57. module.exports = RequireEnsurePlugin;