ExportsInfoApiPlugin.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const {
  7. JAVASCRIPT_MODULE_TYPE_AUTO,
  8. JAVASCRIPT_MODULE_TYPE_DYNAMIC,
  9. JAVASCRIPT_MODULE_TYPE_ESM
  10. } = require("./ModuleTypeConstants");
  11. const ConstDependency = require("./dependencies/ConstDependency");
  12. const ExportsInfoDependency = require("./dependencies/ExportsInfoDependency");
  13. /** @typedef {import("./Compiler")} Compiler */
  14. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  15. const PLUGIN_NAME = "ExportsInfoApiPlugin";
  16. class ExportsInfoApiPlugin {
  17. /**
  18. * Apply the plugin
  19. * @param {Compiler} compiler the compiler instance
  20. * @returns {void}
  21. */
  22. apply(compiler) {
  23. compiler.hooks.compilation.tap(
  24. PLUGIN_NAME,
  25. (compilation, { normalModuleFactory }) => {
  26. compilation.dependencyTemplates.set(
  27. ExportsInfoDependency,
  28. new ExportsInfoDependency.Template()
  29. );
  30. /**
  31. * @param {JavascriptParser} parser the parser
  32. * @returns {void}
  33. */
  34. const handler = parser => {
  35. parser.hooks.expressionMemberChain
  36. .for("__webpack_exports_info__")
  37. .tap(PLUGIN_NAME, (expr, members) => {
  38. const dep =
  39. members.length >= 2
  40. ? new ExportsInfoDependency(
  41. expr.range,
  42. members.slice(0, -1),
  43. members[members.length - 1]
  44. )
  45. : new ExportsInfoDependency(expr.range, null, members[0]);
  46. dep.loc = expr.loc;
  47. parser.state.module.addDependency(dep);
  48. return true;
  49. });
  50. parser.hooks.expression
  51. .for("__webpack_exports_info__")
  52. .tap(PLUGIN_NAME, expr => {
  53. const dep = new ConstDependency("true", expr.range);
  54. dep.loc = expr.loc;
  55. parser.state.module.addPresentationalDependency(dep);
  56. return true;
  57. });
  58. };
  59. normalModuleFactory.hooks.parser
  60. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  61. .tap(PLUGIN_NAME, handler);
  62. normalModuleFactory.hooks.parser
  63. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  64. .tap(PLUGIN_NAME, handler);
  65. normalModuleFactory.hooks.parser
  66. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  67. .tap(PLUGIN_NAME, handler);
  68. }
  69. );
  70. }
  71. }
  72. module.exports = ExportsInfoApiPlugin;