From ef14ded3e995e3ea1cf0d641302c4424169e8bf4 Mon Sep 17 00:00:00 2001 From: NKDuy Date: Fri, 1 Dec 2023 08:45:10 +0700 Subject: [PATCH] fix(compiler): ensures transformed paths are relative paths for `dist-collection` --- .../map-imports-to-path-aliases.ts | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/compiler/transformers/map-imports-to-path-aliases.ts b/src/compiler/transformers/map-imports-to-path-aliases.ts index 3a07c7b8..ec69f30b 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; } }