-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathimport-resolver.js
95 lines (81 loc) · 1.85 KB
/
import-resolver.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
/* eslint-env es6 */
/**
* External dependencies.
*/
const resolverTS = require( 'eslint-import-resolver-typescript' );
const path = require( 'path' );
exports.interfaceVersion = 2;
/**
* Eslint configuration for resolving TypeScript aliases.
*
* @param source Import string.
* @param file File-path in which alias is used.
* @param config configuration.
*
* @return Resolved path.
*/
exports.resolve = function ( source, file, config ) {
/**
* Creates a path resolver.
*
* @param sourcePath Import string.
*
* @return Path resolver.
*/
const resolve = ( sourcePath ) =>
resolverTS.resolve( sourcePath, file, { ...config } );
const aliasPaths = {
'@/': 'src/',
'@graphqlTypes/': 'src/__generated/',
};
const aliases = Object.keys( aliasPaths );
for ( const alias of aliases ) {
const resolvedPath = resolvePath(
source,
alias,
aliasPaths[ alias ],
file,
resolve
);
if ( resolvedPath ) {
return resolvedPath;
}
}
return resolve( source );
};
/**
* Resolves TS paths.
*
* @param source Import string.
* @param alias Alias to search.
* @param aliasPath Alias path.
* @param file File-path in which alias is used.
* @param resolve Path resolver.
*
* @return Resolved path on success | False if alias is not found in import string.
*/
function resolvePath( source, alias, aliasPath, file, resolve ) {
if ( ! source.startsWith( alias ) ) {
return false;
}
const packageName = source.slice( alias.length );
const slicedAliasPath = aliasPath.slice(
aliasPath.indexOf( 'src' ) + 'src'.length + 1
);
const result = resolve(
path.join(
file.slice( 0, file.indexOf( 'src' ) + 'src'.length ),
slicedAliasPath,
packageName
)
);
if ( result.found ) {
return result;
}
return resolve(
path.join(
file.slice( 0, file.indexOf( 'src' ) + 'src'.length ),
packageName
)
);
}