1
- import { dirname , relative , resolve } from "path" ;
1
+ import { dirname , relative , resolve , extname } from "path" ;
2
2
import ts from "typescript" ;
3
3
import slash from "slash" ;
4
4
import { parse } from "url" ;
5
+ import { existsSync , statSync } from "fs" ;
5
6
6
7
const transformer = ( _ : ts . Program ) => ( context : ts . TransformationContext ) => (
7
8
sourceFile : ts . SourceFile
@@ -13,6 +14,19 @@ const transformer = (_: ts.Program) => (context: ts.TransformationContext) => (
13
14
const compilerOptions = context . getCompilerOptions ( ) ;
14
15
const sourceDir = dirname ( sourceFile . fileName ) ;
15
16
17
+ const implicitExtensions = [ ".ts" , ".d.ts" ] ;
18
+
19
+ const allowJs = compilerOptions . allowJs === true ;
20
+ const allowJsx =
21
+ compilerOptions . jsx !== undefined &&
22
+ compilerOptions . jsx !== ts . JsxEmit . None ;
23
+ const allowJson = compilerOptions . resolveJsonModule === true ;
24
+
25
+ allowJs && implicitExtensions . push ( ".js" ) ;
26
+ allowJsx && implicitExtensions . push ( ".tsx" ) ;
27
+ allowJs && allowJsx && implicitExtensions . push ( ".jsx" ) ;
28
+ allowJson && implicitExtensions . push ( ".json" ) ;
29
+
16
30
const { isDeclarationFile } = sourceFile ;
17
31
18
32
const { baseUrl = "" , paths = { } } = compilerOptions ;
@@ -29,12 +43,24 @@ const transformer = (_: ts.Program) => (context: ts.TransformationContext) => (
29
43
return sourceFile ;
30
44
}
31
45
46
+ function isRelative ( s : string ) {
47
+ return s [ 0 ] === "." ;
48
+ }
49
+
32
50
function isUrl ( s : string ) {
33
51
return parse ( s ) . protocol !== null ;
34
52
}
35
53
54
+ function fileExists ( s : string ) {
55
+ // if has extensions, file must exist
56
+ if ( extname ( s ) !== "" ) return existsSync ( s ) ;
57
+ // else check for implicit extensions .ts, .dts, etc...
58
+ for ( const ext of implicitExtensions ) if ( existsSync ( s + ext ) ) return true ;
59
+ return false ;
60
+ }
61
+
36
62
function bindModuleToFile ( moduleName : string ) {
37
- if ( moduleName [ 0 ] === "." ) {
63
+ if ( isRelative ( moduleName ) ) {
38
64
// if it's relative path do not transform
39
65
return moduleName ;
40
66
}
@@ -45,10 +71,13 @@ const transformer = (_: ts.Program) => (context: ts.TransformationContext) => (
45
71
if ( isUrl ( out ) ) {
46
72
return out ;
47
73
}
48
- const file = slash ( relative ( sourceDir , resolve ( baseUrl , out ) ) ) ;
49
- return file [ 0 ] === "." ? file : `./${ file } ` ;
74
+ const filepath = resolve ( baseUrl , out ) ;
75
+ if ( ! fileExists ( `${ filepath } /index` ) && ! fileExists ( filepath ) ) continue ;
76
+ const resolved = slash ( relative ( sourceDir , filepath ) ) ;
77
+ return isRelative ( resolved ) ? resolved : `./${ resolved } ` ;
50
78
}
51
79
}
80
+ return undefined ;
52
81
}
53
82
54
83
function visit ( node : ts . Node ) : ts . VisitResult < ts . Node > {
0 commit comments