Skip to content

Commit

Permalink
fix(compiler): ensures transformed paths are relative paths for `dist…
Browse files Browse the repository at this point in the history
…-collection` (#4552)

* ensures transformed paths are relative paths

* fix test expected path
  • Loading branch information
tanner-reits committed Jul 14, 2023
1 parent cd5849c commit e11ac0e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
33 changes: 33 additions & 0 deletions src/compiler/transformers/map-imports-to-path-aliases.ts
Expand Up @@ -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;
}
}

Expand Down
Expand Up @@ -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
Expand Down

0 comments on commit e11ac0e

Please sign in to comment.