-
-
Notifications
You must be signed in to change notification settings - Fork 26.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conditionally Import Components? #2375
Comments
What problem are you trying to solve? Even though “in any one render of DetailsField, only one of the 6 imports will ever be needed”, this doesn’t affect how bundles are created. Imports need to be resolved statically, so declaring them at the top is necessary. |
To be more specific, I think there might be a misconception of how imports work, and I want to ensure we’re on the same page. Even if there was some way to import just one “dynamically“ it would not really make sense from the bundling perspective. If code is bundled statically, all files get packaged anyway. You could use a dynamic So it’s not a limitation of the tool, or something you’d eject for—it’s fundamentally how modules work with JS bundlers. Hope this helps! Let me know if it’s still not very clear. |
Yeah, I’m really unclear on some of the “magic” under the hood of bundling. I get that, if everything is statically bundled, then DetailsField “includes” its defined dependencies, whether or not they are used at runtime. I guess I’m thinking that if I render DetailsField 1000 times, then I’ll have 5 * 1000 = 5000 unnecessary modules imported that are taking up space in memory.
Apart from my linter complaining, could I do this then? (I'll give it a try)
|
This is not a correct assumption. Imports are evaluated only once, and later cached. Moreover, rendering a component does not re-execute any code in top level scope. So it does not even get to the imports (which, again, are cached anyway). |
No, you'd just create unused Promises. The I'm happy to discuss this more, but as a separate StackOverflow question. It's neither directly related to CRA, nor related to the problem you're solving (which as I've explained earlier is not really a problem, since you have incorrect assumptions). |
Lightbulb moment! So, there's no advantage jumping through conditional import hoops. I actually thought React (and similar modules) were special cases. Didn't realize the same applied to my custom components. Thanks! |
Yea, exactly! |
Is there a way to conditionally (and dynamically) import the modules needed without ejecting my create-react-app project?
For example, in the code below, in any one render of DetailsField, only one of the 6 imports will ever be needed.
The text was updated successfully, but these errors were encountered: