ExportsInfoApiPlugin.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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("./Dependency").DependencyLocation} DependencyLocation */
  15. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  16. /** @typedef {import("./javascript/JavascriptParser").Range} Range */
  17. const PLUGIN_NAME = "ExportsInfoApiPlugin";
  18. class ExportsInfoApiPlugin {
  19. /**
  20. * Apply the plugin
  21. * @param {Compiler} compiler the compiler instance
  22. * @returns {void}
  23. */
  24. apply(compiler) {
  25. compiler.hooks.compilation.tap(
  26. PLUGIN_NAME,
  27. (compilation, { normalModuleFactory }) => {
  28. compilation.dependencyTemplates.set(
  29. ExportsInfoDependency,
  30. new ExportsInfoDependency.Template()
  31. );
  32. /**
  33. * @param {JavascriptParser} parser the parser
  34. * @returns {void}
  35. */
  36. const handler = parser => {
  37. parser.hooks.expressionMemberChain
  38. .for("__webpack_exports_info__")
  39. .tap(PLUGIN_NAME, (expr, members) => {
  40. const dep =
  41. members.length >= 2
  42. ? new ExportsInfoDependency(
  43. /** @type {Range} */ (expr.range),
  44. members.slice(0, -1),
  45. members[members.length - 1]
  46. )
  47. : new ExportsInfoDependency(
  48. /** @type {Range} */ (expr.range),
  49. null,
  50. members[0]
  51. );
  52. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  53. parser.state.module.addDependency(dep);
  54. return true;
  55. });
  56. parser.hooks.expression
  57. .for("__webpack_exports_info__")
  58. .tap(PLUGIN_NAME, expr => {
  59. const dep = new ConstDependency(
  60. "true",
  61. /** @type {Range} */ (expr.range)
  62. );
  63. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  64. parser.state.module.addPresentationalDependency(dep);
  65. return true;
  66. });
  67. };
  68. normalModuleFactory.hooks.parser
  69. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  70. .tap(PLUGIN_NAME, handler);
  71. normalModuleFactory.hooks.parser
  72. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  73. .tap(PLUGIN_NAME, handler);
  74. normalModuleFactory.hooks.parser
  75. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  76. .tap(PLUGIN_NAME, handler);
  77. }
  78. );
  79. }
  80. }
  81. module.exports = ExportsInfoApiPlugin;