JavascriptMetaInfoPlugin.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sergey Melyukov @smelukov
  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 InnerGraph = require("./optimize/InnerGraph");
  12. /** @typedef {import("./Compiler")} Compiler */
  13. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  14. const PLUGIN_NAME = "JavascriptMetaInfoPlugin";
  15. class JavascriptMetaInfoPlugin {
  16. /**
  17. * Apply the plugin
  18. * @param {Compiler} compiler the compiler instance
  19. * @returns {void}
  20. */
  21. apply(compiler) {
  22. compiler.hooks.compilation.tap(
  23. PLUGIN_NAME,
  24. (compilation, { normalModuleFactory }) => {
  25. /**
  26. * @param {JavascriptParser} parser the parser
  27. * @returns {void}
  28. */
  29. const handler = parser => {
  30. parser.hooks.call.for("eval").tap(PLUGIN_NAME, () => {
  31. parser.state.module.buildInfo.moduleConcatenationBailout = "eval()";
  32. parser.state.module.buildInfo.usingEval = true;
  33. const currentSymbol = InnerGraph.getTopLevelSymbol(parser.state);
  34. if (currentSymbol) {
  35. InnerGraph.addUsage(parser.state, null, currentSymbol);
  36. } else {
  37. InnerGraph.bailout(parser.state);
  38. }
  39. });
  40. parser.hooks.finish.tap(PLUGIN_NAME, () => {
  41. let topLevelDeclarations =
  42. parser.state.module.buildInfo.topLevelDeclarations;
  43. if (topLevelDeclarations === undefined) {
  44. topLevelDeclarations =
  45. parser.state.module.buildInfo.topLevelDeclarations = new Set();
  46. }
  47. for (const name of parser.scope.definitions.asSet()) {
  48. const freeInfo = parser.getFreeInfoFromVariable(name);
  49. if (freeInfo === undefined) {
  50. topLevelDeclarations.add(name);
  51. }
  52. }
  53. });
  54. };
  55. normalModuleFactory.hooks.parser
  56. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  57. .tap(PLUGIN_NAME, handler);
  58. normalModuleFactory.hooks.parser
  59. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  60. .tap(PLUGIN_NAME, handler);
  61. normalModuleFactory.hooks.parser
  62. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  63. .tap(PLUGIN_NAME, handler);
  64. }
  65. );
  66. }
  67. }
  68. module.exports = JavascriptMetaInfoPlugin;