I have an index.ts file with multiple exports in my react + typescript project. I am using that file to import things from. I have more than one index.ts in my project and this sometimes causes circular dependencies in my project especially when writing tests using jest.
My question is that what will happen when I import one or more things from index.ts files? Does webpack use this file to find paths and load only the requested module using the path or all exported things are loaded in the function? ( do A and B load into C or only A will be loaded into C by webpack in the below example?)
here is one simple pattern of such a circular dependency:
// -- index.ts --
export {default as A} from './A'
export {default as B} from './B'
export {default as C} from './C'
// -- A.tsx --
import { B, C } from './index'
export class A{
/* as is */
}
// -- B.tsx --
import { A} from './index'
export class B extends A {
/* as is */
}
// -- C.tsx --
import { A} from './index'
export class C extends A {
/* as is */
}
accoriding to this, I assume that there is a central repository for webpack that all theses imports are cached there and whenever an import occures, it will check there first and if no match found, it will try to find the module. In this case, my assumption that all index.ts exports are loaded is wrong.
I am looking for help to answer my ambiguity about all these behaviors of webpack, nodeJs, typescript or anything that is responsible for this
Webpack only loads the specific modules that are imported in your code and not the entire file.
In the example you provided, when you import B and C from index.ts in A.tsx, webpack will only load the B and C modules and not the entire index.ts file. Similarly, when you import A from index.ts in B.tsx and C.tsx, only the A module will be loaded.
As for your question about circular dependencies, webpack can handle circular dependencies, but it can lead to unexpected behavior. It's best to avoid them whenever possible in order to have a maintainable codebase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With