aboutsummaryrefslogtreecommitdiffstats
path: root/config/webpack/plugins/create-manifest-webpack-plugin/index.js
blob: 6bbb485e96b3dd11f537427e55989d09ec492784 (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const { sources } = require("webpack");
const path = require("path");

const { version } = require(path.resolve(process.env.ROOT_DIR, "package.json"));

const getRunAt = scriptType => {
	switch (scriptType) {
		case "before":
		case "injected":
		case "injected_and_loaded":
			return "document_start";

		case "rendered":
			return "document_end";

		case "loaded":
		default:
			return "document_idle";
	}
};

class CreateManifestPlugin {
	constructor({ scripts }) {
		this.scripts = {};
		this.manifest = require("./manifest-template.json");
		this.scripts.before = scripts.before || {};
		this.scripts.injected = scripts.injected || {};
		this.scripts.injected_and_loaded = scripts.injected_and_loaded || {};
		this.scripts.rendered = scripts.rendered || {};
		this.scripts.loaded = scripts.loaded || {};
	}

	apply(compiler) {
		compiler.hooks.compilation.tap("CreateManifestPlugin", compilation => {
			compilation.hooks.processAssets.tap(
				{
					name: "CreateManifestPlugin",
					stage: compiler.webpack.Compilation.PROCESS_ASSETS_ADDITIONAL,
					additionalAssets: true
				},
				() => {
					this.manifest.version = version;
					this.manifest.content_scripts = []

					for (const scriptType in this.scripts) {
						if (Object.keys(this.scripts[scriptType]).length > 0) {
							const currentScripts = this.scripts[scriptType];

							let paths = {};
							for (const scriptName in currentScripts) {
								const scriptPath = currentScripts[scriptName];
								if (!path[scriptPath]) {
									paths[scriptPath] = [];
								}
								paths[scriptPath].push(scriptName);
							}

							for (const scriptPath in paths) {
								this.manifest.content_scripts.push({
									matches: [`*://banglarbhumi.gov.in/${scriptPath}`],
									js: [`${scriptType}.js`],
									run_at: getRunAt(scriptType)
								});
							}
						}
					}

					compilation.updateAsset(
						"manifest.json",
						new sources.RawSource(JSON.stringify(this.manifest))
					);
				}
			);
		});
	}
}

module.exports = CreateManifestPlugin;