DEV Community

Discussion on: Organize React Components Better with Barrel Exports

Collapse
 
justmyrealname profile image
Joe Ziemba

Thanks Peter, good to know for people using Next.js! I haven't run into that problem using standard CRA luckily.

Bit of a tangent, but I it's worth noting why no tree shaking is hurting them there:

There's about 100 components defined, and only a couple are used

Unused components - especially that many - really should be deleted. Having build tools help with our bundle size is great, but shouldn't replace our own clean code practices. We don't want our codebases to start looking like an episode of Hoarders! 😄

Collapse
 
ashoutinthevoid profile image
Full Name

The full quote is important here

There's about 100 components defined, and only a couple are used in _app.tsx.

Only a few used in that specific file, _app.tsx. That's not the same thing as having only a few used in the entire application. That file initializes every single page; if every component was used in every single page, there would be nothing to shake.
The absence of tree shaking is not a hoarding problem, it's a legitimate bug in this next.js case.

Thread Thread
 
maciekgrzybek profile image
Maciek Grzybek • Edited

First of all, great stuff with the article :) I've been using this pattern for a while now, but never knew that it's called like that :)
Is the tree shaking problem only related to next js?

Thread Thread
 
pcjmfranken profile image
Peter Franken

Not limited to Next. Whether your codebase is affected depends on its complexity and your bundler configuration. Running some tests is the only way to to be sure.

Figuring out what code can be safely dropped ("tree-shaken") is quite complex. Your bundler (e.g. webpack) has to look at each piece of code and figure out if it's used anywhere else in any way (deep-scope analysis).

The more ambiguous your code or deeper your import trees, the more time it would take to get this right (exponential complexity AKA best leave it for the CompSci's 😉). We want fast builds though, so at some point the bundler is just going to tap out and leave the code that it isn't sure about in.

Here's an amazing and really in-depth article for those wanting to learn more: dev.to/livechat/tree-shaking-for-j...