ImportMetaContextPlugin.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const {
  7. JAVASCRIPT_MODULE_TYPE_AUTO,
  8. JAVASCRIPT_MODULE_TYPE_ESM
  9. } = require("../ModuleTypeConstants");
  10. const ContextElementDependency = require("./ContextElementDependency");
  11. const ImportMetaContextDependency = require("./ImportMetaContextDependency");
  12. const ImportMetaContextDependencyParserPlugin = require("./ImportMetaContextDependencyParserPlugin");
  13. /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
  14. /** @typedef {import("../Compiler")} Compiler */
  15. /** @typedef {import("../javascript/JavascriptParser")} Parser */
  16. const PLUGIN_NAME = "ImportMetaContextPlugin";
  17. class ImportMetaContextPlugin {
  18. /**
  19. * Applies the plugin by registering its hooks on the compiler.
  20. * @param {Compiler} compiler the compiler instance
  21. * @returns {void}
  22. */
  23. apply(compiler) {
  24. compiler.hooks.compilation.tap(
  25. PLUGIN_NAME,
  26. (compilation, { contextModuleFactory, normalModuleFactory }) => {
  27. compilation.dependencyFactories.set(
  28. ImportMetaContextDependency,
  29. contextModuleFactory
  30. );
  31. compilation.dependencyTemplates.set(
  32. ImportMetaContextDependency,
  33. new ImportMetaContextDependency.Template()
  34. );
  35. compilation.dependencyFactories.set(
  36. ContextElementDependency,
  37. normalModuleFactory
  38. );
  39. /**
  40. * Handles the hook callback for this code path.
  41. * @param {Parser} parser parser parser
  42. * @param {JavascriptParserOptions} parserOptions parserOptions
  43. * @returns {void}
  44. */
  45. const handler = (parser, parserOptions) => {
  46. if (
  47. parserOptions.importMetaContext !== undefined &&
  48. !parserOptions.importMetaContext
  49. ) {
  50. return;
  51. }
  52. new ImportMetaContextDependencyParserPlugin().apply(parser);
  53. };
  54. normalModuleFactory.hooks.parser
  55. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  56. .tap(PLUGIN_NAME, handler);
  57. normalModuleFactory.hooks.parser
  58. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  59. .tap(PLUGIN_NAME, handler);
  60. }
  61. );
  62. }
  63. }
  64. module.exports = ImportMetaContextPlugin;