Skip to content

Commit e6c51e0

Browse files
committed
fix: resolve only if file exists
1 parent 73568da commit e6c51e0

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

src/index.ts

+33-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { dirname, relative, resolve } from "path";
1+
import { dirname, relative, resolve, extname } from "path";
22
import ts from "typescript";
33
import slash from "slash";
44
import { parse } from "url";
5+
import { existsSync, statSync } from "fs";
56

67
const transformer = (_: ts.Program) => (context: ts.TransformationContext) => (
78
sourceFile: ts.SourceFile
@@ -13,6 +14,19 @@ const transformer = (_: ts.Program) => (context: ts.TransformationContext) => (
1314
const compilerOptions = context.getCompilerOptions();
1415
const sourceDir = dirname(sourceFile.fileName);
1516

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+
1630
const { isDeclarationFile } = sourceFile;
1731

1832
const { baseUrl = "", paths = {} } = compilerOptions;
@@ -29,12 +43,24 @@ const transformer = (_: ts.Program) => (context: ts.TransformationContext) => (
2943
return sourceFile;
3044
}
3145

46+
function isRelative(s: string) {
47+
return s[0] === ".";
48+
}
49+
3250
function isUrl(s: string) {
3351
return parse(s).protocol !== null;
3452
}
3553

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+
3662
function bindModuleToFile(moduleName: string) {
37-
if (moduleName[0] === ".") {
63+
if (isRelative(moduleName)) {
3864
// if it's relative path do not transform
3965
return moduleName;
4066
}
@@ -45,10 +71,13 @@ const transformer = (_: ts.Program) => (context: ts.TransformationContext) => (
4571
if (isUrl(out)) {
4672
return out;
4773
}
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}`;
5078
}
5179
}
80+
return undefined;
5281
}
5382

5483
function visit(node: ts.Node): ts.VisitResult<ts.Node> {

0 commit comments

Comments
 (0)