ExportsInfoApiPlugin.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 {
  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. /** @import Compiler from "./Compiler" */
  14. /** @import JavascriptParser, { Range } from "./javascript/JavascriptParser" */
  15. const PLUGIN_NAME = "ExportsInfoApiPlugin";
  16. class ExportsInfoApiPlugin {
  17. /**
  18. * Applies the plugin by registering its hooks on the compiler.
  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. * Handles the hook callback for this code path.
  32. * @param {JavascriptParser} parser the parser
  33. * @returns {void}
  34. */
  35. const handler = (parser) => {
  36. parser.hooks.expressionMemberChain
  37. .for("__webpack_exports_info__")
  38. .tap(PLUGIN_NAME, (expr, members) => {
  39. const dep =
  40. members.length >= 2
  41. ? new ExportsInfoDependency(
  42. /** @type {Range} */ (expr.range),
  43. members.slice(0, -1),
  44. members[members.length - 1]
  45. )
  46. : new ExportsInfoDependency(
  47. /** @type {Range} */ (expr.range),
  48. null,
  49. members[0]
  50. );
  51. dep.loc = parser.getLocation(expr);
  52. parser.state.module.addDependency(dep);
  53. return true;
  54. });
  55. parser.hooks.expression
  56. .for("__webpack_exports_info__")
  57. .tap(PLUGIN_NAME, (expr) => {
  58. const dep = new ConstDependency(
  59. "true",
  60. /** @type {Range} */ (expr.range)
  61. );
  62. dep.loc = parser.getLocation(expr);
  63. parser.state.module.addPresentationalDependency(dep);
  64. return true;
  65. });
  66. };
  67. normalModuleFactory.hooks.parser
  68. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  69. .tap(PLUGIN_NAME, handler);
  70. normalModuleFactory.hooks.parser
  71. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  72. .tap(PLUGIN_NAME, handler);
  73. normalModuleFactory.hooks.parser
  74. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  75. .tap(PLUGIN_NAME, handler);
  76. }
  77. );
  78. }
  79. }
  80. module.exports = ExportsInfoApiPlugin;