/nextjs-bundle-analyzer
Analyze and optimize Next.js bundle size with detailed recommendations
$ npx -y skills add davila7/claude-code-templates --agent claude-codeHow it fires
How this command gets triggered: by you, by Claude, or both.
- Fires itselfClaude auto-loads it when your prompt matches the work.
- You can call itInvoke it directly when you want it.
- Slash command
/nextjs-bundle-analyzer
Context preview
What this command does when you run it.
Analyze and optimize Next.js bundle size with detailed recommendations
Command definition
nextjs-bundle-analyzer.mdallowed-tools: Read, Edit, Bash
argument-hint: [--build] [--analyze] [--report]
description: Analyze and optimize Next.js bundle size with detailed recommendations
Next.js Bundle Analyzer
**Analysis Mode**: $ARGUMENTS
Current Project Analysis
Build Configuration
- Next.js config: @next.config.js
- Package.json: @package.json
- TypeScript config: @tsconfig.json (if exists)
- Build output: !`ls -la .next/ 2>/dev/null || echo "No build found"`
Dependencies Analysis
- Production dependencies: !`npm list --prod --depth=0 2>/dev/null || echo "Run npm install first"`
- Development dependencies: !`npm list --dev --depth=0 2>/dev/null || echo "Run npm install first"`
- Package vulnerabilities: !`npm audit --audit-level=moderate 2>/dev/null || echo "No audit available"`
Bundle Analysis Setup
1. Install Bundle Analyzer
# Install webpack-bundle-analyzer
npm install --save-dev @next/bundle-analyzer
# Or use built-in Next.js analyzer
npm install --save-dev cross-env
2. Configure Next.js Bundle Analyzer
// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
/** @type {import('next').NextConfig} */
const nextConfig = {
// Your existing config
experimental: {
optimizePackageImports: [
'lucide-react',
'@heroicons/react',
'date-fns',
'lodash',
],
},
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Bundle analysis optimizations
if (!dev && !isServer) {
config.optimization.splitChunks = {
chunks: 'all',
cacheGroups: {
default: false,
vendors: false,
// Vendor chunk for common libraries
vendor: {
name: 'vendors',
chunks: 'all',
test: /node_modules/,
priority: 20,
},
// Common chunk for shared code
common: {
name: 'commons',
minChunks: 2,
chunks: 'all',
priority: 10,
reuseExistingChunk: true,
enforce: true,
},
// UI libraries chunk
ui: {
name: 'ui-libs',
chunks: 'all',
test: /node_modules\/(react|react-dom|@radix-ui|@headlessui)/,
priority: 15,
},
// Utility libraries chunk
utils: {
name: 'utils',
chunks: 'all',
test: /node_modules\/(lodash|date-fns|clsx|classnames)/,
priority: 15,
},
},
};
}
return config;
},
};
module.exports = withBundleAnalyzer(nextConfig);3. Package.json Scripts
{
"scripts": {
"analyze": "cross-env ANALYZE=true next build",
"analyze:server": "cross-env BUNDLE_ANALYZE=server next build",
"analyze:browser": "cross-env BUNDLE_ANALYZE=browser next build",
"build:analyze": "npm run build && npm run analyze"
}
}Bundle Analysis Execution
1. Generate Analysis Report
# Full bundle analysis
ANALYZE=true npm run build
# Server-side bundle analysis
BUNDLE_ANALYZE=server npm run build
# Client-side bundle analysis
BUNDLE_ANALYZE=browser npm run build
# Production build with analysis
npm run analyze
2. Bundle Size Check
# Check current bundle size
ls -lah .next/static/chunks/ | head -20
# Check bundle sizes with details
find .next/static/chunks -name "*.js" -exec ls -lah {} \; | sort -k5 -hr
# Gzipped size analysis
find .next/static/chunks -name "*.js" -exec gzip -c {} \; | wc -cBundle Analysis Results
1. Bundle Size Breakdown
Analyze the generated webpack-bundle-analyzer report for:
Client Bundles
- **Main bundle**: Core application code
- **Framework bundle**: Next.js runtime and React
- **Vendor bundles**: Third-party libraries
- **Page bundles**: Individual page chunks
- **Shared bundles**: Common code between pages
Server Bundles
- **API routes**: Server-side API handlers
- **Middleware**: Edge and server middleware
- **Server components**: RSC bundles
2. Size Thresholds and Recommendations
// Bundle size thresholds
const bundleThresholds = {
// First Load JS (critical)
firstLoadJS: {
warning: 200 * 1024, // 200KB
error: 300 * 1024, // 300KB
},
// Individual chunks
chunk: {
warning: 150 * 1024, // 150KB
error: 250 * 1024, // 250KB
},
// Total bundle size
total: {
warning: 1024 * 1024, // 1MB
error: 2048 * 1024, // 2MB
}
};Bundle Optimization Strategies
1. Code Splitting Optimization
// Dynamic imports for large components
import dynamic from 'next/dynamic';
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <p>Loading...</p>,
ssr: false, // Disable SSR for client-only components
});
// Route-based code splitting
const AdminDashboard = dynamic(() => import('./AdminDashboard'), {
loading: () => <DashboardSkeleton />,
});
// Conditional loading
const ChartComponent = dynamic(
() => import('./ChartComponent'),
{
ssr: false,
loading: () => <ChartSkeleton />
}
);2. Library Optimization
// Optimize lodash imports
// ❌ Imports entire lodash library
import _ from 'lodash';
// ✅ Import only needed functions
import { debounce, throttle } from 'lodash';
// ✅ Even better - use tree-shaking friendly alternatives
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';// Date library optimization
// ❌ Moment.js (large bundle)
import moment from 'moment';
// ✅ date-fns (tree-shakable)
import { format, parseISO } from 'date-fns';
// ✅ Day.js (smaller alternative)
import dayjs from 'dayjs';3. Next.js Specific Optimizations
// next.config.js optimizations
const nextConfig = {
// Optimize package imports
experimental: {
optimizePackageImports: [Read more
allowed-tools: Read, Edit, Bash argument-hint: [--build] [--analyze] [--report] description: Analyze and optimize Next.js bundle size with detailed recommendations
Next.js Bundle Analyzer
**Analysis Mode**: $ARGUMENTS
Current Project Analysis
Build Configuration
- Next.js config: @next.config.js
- Package.json: @package.json
- TypeScript config: @tsconfig.json (if exists)
- Build output: !`ls -la .next/ 2>/dev/null || echo "No build found"`
Dependencies Analysis
- Production dependencies: !`npm list --prod --depth=0 2>/dev/null || echo "Run npm install first"`
- Development dependencies: !`npm list --dev --depth=0 2>/dev/null || echo "Run npm install first"`
- Package vulnerabilities: !`npm audit --audit-level=moderate 2>/dev/null || echo "No audit available"`
Bundle Analysis Setup
1. Install Bundle Analyzer
# Install webpack-bundle-analyzer npm install --save-dev @next/bundle-analyzer # Or use built-in Next.js analyzer npm install --save-dev cross-env
2. Configure Next.js Bundle Analyzer
// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
/** @type {import('next').NextConfig} */
const nextConfig = {
// Your existing config
experimental: {
optimizePackageImports: [
'lucide-react',
'@heroicons/react',
'date-fns',
'lodash',
],
},
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Bundle analysis optimizations
if (!dev && !isServer) {
config.optimization.splitChunks = {
chunks: 'all',
cacheGroups: {
default: false,
vendors: false,
// Vendor chunk for common libraries
vendor: {
name: 'vendors',
chunks: 'all',
test: /node_modules/,
priority: 20,
},
// Common chunk for shared code
common: {
name: 'commons',
minChunks: 2,
chunks: 'all',
priority: 10,
reuseExistingChunk: true,
enforce: true,
},
// UI libraries chunk
ui: {
name: 'ui-libs',
chunks: 'all',
test: /node_modules\/(react|react-dom|@radix-ui|@headlessui)/,
priority: 15,
},
// Utility libraries chunk
utils: {
name: 'utils',
chunks: 'all',
test: /node_modules\/(lodash|date-fns|clsx|classnames)/,
priority: 15,
},
},
};
}
return config;
},
};
module.exports = withBundleAnalyzer(nextConfig);3. Package.json Scripts
{
"scripts": {
"analyze": "cross-env ANALYZE=true next build",
"analyze:server": "cross-env BUNDLE_ANALYZE=server next build",
"analyze:browser": "cross-env BUNDLE_ANALYZE=browser next build",
"build:analyze": "npm run build && npm run analyze"
}
}Bundle Analysis Execution
1. Generate Analysis Report
# Full bundle analysis ANALYZE=true npm run build # Server-side bundle analysis BUNDLE_ANALYZE=server npm run build # Client-side bundle analysis BUNDLE_ANALYZE=browser npm run build # Production build with analysis npm run analyze
2. Bundle Size Check
# Check current bundle size
ls -lah .next/static/chunks/ | head -20
# Check bundle sizes with details
find .next/static/chunks -name "*.js" -exec ls -lah {} \; | sort -k5 -hr
# Gzipped size analysis
find .next/static/chunks -name "*.js" -exec gzip -c {} \; | wc -cBundle Analysis Results
1. Bundle Size Breakdown
Analyze the generated webpack-bundle-analyzer report for:
Client Bundles
- **Main bundle**: Core application code
- **Framework bundle**: Next.js runtime and React
- **Vendor bundles**: Third-party libraries
- **Page bundles**: Individual page chunks
- **Shared bundles**: Common code between pages
Server Bundles
- **API routes**: Server-side API handlers
- **Middleware**: Edge and server middleware
- **Server components**: RSC bundles
2. Size Thresholds and Recommendations
// Bundle size thresholds
const bundleThresholds = {
// First Load JS (critical)
firstLoadJS: {
warning: 200 * 1024, // 200KB
error: 300 * 1024, // 300KB
},
// Individual chunks
chunk: {
warning: 150 * 1024, // 150KB
error: 250 * 1024, // 250KB
},
// Total bundle size
total: {
warning: 1024 * 1024, // 1MB
error: 2048 * 1024, // 2MB
}
};Bundle Optimization Strategies
1. Code Splitting Optimization
// Dynamic imports for large components
import dynamic from 'next/dynamic';
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <p>Loading...</p>,
ssr: false, // Disable SSR for client-only components
});
// Route-based code splitting
const AdminDashboard = dynamic(() => import('./AdminDashboard'), {
loading: () => <DashboardSkeleton />,
});
// Conditional loading
const ChartComponent = dynamic(
() => import('./ChartComponent'),
{
ssr: false,
loading: () => <ChartSkeleton />
}
);2. Library Optimization
// Optimize lodash imports
// ❌ Imports entire lodash library
import _ from 'lodash';
// ✅ Import only needed functions
import { debounce, throttle } from 'lodash';
// ✅ Even better - use tree-shaking friendly alternatives
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';// Date library optimization
// ❌ Moment.js (large bundle)
import moment from 'moment';
// ✅ date-fns (tree-shakable)
import { format, parseISO } from 'date-fns';
// ✅ Day.js (smaller alternative)
import dayjs from 'dayjs';3. Next.js Specific Optimizations
// next.config.js optimizations
const nextConfig = {
// Optimize package imports
experimental: {
optimizePackageImports: [Ready-to-use configurations for Anthropic's Claude Code. A comprehensive collection of AI agents, custom commands, settings, hooks, external integrations (MCPs), and project templates to enhance your development workflow.
Repo: davila7/claude-code-templates
Other commands on claude-code-templates.
- /cleanup-cache
Clean system caches (npm, Homebrew, Yarn, browsers, Python/ML) to free disk space
Open command - /create-blog-article
Create an SEO-optimized blog article for a Claude Code component with AI-generated cover image
Open command - /lint
Run Python code linting and formatting tools.
Open command - /test
Run Python tests with pytest, unittest, or other testing frameworks.
Open command - /worktree-check
Check current worktree status, branch, and assigned task
Open command - /worktree-cleanup
Clean up merged worktrees and their branches
Open command

