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

const { getInjectionCode } = webpackRequire("utils/get-injection-code");

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_ANALYSE,
					additionalAssets: true
				},
				async assets => {
					for (const assetName in assets) {
						if (/\.js$/.test(assetName)) {
							compilation.updateAsset(
								assetName,
								new sources.RawSource(
									getInjectionCode(
										compilation.getAsset(assetName).source.source(),
										this.insertedBefore
									)
								)
							);
						}
					}
				}
			);
		});
	}
}

module.exports = InjectScriptPlugin;