Article

Barrel imports and tree shaking: shrinking a webpack vendor bundle

Find the barrel imports that bloat a webpack vendor bundle, fix them with direct imports and sideEffects, and keep them out with ESLint and a size budget.

Published Updated 7 min read

This guide shows how barrel imports can stop tree shaking and bloat a webpack vendor bundle, and how you find them, fix them and keep them out with lint rules and a size budget in CI. It is written for frontend engineers and tech leads who own a webpack build or a shared component library. The examples use webpack 5.113.0, webpack-bundle-analyzer 5.4.3, source-map-explorer 2.5.3, @fortawesome/fontawesome-svg-core and @fortawesome/free-solid-svg-icons 7.3.1, @fortawesome/react-fontawesome 3.5.0, no-barrel-file 1.0.1, eslint 10.16.0, eslint-plugin-barrel-files 3.0.1, size-limit and @size-limit/file 14.3.0 and next 16.4.6. These are the current npm versions on 1 December 2026.

What a barrel file is

A barrel file is an index file that re-exports other modules:

// src/components/index.js
export * from './Button'
export * from './ProductCard'
export * from './IconButton'

Other code then imports from the folder:

import { Button } from '@/components'

This looks tidy, but the bundler now has to load the barrel and follow every re-export to find Button. If it cannot prove that the other modules are unused and free of side effects, it keeps them, so one import of Button can pull in ProductCard, IconButton and everything they import. The webpack docs call this “the classic barrel file cost”.

Why tree shaking does not remove the extra code

webpack removes unused code in two steps:

  • optimization.usedExports marks exports that nothing uses, and the minifier (Terser) then drops them.
  • optimization.sideEffects skips whole modules when none of their exports are used, but only when the package declares that its modules have no side effects. The webpack guide calls this step more effective because it skips whole modules and subtrees.

Both options are on by default in production mode. Tree shaking also needs ES module syntax, so if Babel turns your import statements into CommonJS require calls, webpack cannot tree shake them.

Barrels break this in three common ways:

  • The barrel or the modules behind it have no sideEffects declaration, so webpack keeps every module behind the barrel and only the minifier can still remove unused code inside them.
  • The code imports a whole set at once, such as a full icon style.
  • A namespace import such as import * as Icons from '...' or a dynamic lookup like Icons[name] makes it hard for the bundler to see which exports you use.

FontAwesome’s React docs warn that importing a whole icon style “won’t work with tree-shaking and can add bloat”:

import { library } from '@fortawesome/fontawesome-svg-core'
import { fas } from '@fortawesome/free-solid-svg-icons'

library.add(fas) // every solid icon ends up in the bundle

Find the barrels

webpack-bundle-analyzer

The analyzer draws a treemap of each bundle once you add it to the production build:

// webpack.config.js
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')

module.exports = {
  mode: 'production',
  devtool: 'source-map',
  plugins: [
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      reportFilename: 'bundle-report.html',
      openAnalyzer: false,
      defaultSizes: 'gzip',
    }),
  ],
}

You can also analyse a stats file without changing the config:

npx webpack --profile --json > stats.json
npx webpack-bundle-analyzer stats.json dist

Look for large blocks of a library in the vendor bundle while the app uses only a few of its exports.

source-map-explorer

source-map-explorer reads the source map of the final file and shows which source files take up the bytes:

npx source-map-explorer dist/vendor.js --html vendor-report.html

The build needs source maps for this, which the devtool: 'source-map' line above creates.

webpack’s own checks

Since webpack 5.110, the performance option has opt-in checks for the shape of the bundle, and two of them target this problem:

// webpack.config.js
module.exports = {
  mode: 'production',
  performance: {
    hints: 'warning',
    unusedModules: true, // webpack 5.111 or later
    missingSideEffects: true,
  },
}
  • unusedModules reports modules in the bundle that nothing uses, and names what kept each one. A re-export from a barrel is one of the causes it names.
  • missingSideEffects reports packages that keep unused code because their package.json has no sideEffects field, and shows how many bytes that costs.

Most checks report through performance.hints, so they stay silent when hints is false.

For a Next.js app, npx next analyze analyses Turbopack builds from Next.js 16.1, and for webpack builds in Next.js you can use @next/bundle-analyzer.

Fix the imports

Import single icons

Import the icons you use by name, because FontAwesome’s icon packages support tree shaking when the bundler does:

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCartShopping, faMagnifyingGlass } from '@fortawesome/free-solid-svg-icons'

export function HeaderIcons() {
  return (
    <>
      <FontAwesomeIcon icon={faMagnifyingGlass} />
      <FontAwesomeIcon icon={faCartShopping} />
    </>
  )
}

The @fortawesome/free-solid-svg-icons package declares "sideEffects": false and ships an ES module build, so webpack can drop the icons that you do not import.

If your build cannot tree shake, FontAwesome documents deep imports as a fallback:

import { faCartShopping } from '@fortawesome/free-solid-svg-icons/faCartShopping'

Each deep import is a small CommonJS file with one icon, so it does not need tree shaking at all.

Replace your own barrels

For your own code, import from the file, not from the folder:

// Before
import { Button } from '@/components'

// After
import { Button } from '@/components/Button'

On a large codebase, a tool such as no-barrel-file can do this for you, because it lists barrel files and can rewrite imports to the direct path:

npx no-barrel-file display --root-path ./src
npx no-barrel-file replace --root-path ./src --alias-config-path tsconfig.json

The replace mode needs the tsconfig.json with your path aliases. It can leave duplicate imports and trip over files with extra suffixes, such as .types.ts, so review the diff before you commit.

Declare side effects in your packages

If you publish a component library or a workspace package, declare its side effects in package.json:

{
  "name": "@shop/ui",
  "sideEffects": ["*.css"]
}

false means that no file has side effects, while a list names the files that do. Imported CSS files count as side effects, so list them, or webpack can drop the CSS.

Check the build settings

Use mode: 'production' for the build that you measure, because the tree shaking options are on by default there:

// webpack.config.js
module.exports = {
  mode: 'production',
  optimization: {
    usedExports: true, // default in production
    sideEffects: true, // default in production
  },
}

Set them only if an older config turned them off. Check your Babel config too, because @babel/preset-env with modules: 'commonjs' turns ES modules into CommonJS. Keep the default modules: 'auto', so that Babel leaves the ES modules for webpack when you use babel-loader.

Next.js apps

Next.js has experimental.optimizePackageImports, which loads only the modules you use from packages with many named exports:

// next.config.js
module.exports = {
  experimental: {
    optimizePackageImports: ['@shop/ui'],
  },
}

The option is experimental. Next.js already optimises some libraries by default, such as lucide-react, date-fns and lodash-es, but FontAwesome is not on that list. Measure the bundle before and after, because the effect depends on how the package is built.

Keep barrels out

Lint rules

no-restricted-imports is a core ESLint rule that can block whole-style icon imports and imports from your own barrel:

// eslint.config.js
import barrelFiles from 'eslint-plugin-barrel-files'

export default [
  barrelFiles.configs.recommended,
  {
    rules: {
      'no-restricted-imports': ['error', {
        paths: [{
          name: '@/components',
          message: 'Import from the component file, for example @/components/Button.',
        }],
        patterns: [{
          group: ['@fortawesome/*-svg-icons'],
          importNames: ['fas', 'far', 'fab'],
          message: 'Import single icons, for example faCartShopping.',
        }],
      }],
    },
  },
]

eslint-plugin-barrel-files adds four rules, and its recommended config sets all four to error:

  • barrel-files/avoid-barrel-files flags barrel files.
  • barrel-files/avoid-importing-barrel-files flags imports from barrel files.
  • barrel-files/avoid-namespace-import flags import * as.
  • barrel-files/avoid-re-export-all flags export *.

On an existing codebase, start with the rules as warnings and fix the largest barrels first.

A size budget in CI

A budget fails the build when the bundle grows, and size-limit does this by checking file sizes after the build:

npm install --save-dev size-limit @size-limit/file
{
  "scripts": {
    "size": "npm run build && size-limit"
  },
  "size-limit": [
    { "path": "dist/vendor.js", "limit": "500 kB" }
  ]
}

Run npm run size in CI, where size-limit measures the Brotli size by default. Start with a limit a little above the current size, and lower it after each fix.

webpack can also fail the build if you set performance.hints to 'error' and set maxAssetSize and maxEntrypointSize in bytes. The default for both is 250,000 bytes.

In practice

An international cosmetics retailer moved from Salesforce Commerce Cloud to a headless Next.js platform, market by market. The whole frontend of the legacy storefront shipped as one JavaScript bundle, and the FontAwesome packages took up a large part of the legacy vendor bundle.

The first idea was a separate webpack chunk for the icon packages, with a splitChunks cache group, but that only moved the code and the size stayed the same. Swapping single icon imports did not help either, because the cause was barrel imports that pulled in the icon library.

We fixed the barrel imports of the icon library on the legacy site and enabled tree shaking, which made the legacy JavaScript vendor bundle 62% smaller, from 4.56 MB to 1.75 MB. The PageSpeed score of the legacy site went from 39 to 50, and both results are from February 2026.

On the new Next.js storefront, each approach was measured per component. Direct imports made one component smaller, while optimizePackageImports, deep imports and dynamic import() changed little there, so measure each change on its own. You can read more in the case study.

Checklist

  • Build in production mode before you measure.
  • Make a treemap of the vendor bundle.
  • Turn on performance.unusedModules and performance.missingSideEffects.
  • Import single icons, never a whole icon style.
  • Use deep imports if your build cannot tree shake.
  • Import from the file, not from a barrel folder.
  • Declare sideEffects in your own packages, with CSS files listed.
  • Keep Babel from turning ES modules into CommonJS.
  • Block barrel imports with ESLint.
  • Add a size budget to CI.
  • Measure each change on its own.

For a review of your bundles and page weight, see the web performance audit. For a review of your shared packages, see the design system and monorepo audit or contact us.

Sources

Let's connect

Talk about your project

Tell us about your team and your problem. In 30 minutes we find out whether one of our offers fits, and if none does, we tell you.

Book a 30-minute call