aboutsummaryrefslogtreecommitdiffstats
path: root/config/webpack/plugins/create-injected-shared-modules-webpack-plugin.js
blob: 695d4efaa75cc4bbadc0d15970d7b3a54d54e936 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import path from "path";
import fs from "fs";
import webpack from "webpack";

import { getFileName } from "../utils/build-file.js";

class CreateInjectedSharedModulesPlugin {
	constructor({ injectedSharedModulesImportedCount, sortedSharedModules }) {
		this.injectedSharedModulesImportedCount = injectedSharedModulesImportedCount;
		this.sortedSharedModules = sortedSharedModules;
	}

	apply(compiler) {
		compiler.hooks.compilation.tap("CreateInjectedSharedModulesPlugin", compilation => {
			compilation.hooks.processAssets.tap(
				{
					name: "CreateInjectedSharedModulesPlugin",
					stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
				},
				assets => {
					const injectedSharedScripts = this.sortedSharedModules
						.filter(sharedModule => this.injectedSharedModulesImportedCount[sharedModule] > 0)
						.map(sharedModule => `shared/${getFileName(sharedModule, "shared")}.js`);

					if (injectedSharedScripts.length > 0) {
						const scriptInjectorModuleName = getFileName("script-injector", "shared", true);
						const injectionCode = injectedSharedScripts
							.map(injectedScript => `$${scriptInjectorModuleName}.injectScriptHead("shared/${path.basename(injectedScript)}");`)
							.join("");
						compilation.emitAsset(
							`shared/${getFileName("injected-shared-modules", "shared")}.js`,
							new webpack.sources.RawSource(injectionCode)
						);
					}
				}
			);
		});
	}
}

export default CreateInjectedSharedModulesPlugin;