ImportMetaContextPlugin.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  15. /** @typedef {import("../Compiler")} Compiler */
  16. /** @typedef {import("../javascript/JavascriptParser")} Parser */
  17. const PLUGIN_NAME = "ImportMetaContextPlugin";
  18. class ImportMetaContextPlugin {
  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, { contextModuleFactory, normalModuleFactory }) => {
  28. compilation.dependencyFactories.set(
  29. ImportMetaContextDependency,
  30. contextModuleFactory
  31. );
  32. compilation.dependencyTemplates.set(
  33. ImportMetaContextDependency,
  34. new ImportMetaContextDependency.Template()
  35. );
  36. compilation.dependencyFactories.set(
  37. ContextElementDependency,
  38. normalModuleFactory
  39. );
  40. /**
  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. new ImportMetaContextDependencyParserPlugin().apply(parser);
  52. };
  53. normalModuleFactory.hooks.parser
  54. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  55. .tap(PLUGIN_NAME, handler);
  56. normalModuleFactory.hooks.parser
  57. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  58. .tap(PLUGIN_NAME, handler);
  59. }
  60. );
  61. }
  62. }
  63. module.exports = ImportMetaContextPlugin;