Optimize bundle size with code splitting and lazy loading
# Code Splitting Optimization for Google Antigravity
Implement advanced code splitting techniques in your Google Antigravity projects to dramatically improve load times and user experience. This guide covers dynamic imports, route-based splitting, and component-level optimization.
## Dynamic Import Fundamentals
Set up dynamic imports with loading states:
```typescript
// src/components/DynamicLoader.tsx
import dynamic from "next/dynamic";
import { ComponentType, ReactNode } from "react";
interface LoadingProps {
message?: string;
}
function DefaultLoader({ message = "Loading..." }: LoadingProps) {
return (
<div className="flex items-center justify-center p-8">
<div className="flex flex-col items-center gap-4">
<div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" />
<p className="text-gray-400 text-sm">{message}</p>
</div>
</div>
);
}
interface DynamicLoaderOptions {
loading?: ComponentType<LoadingProps>;
ssr?: boolean;
loadingMessage?: string;
}
export function createDynamicComponent<P extends object>(
importFn: () => Promise<{ default: ComponentType<P> }>,
options: DynamicLoaderOptions = {}
) {
const { loading: LoadingComponent = DefaultLoader, ssr = true, loadingMessage } = options;
return dynamic(importFn, {
loading: () => <LoadingComponent message={loadingMessage} />,
ssr,
});
}
// Usage examples
export const DynamicChart = createDynamicComponent(
() => import("@/components/Charts/AreaChart"),
{ loadingMessage: "Loading chart...", ssr: false }
);
export const DynamicEditor = createDynamicComponent(
() => import("@/components/Editor/CodeEditor"),
{ loadingMessage: "Loading editor...", ssr: false }
);
export const DynamicDataTable = createDynamicComponent(
() => import("@/components/DataTable/DataTable"),
{ loadingMessage: "Loading data..." }
);
```
## Route-Based Code Splitting
Implement intelligent route prefetching:
```typescript
// src/lib/routePrefetch.ts
import { useRouter } from "next/navigation";
import { useEffect, useCallback } from "react";
interface PrefetchConfig {
routes: string[];
delay?: number;
priority?: "high" | "low";
}
export function useRoutePrefetch({ routes, delay = 2000, priority = "low" }: PrefetchConfig) {
const router = useRouter();
useEffect(() => {
const timer = setTimeout(() => {
routes.forEach((route) => {
router.prefetch(route);
});
}, delay);
return () => clearTimeout(timer);
}, [routes, delay, router]);
}
export function useLinkPrefetch() {
const router = useRouter();
const handleMouseEnter = useCallback(
(href: string) => {
router.prefetch(href);
},
[router]
);
return { handleMouseEnter };
}
// Smart prefetch based on viewport
export function useIntersectionPrefetch(href: string) {
const router = useRouter();
const prefetchRef = useCallback(
(node: HTMLElement | null) => {
if (!node) return;
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
router.prefetch(href);
observer.disconnect();
}
});
},
{ rootMargin: "200px" }
);
observer.observe(node);
return () => observer.disconnect();
},
[href, router]
);
return prefetchRef;
}
```
## Component-Level Splitting
Split heavy components intelligently:
```typescript
// src/components/Dashboard/Dashboard.tsx
"use client";
import { Suspense, lazy, useState } from "react";
// Lazy load dashboard widgets
const AnalyticsWidget = lazy(() => import("./widgets/AnalyticsWidget"));
const RevenueChart = lazy(() => import("./widgets/RevenueChart"));
const UserActivity = lazy(() => import("./widgets/UserActivity"));
const NotificationPanel = lazy(() => import("./widgets/NotificationPanel"));
function WidgetSkeleton() {
return (
<div className="bg-gray-800 rounded-xl p-6 animate-pulse">
<div className="h-4 bg-gray-700 rounded w-1/3 mb-4" />
<div className="h-32 bg-gray-700 rounded" />
</div>
);
}
export function Dashboard() {
const [activeTab, setActiveTab] = useState<"overview" | "analytics" | "users">("overview");
return (
<div className="space-y-6">
<nav className="flex gap-4 border-b border-gray-800 pb-4">
{(["overview", "analytics", "users"] as const).map((tab) => (
<button
key={tab}
onClick={() => setActiveTab(tab)}
className={`px-4 py-2 rounded-lg transition-colors ${
activeTab === tab
? "bg-indigo-500 text-white"
: "text-gray-400 hover:text-white"
}`}
>
{tab.charAt(0).toUpperCase() + tab.slice(1)}
</button>
))}
</nav>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{activeTab === "overview" && (
<>
<Suspense fallback={<WidgetSkeleton />}>
<AnalyticsWidget />
</Suspense>
<Suspense fallback={<WidgetSkeleton />}>
<RevenueChart />
</Suspense>
<Suspense fallback={<WidgetSkeleton />}>
<NotificationPanel />
</Suspense>
</>
)}
{activeTab === "analytics" && (
<div className="col-span-full">
<Suspense fallback={<WidgetSkeleton />}>
<RevenueChart fullWidth />
</Suspense>
</div>
)}
{activeTab === "users" && (
<div className="col-span-full">
<Suspense fallback={<WidgetSkeleton />}>
<UserActivity />
</Suspense>
</div>
)}
</div>
</div>
);
}
```
## Bundle Analysis and Optimization
Analyze and optimize bundle sizes:
```typescript
// next.config.js
const withBundleAnalyzer = require("@next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
module.exports = withBundleAnalyzer({
experimental: {
optimizePackageImports: [
"lodash",
"date-fns",
"@heroicons/react",
"lucide-react",
],
},
webpack: (config, { isServer }) => {
if (!isServer) {
config.optimization.splitChunks = {
chunks: "all",
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
chunks: "all",
},
common: {
minChunks: 2,
priority: -10,
reuseExistingChunk: true,
},
},
};
}
return config;
},
});
```
Google Antigravity automatically generates optimized code splitting patterns that reduce initial bundle size and improve Time to Interactive for your applications.This Performance prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their performance implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Performance projects, consider mentioning your framework version, coding style, and any specific libraries you're using.