aboutsummaryrefslogtreecommitdiffstats
path: root/config/webpack/loader/arrange-shared-module-loader.js
blob: 31c5d61b5c0e09e0828677872d9211ab89681b2c (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
import path from "path";

import { ImportManager } from "import-manager";

import sharedModules from "../utils/shared-modules.js";

/**
 * Webpack loader that arranges shared modules in dependency order.
 * As each shared module is processed, its own shared-module dependencies
 * are inserted before it in the global `sortedSharedModules` array so that
 * the final output respects the import graph.
 *
 * @param {string} source - The source code of the current module.
 * @returns {string} The unmodified source (this loader is side-effect only).
 */
export default function(source) {
	const currentSharedModuleName = path.basename(this.resourcePath.substring(0, this.resourcePath.length - 3));

	if (sharedModules.includes(currentSharedModuleName)) {
		const { sortedSharedModules } = this.getOptions();
		const manager = new ImportManager(source);
		const modulesToBeIncluded = [];

		for (const unit of manager.imports.es6.units) {
			const moduleIndex = sharedModules.indexOf(unit.module.name);

			if (moduleIndex >= 0) {
				const currentSharedModuleName = sharedModules[moduleIndex];

				if (!(sortedSharedModules.includes(currentSharedModuleName) || modulesToBeIncluded.includes(currentSharedModuleName))) {
					modulesToBeIncluded.push(currentSharedModuleName);
				}
			}
		}

		const currentModuleIndex = sortedSharedModules.indexOf(currentSharedModuleName);

		if (currentModuleIndex >= 0) {
			for (const sharedModule of modulesToBeIncluded) {
				sortedSharedModules.splice(currentModuleIndex, 0, sharedModule);
			}
		} else {
			for (const sharedModule of modulesToBeIncluded) {
				sortedSharedModules.push(sharedModule);
			}

			sortedSharedModules.push(currentSharedModuleName);
		}
	}

	return source;
};