1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 | function startsWith(string, searchString) {
|
8 | const stringLength = string.length;
|
9 | const searchLength = searchString.length;
|
10 |
|
11 |
|
12 | if(searchLength > stringLength) {
|
13 | return false;
|
14 | }
|
15 | let index = -1;
|
16 | while(++index < searchLength) {
|
17 | if(string.charCodeAt(index) !== searchString.charCodeAt(index)) {
|
18 | return false;
|
19 | }
|
20 | }
|
21 | return true;
|
22 | }
|
23 |
|
24 | module.exports = class AliasPlugin {
|
25 | constructor(source, options, target) {
|
26 | this.source = source;
|
27 | this.options = Array.isArray(options) ? options : [options];
|
28 | this.target = target;
|
29 | }
|
30 |
|
31 | apply(resolver) {
|
32 | const target = resolver.ensureHook(this.target);
|
33 | resolver.getHook(this.source).tapAsync("AliasPlugin", (request, resolveContext, callback) => {
|
34 | const innerRequest = request.request;
|
35 | if(!innerRequest) return callback();
|
36 | for(const item of this.options) {
|
37 | if(innerRequest === item.name || (!item.onlyModule && startsWith(innerRequest, item.name + "/"))) {
|
38 | if(innerRequest !== item.alias && !startsWith(innerRequest, item.alias + "/")) {
|
39 | const newRequestStr = item.alias + innerRequest.substr(item.name.length);
|
40 | const obj = Object.assign({}, request, {
|
41 | request: newRequestStr
|
42 | });
|
43 | return resolver.doResolve(target, obj, "aliased with mapping '" + item.name + "': '" + item.alias + "' to '" + newRequestStr + "'", resolveContext, (err, result) => {
|
44 | if(err) return callback(err);
|
45 |
|
46 |
|
47 | if(result === undefined) return callback(null, null);
|
48 | callback(null, result);
|
49 | });
|
50 | }
|
51 | }
|
52 | }
|
53 | return callback();
|
54 | });
|
55 | }
|
56 | };
|