Skip to main content
command CX Codex

optimize-bundle-size — Claude Code command: what it does

optimize-bundle-size reads your bundle, finds the dependencies that bloat it and rewrites the build config: chunk splitting, lazy routes, tree shaking. Useful when the JS payload slows the page down.

MIT ★ 3,785 updated 2026-10-25

Install into Claude Code · Plugin marketplace All methods and platforms ↓
/plugin marketplace add davepoon/buildwithclaude
/plugin install all-commands@buildwithclaude
Open on GitHub

What optimize-bundle-size does

The command walks a build in order. It starts with a size and composition check of the current bundle, flags fat dependencies and dead code, then edits the bundler config. On webpack that means splitChunks with separate vendor and common groups, plus usedExports and sideEffects; on Vite, manualChunks and rollup-plugin-visualizer writing a report to dist/stats.html.

From there it adds route-level lazy/Suspense loading, swaps whole-library imports for single functions, and drops in a script that walks the dependency list and prints anything above 100 KB. Image compression through image-webpack-loader and module federation for bigger apps are part of the steps too.

Shell access is scoped to Bash(npm *), so the install and build calls it runs are npm ones. On a pnpm or yarn project that permission buys you nothing, and you'll run installs and builds yourself.

What it helps with

  • find dependencies that bloat the bundle
  • split vendor and common chunks in webpack
  • lazy-load routes in a React app
  • cut dead code with tree shaking
  • track file sizes in dist after a build

Example prompts for the agent

  • /optimize-bundle-size analyze the production build and list the heaviest dependencies
  • /optimize-bundle-size set up route-level lazy loading for the pages in src/pages
  • /optimize-bundle-size why does the whole of lodash end up in the vendor chunk

How to install optimize-bundle-size

1Plugin marketplace

/plugin marketplace add davepoon/buildwithclaude
/plugin install all-commands@buildwithclaude

2Manually: put the files in place

.claude/commands/optimize-bundle-size.md

Call it with /optimize-bundle-size. For all projects use ~/.claude/commands/

Questions about optimize-bundle-size

How do I install optimize-bundle-size in Claude Code?

Run /plugin marketplace add davepoon/buildwithclaude, then /plugin install all-commands@buildwithclaude. The command file lands at .claude/commands/optimize-bundle-size.md.

What does optimize-bundle-size do?

It inspects the current build, points at the dependencies that weigh the most, and rewrites the webpack or Vite config for smaller chunks and less dead code.

Does it cover Vite as well as webpack?

Both are in the steps: webpack gets splitChunks and usedExports, Vite gets manualChunks and a visualizer report in dist/stats.html.

Source text

optimize-bundle-size.md · MIT
---
description: Reduce and optimize bundle sizes
category: performance-optimization
allowed-tools: Bash(npm *)
---

# Optimize Bundle Size

Reduce and optimize bundle sizes

## Instructions

1. **Bundle Analysis and Assessment**
   - Analyze current bundle size and composition using webpack-bundle-analyzer or similar
   - Identify large dependencies and unused code
   - Assess current build configuration and optimization settings
   - Create baseline measurements for optimization tracking
   - Document current performance metrics and loading times

2. **Build Tool Configuration**
   - Configure build tool optimization settings:

   **Webpack Configuration:**
   ```javascript
   // webpack.config.js
   const path = require('path');
   const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

   module.exports = {
     mode: 'production',
     optimization: {
       splitChunks: {
         chunks: 'all',
         cacheGroups: {
           vendor: {
             test: /[\\/]node_modules[\\/]/,
             name: 'vendors',
             priority: 10,
             reuseExistingChunk: true,
           },
           common: {
             name: 'common',
             minChunks: 2,
             priority: 5,
             reuseExistingChunk: true,
           },
         },
       },
       usedExports: true,
       sideEffects: false,
     },
     plugins: [
       new BundleAnalyzerPlugin({
         analyzerMode: 'static',
         openAnalyzer: false,
       }),
     ],
   };
   ```

   **Vite Configuration:**
   ```javascript
   // vite.config.js
   import { defineConfig } from 'vite';
   import { visualizer } from 'rollup-plugin-visualizer';

   export default defineConfig({
     build: {
       rollupOptions: {
         output: {
           manualChunks: {
             vendor: ['react', 'react-dom'],
             ui: ['@mui/material', '@emotion/react'],
           },
         },
       },
     },
     plugins: [
       visualizer({
         filename: 'dist/stats.html',
         open: true,
         gzipSize: true,
       }),
     ],
   });
   ```

3. **Code Splitting and Lazy Loading**
   - Implement route-based code splitting:

   **React Route Splitting:**
   ```javascript
   import { lazy, Suspense } from 'react';
   import { Routes, Route } from 'react-router-dom';

   const Home = lazy(() => import('./pages/Home'));
   const Dashboard = lazy(() => import('./pages/Dashboard'));
   const Profile = lazy(() => import('./pages/Profile'));

   function App() {
     return (
       <Suspense fallback={<div>Loading...</div>}>
         <Routes>
           <Route path="/" element={<Home />} />
           <Route path="/dashboard" element={<Dashboard />} />
           <Route path="/profile" element={<Profile />} />
         </Routes>
       </Suspense>
     );
   }
   ```

   **Dynamic Imports:**
   ```javascript
   // Lazy load heavy components
   const HeavyComponent = lazy(() => 
     import('./HeavyComponent').then(module => ({
       default: module.HeavyComponent
     }))
   );

   // Conditional loading
   async function loadAnalytics() {
     if (process.env.NODE_ENV === 'production') {
       const { analytics } = await import('./analytics');
       return analytics;
     }
   }
   ```

4. **Tree Shaking and Dead Code Elimination**
   - Configure tree shaking for optimal dead code elimination:

   **Package.json Configuration:**
   ```json
   {
     "sideEffects": false,
     "exports": {
       ".": {
         "import": "./dist/index.esm.js",
         "require": "./dist/index.cjs.js"
       }
     }
   }
   ```

   **Import Optimization:**
   ```javascript
   // Instead of importing entire library
   // import * as _ from 'lodash';

   // Import only what you need
   import debounce from 'lodash/debounce';
   import throttle from 'lodash/throttle';

   // Use babel-plugin-import for automatic optimization
   // .babelrc
   {
     "plugins": [
       ["import", {
         "libraryName": "lodash",
         "libraryDirectory": "",
         "camel2DashComponentName": false
       }, "lodash"]
     ]
   }
   ```

5. **Dependency Optimization**
   - Analyze and optimize dependencies:

   **Package Analysis Script:**
   ```javascript
   // scripts/analyze-deps.js
   const fs = require('fs');
   const path = require('path');

   function analyzeDependencies() {
     const packageJson = JSON.parse(
       fs.readFileSync('package.json', 'utf8')
     );
     
     const deps = {
       ...packageJson.dependencies,
       ...packageJson.devDependencies
     };

     console.log('Large dependencies to review:');
     Object.keys(deps).forEach(dep => {
       try {
         const depPath = require.resolve(dep);
         const stats = fs.statSync(depPath);
         if (stats.size > 100000) { // > 100KB
           console.log(`${dep}: ${(stats.size / 1024).toFixed(2)}KB`);
         }
       } catch (e) {
         // Skip if can't resolve
       }
     });
   }

   analyzeDependencies();
   ```

6. **Asset Optimization**
   - Optimize static assets and media files:

   **Image Optimization:**
   ```javascript
   // webpack.config.js
   module.exports = {
     module: {
       rules: [
         {
           test: /\.(png|jpe?g|gif|svg)$/i,
           use: [
             {
               loader: 'file-loader',
               options: {
                 outputPath: 'images',
               },
             },
             {
               loader: 'image-webpack-loader',
               options: {
                 mozjpeg: { progressive: true, quality: 80 },
                 optipng: { enabled: false },
                 pngquant: { quality: [0.6, 0.8] },
                 gifsicle: { interlaced: false },
               },
             },
           ],
         },
       ],
     },
   };
   ```

7. **Module Federation and Micro-frontends**
   - Implement module federation for large applications:

   **Module Federation Setup:**
   ```javascript
   // webpack.config.js
   const ModuleFederationPlugin = require('@module-federation/webpack');

   module.exports = {
     plugins: [
       new ModuleFederationPlugin({
         name: 'host',
         remotes: {
           mfe1: 'mfe1@http://localhost:3001/remoteEntry.js',
           mfe2: 'mfe2@http://localhost:3002/remoteEntry.js',
         },
         shared: {
           react: { singleton: true },
           'react-dom': { singleton: true },
         },
       }),
     ],
   };
   ```

8. **Performance Monitoring and Measurement**
   - Set up bundle size monitoring:

   **Bundle Size Monitoring:**
   ```javascript
   // scripts/bundle-monitor.js
   const fs = require('fs');
   const path = require('path');
   const gzipSize = require('gzip-size');

   async function measureBundleSize() {
     const distPath = path.join(__dirname, '../dist');
     const files = fs.readdirSync(distPath);
     
     for (const file of files) {
       if (file.endsWith('.js')) {
         const filePath = path.join(distPath, file);
         const content = fs.readFileSync(filePath);
         const originalSize = content.length;
         const compressed = await gzipSize(content);
         
         console.log(`${file}:`);
         console.log(`  Original: ${(originalSize / 1024).toFixed(2)}KB`);
         console.log(`  Gzipped: ${(compressed / 1024).toFixed(2)}KB`);
       }
     }
   }

   measureBundleSize();
   ```

9. **Progressive Loading Strategies**
   - Implement progressive loading and resource hints:

   **Resource Hints:**
   ```html
   <!-- Preload critical resources -->
   <link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin>
   <link rel="preload" href="/critical.css" as="style">

   <!-- Prefetch non-critical resources -->
   <link rel="prefetch" href="/dashboard.js">
   <link rel="prefetch" href="/profile.js">

   <!-- DNS prefetch for external domains -->
   <link rel="dns-prefetch" href="//api.example.com">
   ```

   **Intersection Observer for Lazy Loading:**
   ```javascript
   // utils/lazyLoad.js
   export function lazyLoadComponent(importFunc) {
     return lazy(() => {
       return new Promise(resolve => {
         const observer = new IntersectionObserver((entries) => {
           entries.forEach(entry => {
             if (entry.isIntersecting) {
               importFunc().then(resolve);
               observer.disconnect();
             }
           });
         });
         
         // Observe a trigger element
         const trigger = document.getElementById('lazy-trigger');
         if (trigger) observer.observe(trigger);
       });
     });
   }
   ```

10. **Validation and Continuous Monitoring**
    - Set up automated bundle size validation:

    **CI/CD Bundle Size Check:**
    ```yaml
    # .github/workflows/bundle-size.yml
    name: Bundle Size Check
    on: [pull_request]

    jobs:
      bundle-size:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v2
          - name: Setup Node
            uses: actions/setup-node@v2
            with:
              node-version: '16'
          - name: Install dependencies
            run: npm ci
          - name: Build bundle
            run: npm run build
          - name: Check bundle size
            run: |
              npm run bundle:analyze
              node scripts/bundle-size-check.js
    ```

    **Bundle Size Threshold Check:**
    ```javascript
    // scripts/bundle-size-check.js
    const fs = require('fs');
    const path = require('path');

    const THRESHOLDS = {
      'main.js': 250 * 1024, // 250KB
      'vendor.js': 500 * 1024, // 500KB
    };

    function checkBundleSize() {
      const distPath = path.join(__dirname, '../dist');
      const files = fs.readdirSync(distPath);
      let failed = false;

      files.forEach(file => {
        if (file.endsWith('.js') && THRESHOLDS[file]) {
          const filePath = path.join(distPath, file);
          const size = fs.statSync(filePath).size;
          
          if (size > THRESHOLDS[file]) {
            console.error(`❌ ${file} exceeds threshold: ${size} > ${THRESHOLDS[file]}`);
            failed = true;
          } else {
            console.log(`✅ ${file} within threshold: ${size}`);
          }
        }
      });

      if (failed) {
        process.exit(1);
      }
    }

    checkBundleSize();
    ```

© BuildWithClaude Community · MIT · davepoon/buildwithclaude

Similar slash commands

All slash commands for Frontend and UI →

From the same set235

The whole set →
tidy This Claude Code skill groups uncategorized transactions and suggests categories. It starts when asked to tidy transactions or sort uncategorized activity. CX Codex +1 104installs google-drive-upload google-drive-upload is a Claude Code skill that sends files to Google Drive through a deployed Google Apps Script web app. It reacts to requests to store or upload a file. CX Codex +1 101installs szamlazz-invoicing The szamlazz-invoicing Claude Code skill handles Hungarian invoices through the szamlazz.hu Agent API. It activates for requests to issue, cancel, or download an invoice, or create a proforma. CX Codex +1 100installs optimize-database-performance optimize-database-performance — a slash command that works through slow queries, index strategy and schema layout for PostgreSQL and MySQL, then hands back SQL you can apply. Useful once page loads start dragging. CX Codex +1 ★ 3,785repo stars implement-caching-strategy implement-caching-strategy is a Claude Code command that plans and adds caching across browser, application, and database layers. Run it to define TTL and invalidation rules for a project. CX Codex +1 ★ 3,785repo stars add-performance-monitoring add-performance-monitoring generates performance monitoring configs for Node.js backends and browser apps using New Relic, Datadog or Web Vitals. CX Codex +1 ★ 3,785repo stars rollback-deploy rollback-deploy turns a release rollback into a numbered runbook: decide whether to revert, check the live version, undo the deploy, restore traffic, tell users. CX Codex +1 ★ 3,785repo stars setup-cdn-optimization setup-cdn-optimization is a Claude Code command for configuring CDN delivery, caching, and static assets. It runs on requests to tune an application's CDN setup. CX Codex +1 ★ 3,785repo stars

More in the catalog

Project sponsors

Companies that keep this analytics open