diff --git a/src/compiler/transformers/map-imports-to-path-aliases.ts b/src/compiler/transformers/map-imports-to-path-aliases.ts index c3910a0703f..2a1e73189c5 100644 --- a/src/compiler/transformers/map-imports-to-path-aliases.ts +++ b/src/compiler/transformers/map-imports-to-path-aliases.ts @@ -74,6 +74,39 @@ export const mapImportsToPathAliases = ( importPath = normalizePath( relative(dirname(destinationFilePath), resolvePathInDestination).replace(extensionRegex, '') ); + // if the importee is a sibling file of the importer then `relative` will + // produce a somewhat confusing result. We use `dirname` to get the + // directory of the importer, so for example, assume we have two files + // `foo/bar.ts` and `foo/baz.ts` like so: + // + // ``` + // foo + // ├── bar.ts + // └── baz.ts + // ``` + // + // then if `baz.ts` imports a symbol from `bar.ts` we'll call + // `relative(fromdir, to)` like so: + // + // ```ts + // relative(dirname("foo/baz.ts"), "foo/bar.ts") + // // equivalently + // relative("foo", "foo/bar.ts") + // ``` + // + // you'd think that in this case `relative` would return `'./bar.ts'` as + // a correct relative path to `bar.ts` from the `foo` directory, but + // actually in this case it returns just `bar.ts`. So since when updating + // import paths we're only concerned with `paths` aliases that should be + // transformed to relative imports anyway, we check to see if the new + // `importPath` starts with `'.'`, and add `'./'` if it doesn't, since + // otherwise Node will interpret `bar` as a module name, not a relative + // path. + // + // Note also that any relative paths as module specifiers which _don't_ + // need to be transformed (e.g. `'./foo'`) have already been handled + // above. + importPath = importPath.startsWith('.') ? importPath : './' + importPath; } } diff --git a/src/compiler/transformers/test/map-imports-to-path-aliases.spec.ts b/src/compiler/transformers/test/map-imports-to-path-aliases.spec.ts index 2dac82973bc..4d656d6c3f8 100644 --- a/src/compiler/transformers/test/map-imports-to-path-aliases.spec.ts +++ b/src/compiler/transformers/test/map-imports-to-path-aliases.spec.ts @@ -122,7 +122,7 @@ describe('mapImportsToPathAliases', () => { module = transpileModule(inputText, config, null, [], [mapImportsToPathAliases(config, '', outputTarget)]); - expect(module.outputText).toContain('import { utils } from "utils";'); + expect(module.outputText).toContain('import { utils } from "./utils";'); }); // The resolved module is not part of the output directory