Barrels and Barrel Imports in Typescript
Prompted by seeing the term "barrel imports" in the MUI docs where they suggest avoiding them because they slow down rebuilds during development. (Tree shaking means they have no impact on prod builds.)
Based on a google search for "barrel imports", they are considered an anti-pattern, so it's not solely a MUI problem.
A barrel is a Typescript package that just imports a bunch of other packages and re-exports them, usually in order to provide a nicer interface.
Based on MUI, and some cursory googling, the usual pattern is to have an index.{js,ts} file that re-exports from the subpackages, as this example from the docs illustrate.
// 🐌 Slower in dev
import { Delete } from '@mui/icons-material';
// 🚀 Faster in dev
import Delete from '@mui/icons-material/Delete';
Note that named imports in general are not the problem. It's when the file you are importing from is a barrel that causes the issue due to the indirection involved and how packages are loaded.
References
- Minimizing bundle size - Material UI - this page is linked from basically every component page in the docs
- Please Stop Using Barrel Files | TkDodo's blog
- this was the first result on Google for "barrel imports"
- despite the name, at the very end the article suggests that they can make sense when publishing a library, but to avoid them for app code.