In my repository, the structure is as follows:
src/
index.ts
main.ts
bar/
file.ts
index.ts
foo/
fooFile.ts
The purpose of src/index
is to serve as a top-level index file that exports all elements in my package.
However, I have noticed an unexpected behavior where calling certain functionalities within this file becomes necessary. I will elaborate on this shortly.
src/bar/file.ts
simply exports a plain string.
src/foo/fooFile.ts
imports this string from the parent index using ..
.
// comments refer to the outcome when running `node lib/index.js`
import { fileName } from "..";
import {fileName as fileName2} from "../bar";
export const test = "test";
const myData = {
data: fileName, // Resolves to undefined
data2: fileName2 //Resolves to "bar"
};
export function main() {
console.log(myData);
console.log(fileName); // Resolves to "bar"
}
If my src/index.ts
is coded like this:
import {main} from "./foo/fooFile";
export * from "./bar";
export * from "./foo/fooFile";
main();
This leads to asynchronous behavior - where importing fileName
resolves as undefined during declaration of myData
constant, but resolves the string at runtime.
On the other hand, if I import from ../bar
, the string appears in both instances.
Output:
{ data: undefined, data2: 'bar' }
bar
Notably, this behavior only surfaces when the main()
function is called from the index file. When done in main.ts
:
import {main} from "./index";
main();
The output differs:
{ data: 'bar', data2: 'bar' }
bar
I suspect this behavior is linked to node module resolution and cyclic dependencies - can anyone provide insight into why this occurs?
Repository link for reference: https://github.com/dwjohnston/import-from-parent-issue
Please note that I've used TypeScript for this demonstration - although unlikely, it's the most effective way for me to replicate the issue at hand.