aboutsummaryrefslogtreecommitdiffstats
path: root/config/webpack/plugins/inject-script-webpack-plugin.js
blob: 599871bbb9e2f9fce8bc49daf4cc535d87dbfac3 (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
const { sources } = require("webpack");
const path = require("path");

const { getFileNameHash } = webpackRequire("utils/filename-hash");

class InjectScriptPlugin {
	constructor(insertedBefore = false) {
		this.insertedBefore = insertedBefore;
	}

	apply(compiler) {
		compiler.hooks.compilation.tap("InjectScriptPlugin", compilation => {
			compilation.hooks.processAssets.tapPromise(
				{
					name: "InjectScriptPlugin",
					stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
					additionalAssets: true
				},
				async assets => {
					for (const assetName in assets) {
						if (/\.js$/.test(assetName)) {
							assets["scripts/" + path.basename(assetName)] = new sources.RawSource(
								`$${getFileNameHash("script-injector", "shared", true)}.injectScriptHead("scripts/injected/${path.basename(assetName)}");`
							);
						}
					}
				}
			);
		});
	}
}

module.exports = InjectScriptPlugin;