UNPKG

2.64 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
4*/
5
6"use strict";
7
8const createSchemaValidation = require("../util/create-schema-validation");
9const ContainerEntryDependency = require("./ContainerEntryDependency");
10const ContainerEntryModuleFactory = require("./ContainerEntryModuleFactory");
11const ContainerExposedDependency = require("./ContainerExposedDependency");
12const { parseOptions } = require("./options");
13
14/** @typedef {import("../../declarations/plugins/container/ContainerPlugin").ContainerPluginOptions} ContainerPluginOptions */
15/** @typedef {import("../Compiler")} Compiler */
16
17const validate = createSchemaValidation(
18 require("../../schemas/plugins/container/ContainerPlugin.check.js"),
19 () => require("../../schemas/plugins/container/ContainerPlugin.json"),
20 {
21 name: "Container Plugin",
22 baseDataPath: "options"
23 }
24);
25
26const PLUGIN_NAME = "ContainerPlugin";
27
28class ContainerPlugin {
29 /**
30 * @param {ContainerPluginOptions} options options
31 */
32 constructor(options) {
33 validate(options);
34
35 this._options = {
36 name: options.name,
37 shareScope: options.shareScope || "default",
38 library: options.library || {
39 type: "var",
40 name: options.name
41 },
42 filename: options.filename || undefined,
43 exposes: parseOptions(
44 options.exposes,
45 item => ({
46 import: Array.isArray(item) ? item : [item],
47 name: undefined
48 }),
49 item => ({
50 import: Array.isArray(item.import) ? item.import : [item.import],
51 name: item.name || undefined
52 })
53 )
54 };
55 }
56
57 /**
58 * Apply the plugin
59 * @param {Compiler} compiler the compiler instance
60 * @returns {void}
61 */
62 apply(compiler) {
63 const { name, exposes, shareScope, filename, library } = this._options;
64
65 compiler.options.output.enabledLibraryTypes.push(library.type);
66
67 compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
68 const dep = new ContainerEntryDependency(name, exposes, shareScope);
69 dep.loc = { name };
70 compilation.addEntry(
71 compilation.options.context,
72 dep,
73 {
74 name,
75 filename,
76 library
77 },
78 error => {
79 if (error) return callback(error);
80 callback();
81 }
82 );
83 });
84
85 compiler.hooks.thisCompilation.tap(
86 PLUGIN_NAME,
87 (compilation, { normalModuleFactory }) => {
88 compilation.dependencyFactories.set(
89 ContainerEntryDependency,
90 new ContainerEntryModuleFactory()
91 );
92
93 compilation.dependencyFactories.set(
94 ContainerExposedDependency,
95 normalModuleFactory
96 );
97 }
98 );
99 }
100}
101
102module.exports = ContainerPlugin;