1
- const resolve = require ( 'resolve' ) ;
2
- const path = require ( 'path' ) ;
3
-
4
- function opts ( file , config ) {
5
- return Object . assign (
6
- { extensions : [ '.ts' , '.tsx' , '.d.ts' ] } ,
7
- config ,
8
- // path.resolve will handle paths relative to CWD
9
- { basedir : path . dirname ( path . resolve ( file ) ) }
10
- ) ;
11
- }
1
+ 'use strict'
12
2
13
- module . exports = {
14
- interfaceVersion : 2 ,
15
- resolve : function ( source , file , config ) {
16
- if ( resolve . isCore ( source ) ) {
17
- return { found : true , path : null } ;
3
+ const path = require ( 'path' )
4
+ const resolve = require ( 'resolve' )
5
+ const tsconfigPaths = require ( 'tsconfig-paths' )
6
+ const debug = require ( 'debug' )
7
+
8
+ const log = debug ( 'eslint-import-resolver-typescript' )
9
+
10
+ /**
11
+ * @param {string } source the module to resolve; i.e './some-module'
12
+ * @param {string } file the importing file's full path; i.e. '/usr/local/bin/file.js'
13
+ */
14
+ function resolveFile ( source , file , config ) {
15
+ log ( 'looking for:' , source )
16
+
17
+ // don't worry about core node modules
18
+ if ( resolve . isCore ( source ) ) {
19
+ log ( 'matched core:' , source )
20
+
21
+ return {
22
+ found : true ,
23
+ path : null ,
18
24
}
25
+ }
26
+
27
+ // setup tsconfig-paths
28
+ const searchStart = config . directory || process . cwd ( )
29
+ const configLoaderResult = tsconfigPaths . loadConfig ( searchStart )
30
+ if ( configLoaderResult . resultType !== 'success' ) {
31
+ throw new Error ( `Unable to find tsconfig in ${ searchStart } : ${ configLoaderResult . message } ` )
32
+ }
33
+ const matchPath = tsconfigPaths . createMatchPath (
34
+ configLoaderResult . absoluteBaseUrl ,
35
+ configLoaderResult . paths ,
36
+ )
37
+
38
+ // look for files based on setup tsconfig "paths"
39
+ const extensions = Object . keys ( require . extensions ) . concat ( '.ts' , '.tsx' , '.d.ts' )
40
+ const foundTsPath = matchPath (
41
+ source ,
42
+ undefined ,
43
+ undefined ,
44
+ extensions ,
45
+ )
19
46
20
- try {
21
- return { found : true , path : resolve . sync ( source , opts ( file , config ) ) } ;
22
- } catch ( err ) {
23
- return { found : false } ;
47
+ if ( foundTsPath ) {
48
+ log ( 'matched ts path:' , foundTsPath )
49
+ }
50
+
51
+ // note that even if we match via tsconfig-paths, we still need to do a final resolve
52
+ const foundNodePath = resolve . sync ( foundTsPath || source , {
53
+ extensions,
54
+ basedir : path . dirname ( path . resolve ( file ) ) ,
55
+ } )
56
+
57
+ if ( foundNodePath ) {
58
+ log ( 'matched node path:' , foundNodePath )
59
+
60
+ return {
61
+ found : true ,
62
+ path : foundNodePath ,
24
63
}
25
- } ,
26
- } ;
64
+ }
65
+
66
+ log ( 'didnt find' , source )
67
+
68
+ return {
69
+ found : false
70
+ }
71
+ }
72
+
73
+ module . exports = {
74
+ interfaceVersion : 2 ,
75
+ resolve : resolveFile ,
76
+ }
0 commit comments