-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (65 loc) · 2.36 KB
/
index.js
File metadata and controls
76 lines (65 loc) · 2.36 KB
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
var fs = require('fs');
var path = require('path');
var resolutionCacheMap = {};
class AliasOverridePlugin {
/**
* @param pathRegExp
* @param pathReplacement
* @param exts
* @constructor
*/
constructor(pathRegExp, pathReplacement, exts) {
this.pathRegExp = pathRegExp;
this.pathReplacement = pathReplacement;
this.exts = exts || ['jsx', 'js'];
}
apply(resolver) {
var pathRegExp = this.pathRegExp;
var pathReplacement = this.pathReplacement;
var exts = this.exts;
resolver.plugin("normal-module-factory", function (nmf) {
nmf.plugin("before-resolve", function (result, callback) {
if (!result) return callback();
// test the request for a path match
if (pathRegExp.test(result.request)) {
// if it already has been resolved and cached return it
if (resolutionCacheMap[result.request]) {
result.request = resolutionCacheMap[result.request];
return callback(null, result);
}
const newFilePath = result.request.replace(pathRegExp, pathReplacement);
const fileExists = fs.existsSync(newFilePath);
// check for the file path after replacement, if exists, return it
if (fileExists) {
resolutionCacheMap[result.request] = newFilePath;
result.request = newFilePath;
return callback(null, result);
} else {
const fileExtension = path.extname(newFilePath);
// if the module doesn't have an extension, append the extension and check for it
if (!fileExtension) {
let foundFile = false;
exts.forEach(function (extension) {
const newFilePathWithExt = `${newFilePath}.${extension}`;
if (!foundFile && fs.existsSync(newFilePathWithExt)) {
foundFile = true;
resolutionCacheMap[result.request] = newFilePathWithExt;
result.request = newFilePathWithExt;
return callback(null, result);
}
});
if (!foundFile) {
return callback(null, result);
}
} else {
return callback(null, result);
}
}
} else {
return callback(null, result);
}
});
});
}
}
module.exports = AliasOverridePlugin;