-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
101 lines (85 loc) · 2.95 KB
/
index.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const path = require('path');
const glob = require('glob');
const fs = require('fs');
const OVERRIDE_FOLDER_PATH = './src/override';
module.exports = class PWAStudioOverridePlugin {
constructor(overrideRootPath = OVERRIDE_FOLDER_PATH) {
this.name = 'OverrideMappingPlugin';
this.moduleOverrideMap = this.getFilePaths(overrideRootPath);
}
getFilePaths(overrideRootPath) {
const getParsedRootPath = (root) => {
return root.replace(`${overrideRootPath}/`, '');
}
const getFiles = (dir, files_) => {
files_ = files_ || {};
const files = fs.readdirSync(dir);
for (const i in files){
const name = dir + '/' + files[i];
if (fs.statSync(name).isDirectory()){
getFiles(name, files_);
} else {
const parsedPath = getParsedRootPath(dir) + '/' + files[i];
files_[parsedPath] = dir + '/' + files[i];
}
}
return files_;
}
return getFiles(overrideRootPath);
}
requireResolveIfCan(id, options = undefined) {
try {
return require.resolve(id, options);
} catch (e) {
return undefined;
}
}
resolveModulePath(context, request) {
const filePathWithoutExtension = path.resolve(context, request);
const files = glob.sync(`${filePathWithoutExtension}@(|.*)`);
if (files.length === 0) {
throw new Error(`There is no file '${filePathWithoutExtension}'`);
}
if (files.length > 1) {
throw new Error(
`There is more than one file '${filePathWithoutExtension}'`
);
}
return require.resolve(files[0]);
}
resolveModuleOverrideMap(context, map) {
return Object.keys(map).reduce(
(result, x) => ({
...result,
[require.resolve(x)]:
this.requireResolveIfCan(map[x]) ||
this.resolveModulePath(context, map[x])
}),
{}
);
}
apply(compiler) {
if (Object.keys(this.moduleOverrideMap).length === 0) {
return;
}
const moduleMap = this.resolveModuleOverrideMap(
compiler.context,
this.moduleOverrideMap
);
compiler.hooks.normalModuleFactory.tap(this.name, nmf => {
nmf.hooks.beforeResolve.tap(this.name, resolve => {
if (!resolve) {
return;
}
const moduleToReplace = this.requireResolveIfCan(
resolve.request,
{ paths: [resolve.context] }
);
if (moduleToReplace && moduleMap[moduleToReplace]) {
resolve.request = moduleMap[moduleToReplace];
}
return resolve;
});
});
}
};