-
Notifications
You must be signed in to change notification settings - Fork 0
/
migration-mapping.js
77 lines (67 loc) · 2.26 KB
/
migration-mapping.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
/**
* This webpack resolver is largely based on TypeScript's "paths" handling
* The TypeScript license can be found here:
* https://github.com/microsoft/TypeScript/blob/214df64e287804577afa1fea0184c18c40f7d1ca/LICENSE.txt
*
* refer to: https://github.com/vercel/next.js/blob/canary/packages/next/build/webpack/plugins/jsconfig-paths-plugin.ts
*/
function matchPatternOrExact(patternStrings, candidate) {
for (const patternString of patternStrings) {
if (patternString === candidate) {
// pattern was matched as is - no need to search further
return patternString;
} else if (candidate.endsWith(patternString)) {
return patternString;
}
}
}
class MigrationMappingPlugin {
constructor({ paths }) {
this.paths = paths;
}
apply(resolver) {
const target = resolver.ensureHook('resolve');
resolver
.getHook('described-resolve')
.tapAsync('MigrationMappingPlugin', (request, resolveContext, callback) => {
const paths = this.paths;
const pathsKeys = Object.keys(paths);
// If no aliases are added bail out
if (pathsKeys.length === 0) {
return callback();
}
const moduleName = request.request;
// If the module name does not match any of the patterns in `paths` we hand off resolving to webpack
const matchedPattern = matchPatternOrExact(pathsKeys, moduleName);
if (!matchedPattern) {
return callback();
}
if (!paths[matchedPattern]) return callback();
const curPath = paths[matchedPattern];
// Ensure .d.ts is not matched
if (curPath.endsWith('.d.ts')) {
// try next path candidate
return callback();
}
const candidate = curPath;
const obj = Object.assign({}, request, {
request: candidate,
});
resolver.doResolve(
target,
obj,
`Aliased for migration: ${matchedPattern} to ${candidate}`,
resolveContext,
(resolverErr, resolverResult) => {
if (resolverErr || resolverResult === undefined) {
return callback();
}
return callback(resolverErr, resolverResult);
}
);
});
}
}
module.exports = {
MigrationMappingPlugin,
};