diff --git a/index.ts b/index.ts index ae35c4f..88d86f7 100644 --- a/index.ts +++ b/index.ts @@ -425,10 +425,32 @@ const visitImportDeclaration = (node: ts.ImportDeclaration) => { }; const visitImportCallExpression = (node: ts.CallExpression) => { - if (pathRewriting) { - if (ts.isStringLiteral(node.arguments[0])) { - const moduleSpecifier = node.arguments[0]; + if (ts.isStringLiteral(node.arguments[0])) { + const moduleSpecifier = node.arguments[0]; + if (imports) { + const match = imports.find(([alias]) => + moduleSpecifier.text.startsWith(alias) + ); + + if (match) { + let replacement = match[1]; + + // relative path: non absolute path that's not an @alias + if (!isAbsolute(replacement) && replacement.startsWith(".")) { + replacement = relative(dirname(filePath), replacement) + + (replacement.endsWith("/") ? "/" : ""); + } + + transformSpecifiers.push({ + pos: moduleSpecifier.pos, + alias: new RegExp("(['\"])" + RegExp.escape(match[0])), + replacement, + }); + } + } + + if (pathRewriting) { sourceCode = sourceCode.slice(0, moduleSpecifier.pos) + `"${moduleSpecifier.text.replace(/\.ts$/, ".js")}"` + sourceCode.slice(moduleSpecifier.end); diff --git a/tests/supported/cases/option-imports/input.ts b/tests/supported/cases/option-imports/input.ts index 63222f6..ca4c9c8 100644 --- a/tests/supported/cases/option-imports/input.ts +++ b/tests/supported/cases/option-imports/input.ts @@ -6,4 +6,11 @@ import { c, type C } from "$baz/bar"; export { b } from "$fiz/bar.ts"; export { type B } from "$foo/bar.d.ts"; -export { c, type C } from "$baz/bar"; \ No newline at end of file +export { c, type C } from "$baz/bar"; + +import("$foo/bar.ts"); +import("$fiz/bar.ts"); +import("$baz/bar"); + +// Expressions are not rewritten +import("$foo/bar" + ".ts"); diff --git a/tests/supported/cases/option-imports/output.js b/tests/supported/cases/option-imports/output.js index 12eaddc..0843787 100644 --- a/tests/supported/cases/option-imports/output.js +++ b/tests/supported/cases/option-imports/output.js @@ -3,4 +3,11 @@ import { b } from "../fiz/bar.js"; import { c,} from "@baz/bar"; export { b } from "../fiz/bar.js"; -export { c, } from "@baz/bar"; \ No newline at end of file +export { c, } from "@baz/bar"; + +import("../foo/bar.js"); +import("../fiz/bar.js"); +import("@baz/bar"); + +// Expressions are not rewritten +import("$foo/bar" + ".ts");