ImportMetaContextPlugin.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const ContextElementDependency = require("./ContextElementDependency");
  7. const ImportMetaContextDependency = require("./ImportMetaContextDependency");
  8. const ImportMetaContextDependencyParserPlugin = require("./ImportMetaContextDependencyParserPlugin");
  9. /** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  10. /** @typedef {import("../Compiler")} Compiler */
  11. class ImportMetaContextPlugin {
  12. /**
  13. * Apply the plugin
  14. * @param {Compiler} compiler the compiler instance
  15. * @returns {void}
  16. */
  17. apply(compiler) {
  18. compiler.hooks.compilation.tap(
  19. "RequireContextPlugin",
  20. (compilation, { contextModuleFactory, normalModuleFactory }) => {
  21. compilation.dependencyFactories.set(
  22. ImportMetaContextDependency,
  23. contextModuleFactory
  24. );
  25. compilation.dependencyTemplates.set(
  26. ImportMetaContextDependency,
  27. new ImportMetaContextDependency.Template()
  28. );
  29. compilation.dependencyFactories.set(
  30. ContextElementDependency,
  31. normalModuleFactory
  32. );
  33. const handler = (parser, parserOptions) => {
  34. if (
  35. parserOptions.importMetaContext !== undefined &&
  36. !parserOptions.importMetaContext
  37. )
  38. return;
  39. new ImportMetaContextDependencyParserPlugin().apply(parser);
  40. };
  41. normalModuleFactory.hooks.parser
  42. .for("javascript/auto")
  43. .tap("ImportMetaContextPlugin", handler);
  44. normalModuleFactory.hooks.parser
  45. .for("javascript/esm")
  46. .tap("ImportMetaContextPlugin", handler);
  47. }
  48. );
  49. }
  50. }
  51. module.exports = ImportMetaContextPlugin;