UNPKG

1.67 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Ivan Kopeykin @vankop
4*/
5
6"use strict";
7
8const ContextElementDependency = require("./ContextElementDependency");
9const ImportMetaContextDependency = require("./ImportMetaContextDependency");
10const ImportMetaContextDependencyParserPlugin = require("./ImportMetaContextDependencyParserPlugin");
11
12/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
13/** @typedef {import("../Compiler")} Compiler */
14
15class ImportMetaContextPlugin {
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 "RequireContextPlugin",
24 (compilation, { contextModuleFactory, normalModuleFactory }) => {
25 compilation.dependencyFactories.set(
26 ImportMetaContextDependency,
27 contextModuleFactory
28 );
29 compilation.dependencyTemplates.set(
30 ImportMetaContextDependency,
31 new ImportMetaContextDependency.Template()
32 );
33 compilation.dependencyFactories.set(
34 ContextElementDependency,
35 normalModuleFactory
36 );
37
38 const handler = (parser, parserOptions) => {
39 if (
40 parserOptions.importMetaContext !== undefined &&
41 !parserOptions.importMetaContext
42 )
43 return;
44
45 new ImportMetaContextDependencyParserPlugin().apply(parser);
46 };
47
48 normalModuleFactory.hooks.parser
49 .for("javascript/auto")
50 .tap("ImportMetaContextPlugin", handler);
51 normalModuleFactory.hooks.parser
52 .for("javascript/esm")
53 .tap("ImportMetaContextPlugin", handler);
54 }
55 );
56 }
57}
58
59module.exports = ImportMetaContextPlugin;