billing hacks

Shrinking Your Bundle

Find what's bloating your JavaScript and fix it in 30 minutes.

TL;DR

Run ANALYZE=true npm run build to find bloat. Replace moment with date-fns, use direct lodash imports, fix barrel file imports. Use modularizeImports for automatic tree-shaking.

A bloated bundle costs you twice: slow page loads AND higher bandwidth bills.

Setup (2 minutes)

npm install @next/bundle-analyzer
next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

module.exports = withBundleAnalyzer({
  // your existing config
});
ANALYZE=true npm run build

Opens an interactive treemap. Bigger rectangles = bigger problems.

The Usual Suspects

LibrarySizeReplace With
moment300KBdate-fns (20KB)
lodash (full)70KBDirect imports
Icon libraries100KB+Direct imports or @iconify/react
@aws-sdk/*500KB+Should be server-only
chart.js200KBLazy load it

Quick Fixes

Moment → date-fns

// Before
import moment from 'moment';
moment(date).format('YYYY-MM-DD');

// After
import { format } from 'date-fns';
format(date, 'yyyy-MM-dd');

Lodash Direct Imports

// Before: pulls in everything
import _ from 'lodash';
_.debounce(fn, 300);

// After: just what you need
import debounce from 'lodash/debounce';
debounce(fn, 300);

Icon Library Fixes

// Before: may import all icons
import { FaHome } from 'react-icons/fa';

// After: specific import path
import { FaHome } from 'react-icons/fa6';

Auto-Fix with modularizeImports

Force proper tree-shaking for problem packages:

next.config.js
module.exports = {
  modularizeImports: {
    'lodash': {
      transform: 'lodash/{{member}}',
    },
    '@mui/icons-material': {
      transform: '@mui/icons-material/{{member}}',
    },
    '@heroicons/react/24/outline': {
      transform: '@heroicons/react/24/outline/{{member}}',
    },
  },
};

Now import { debounce } from 'lodash' automatically becomes import debounce from 'lodash/debounce'.

The Barrel File Problem

components/index.ts
export * from './Button';
export * from './Modal';
export * from './Chart'; // 200KB!
// Importing one thing evaluates everything
import { Button } from '@/components'; // Pulls in Chart too

Fix: Import from source files directly:

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

Key Takeaways

Check package sizes No single package should exceed 100KB without justification.

Verify server-only code stays server-side AWS SDK, database drivers, etc. should never appear in client bundles.

Eliminate duplicates Watch for the same package appearing multiple times with different versions.

Verify tree-shaking Icon libraries and lodash should only include what you actually use.


Next: Dynamic Imports - load heavy code only when needed.

On this page