556
Bn
bees-nest / files
bees-nest / .opencode / skills / vercel-react-best-practices / rules / bundle-barrel-imports.md
2.3 KB
1--- 2title: Avoid Barrel File Imports 3impact: CRITICAL 4impactDescription: 200-800ms import cost, slow builds 5tags: bundle, imports, tree-shaking, barrel-files, performance 6--- 7 8## Avoid Barrel File Imports 9 10Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`). 11 12Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts. 13 14**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph. 15 16**Incorrect (imports entire library):** 17 18```tsx 19import { Check, X, Menu } from 'lucide-react' 20// Loads 1,583 modules, takes ~2.8s extra in dev 21// Runtime cost: 200-800ms on every cold start 22 23import { Button, TextField } from '@mui/material' 24// Loads 2,225 modules, takes ~4.2s extra in dev 25``` 26 27**Correct (imports only what you need):** 28 29```tsx 30import Check from 'lucide-react/dist/esm/icons/check' 31import X from 'lucide-react/dist/esm/icons/x' 32import Menu from 'lucide-react/dist/esm/icons/menu' 33// Loads only 3 modules (~2KB vs ~1MB) 34 35import Button from '@mui/material/Button' 36import TextField from '@mui/material/TextField' 37// Loads only what you use 38``` 39 40**Alternative (Next.js 13.5+):** 41 42```js 43// next.config.js - use optimizePackageImports 44module.exports = { 45 experimental: { 46 optimizePackageImports: ['lucide-react', '@mui/material'] 47 } 48} 49 50// Then you can keep the ergonomic barrel imports: 51import { Check, X, Menu } from 'lucide-react' 52// Automatically transformed to direct imports at build time 53``` 54 55Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR. 56 57Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`. 58 59Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)