Imagine the following setup:
There is an api that contains let's say a folder foo
and bar
. These folders export all their public stuff to their local index.ts
which will just re-export the public stuff via export * from [...]
to make it more convenient.
In my example, there is a circular dependency, because foo.ts
requires a part of bar
and vice-versa - and I totally understand why this is the case.
See screenshot below:
How can I resolve this in an environment with hundreds of classes, functions, constants, types, enums, etc. effectively with TypeScript? I imagine that I need some kind of helper file to resolve the commonalities.
Even if I created some kind of foobar
folder that requires foo
and bar
and then exports everything into one big export file it'll probably get messy really soon. What if I need only bar
or only foo
? Is a named export good enough?
I also want to avoid problems in the future, so I am looking for a robust solution. The call precedence is not the main issue that I try to tackle here. It's more about how to set up the dependencies in a smart way.
I'd like to use both foo and bar separately and they should be able to share functions/types/enums/interfaces etc. with each other.
A very simple code snippet can be found here:
Sorry for the misunderstanding about naming. Unfortunately, I had a chance to see similar names in real apps and somehow wrongly assumed that you also want to use this convention. When it comes to "ending up either with huge files that have everything piled up or super-tiny files". This is a matter of finding a good balance. I don't mind a lot of small files (js modules), that are focused on a single functionality - it is a sign that one has correctly distilled smaller responsibilities from some bigger use case. This produces code that is simpler to understand, test and maintain. The big files (js modules) or big classes/functions are often a sign that SRP is broken. Regarding sandbox.io example - I can't wrap my head around it and don't understand the intentions behind hello
and world
functions. They are just simple functions that recursively call each other (causing stack overflow). The simplest refactor would be to just use a shared function like e.g. buildGreeting(msg1, msg2)
placed in foobar
directory. Export const world = 'world'
from foo
directory, and const hello = 'hello'
from bar
directory, then in some other sibling directory create a module with a call like:
import {hello} from '../foo'
import {word} from '../bar'
buildGreeting(hello, word);
However, it is challenging to illustrate any meaningful improvement over this example code, because it does not illustrate any real use case.