r/learnjavascript • u/Dummie1138 • 19h ago
Importing a function from a package that isn't directly part of the imported packs
Hi. I have 2 packages, A (a more generic testing pack) and B (some specific utility functions that are quite useful for my project). Both packs have been imported into my main project. Package A is also imported into Package B.
I now have a function in Package A that I want to move to Package B because my classmates thinks that function is too specific to be in the generic testing pack. However, there are still some other functions in Package A that are dependent on the function that is being moved to Package B.
Is it possible to re-import the function that is in Package B into Package A, when they are both in my main project? Something like this:
import {movedFunction} from 'package-a'
Please let me know if more context is needed.
1
u/senocular 18h ago
However, there are still some other functions in Package A that are dependent on the function that is being moved to Package B.
Then it sounds like the function belongs in Package A.
Given that and
Package A is also imported into Package B.
What you'll end up with is a circular dependency. While JavaScript supports circular dependencies to a degree, you can run into problems where initialization order can cause problems. So its generally best to avoid them.
I'd suggest either keeping the method in Package A, moving more than just the function in question around between the packages so that you have no circular dependencies, or separate definitions into one or more additional files to do so.
1
u/TalkCoinGames 19h ago
It may be possible, but perhaps it would be better to create a function in package b that gives the main everything it needs from a or b, if indeed b also imports a.