Skip to content

Commit e11ac0e

Browse files
authoredJul 14, 2023
fix(compiler): ensures transformed paths are relative paths for dist-collection (#4552)
* ensures transformed paths are relative paths * fix test expected path
1 parent cd5849c commit e11ac0e

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed
 

‎src/compiler/transformers/map-imports-to-path-aliases.ts

+33
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,39 @@ export const mapImportsToPathAliases = (
7474
importPath = normalizePath(
7575
relative(dirname(destinationFilePath), resolvePathInDestination).replace(extensionRegex, '')
7676
);
77+
// if the importee is a sibling file of the importer then `relative` will
78+
// produce a somewhat confusing result. We use `dirname` to get the
79+
// directory of the importer, so for example, assume we have two files
80+
// `foo/bar.ts` and `foo/baz.ts` like so:
81+
//
82+
// ```
83+
// foo
84+
// ├── bar.ts
85+
// └── baz.ts
86+
// ```
87+
//
88+
// then if `baz.ts` imports a symbol from `bar.ts` we'll call
89+
// `relative(fromdir, to)` like so:
90+
//
91+
// ```ts
92+
// relative(dirname("foo/baz.ts"), "foo/bar.ts")
93+
// // equivalently
94+
// relative("foo", "foo/bar.ts")
95+
// ```
96+
//
97+
// you'd think that in this case `relative` would return `'./bar.ts'` as
98+
// a correct relative path to `bar.ts` from the `foo` directory, but
99+
// actually in this case it returns just `bar.ts`. So since when updating
100+
// import paths we're only concerned with `paths` aliases that should be
101+
// transformed to relative imports anyway, we check to see if the new
102+
// `importPath` starts with `'.'`, and add `'./'` if it doesn't, since
103+
// otherwise Node will interpret `bar` as a module name, not a relative
104+
// path.
105+
//
106+
// Note also that any relative paths as module specifiers which _don't_
107+
// need to be transformed (e.g. `'./foo'`) have already been handled
108+
// above.
109+
importPath = importPath.startsWith('.') ? importPath : './' + importPath;
77110
}
78111
}
79112

‎src/compiler/transformers/test/map-imports-to-path-aliases.spec.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ describe('mapImportsToPathAliases', () => {
122122

123123
module = transpileModule(inputText, config, null, [], [mapImportsToPathAliases(config, '', outputTarget)]);
124124

125-
expect(module.outputText).toContain('import { utils } from "utils";');
125+
expect(module.outputText).toContain('import { utils } from "./utils";');
126126
});
127127

128128
// The resolved module is not part of the output directory

0 commit comments

Comments
 (0)
Please sign in to comment.