AliasPlugin.js
1.94 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
77
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
function startsWith(string, searchString) {
const stringLength = string.length;
const searchLength = searchString.length;
// early out if the search length is greater than the search string
if (searchLength > stringLength) {
return false;
}
let index = -1;
while (++index < searchLength) {
if (string.charCodeAt(index) !== searchString.charCodeAt(index)) {
return false;
}
}
return true;
}
module.exports = class AliasPlugin {
constructor(source, options, target) {
this.source = source;
this.options = Array.isArray(options) ? options : [options];
this.target = target;
}
apply(resolver) {
const target = resolver.ensureHook(this.target);
resolver
.getHook(this.source)
.tapAsync("AliasPlugin", (request, resolveContext, callback) => {
const innerRequest = request.request || request.path;
if (!innerRequest) return callback();
for (const item of this.options) {
if (
innerRequest === item.name ||
(!item.onlyModule && startsWith(innerRequest, item.name + "/"))
) {
if (
innerRequest !== item.alias &&
!startsWith(innerRequest, item.alias + "/")
) {
const newRequestStr =
item.alias + innerRequest.substr(item.name.length);
const obj = Object.assign({}, request, {
request: newRequestStr
});
return resolver.doResolve(
target,
obj,
"aliased with mapping '" +
item.name +
"': '" +
item.alias +
"' to '" +
newRequestStr +
"'",
resolveContext,
(err, result) => {
if (err) return callback(err);
// Don't allow other aliasing or raw request
if (result === undefined) return callback(null, null);
callback(null, result);
}
);
}
}
}
return callback();
});
}
};