ImportMetaContextPlugin.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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").ResolveOptions} ResolveOptions */
  14. /** @typedef {import("../Compiler")} Compiler */
  15. const PLUGIN_NAME = "ImportMetaContextPlugin";
  16. class ImportMetaContextPlugin {
  17. /**
  18. * Apply the plugin
  19. * @param {Compiler} compiler the compiler instance
  20. * @returns {void}
  21. */
  22. apply(compiler) {
  23. compiler.hooks.compilation.tap(
  24. PLUGIN_NAME,
  25. (compilation, { contextModuleFactory, normalModuleFactory }) => {
  26. compilation.dependencyFactories.set(
  27. ImportMetaContextDependency,
  28. contextModuleFactory
  29. );
  30. compilation.dependencyTemplates.set(
  31. ImportMetaContextDependency,
  32. new ImportMetaContextDependency.Template()
  33. );
  34. compilation.dependencyFactories.set(
  35. ContextElementDependency,
  36. normalModuleFactory
  37. );
  38. const handler = (parser, parserOptions) => {
  39. if (
  40. parserOptions.importMetaContext !== undefined &&
  41. !parserOptions.importMetaContext
  42. )
  43. return;
  44. new ImportMetaContextDependencyParserPlugin().apply(parser);
  45. };
  46. normalModuleFactory.hooks.parser
  47. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  48. .tap(PLUGIN_NAME, handler);
  49. normalModuleFactory.hooks.parser
  50. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  51. .tap(PLUGIN_NAME, handler);
  52. }
  53. );
  54. }
  55. }
  56. module.exports = ImportMetaContextPlugin;