Optimizing Code Splitting and Lazy Loading with Claude Code
Learn about optimizing code splitting and lazy loading using Claude Code. Practical tips and code examples included.
コード分割の必要性
SPAのバンドルサイズが大きくなると初期読み込みが遅くなります。コード分割と遅延読み込みを適切に実装すれば、必要なコードだけを必要なタイミングで読み込めます。Claude Codeを活用すれば、既存プロジェクトへの導入も効率的です。
React.lazy と Suspense
import { lazy, Suspense } from "react";
// 遅延読み込みコンポーネント
const Dashboard = lazy(() => import("./pages/Dashboard"));
const Settings = lazy(() => import("./pages/Settings"));
const Analytics = lazy(() => import("./pages/Analytics"));
function LoadingSpinner() {
return (
<div className="flex items-center justify-center h-64">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500" />
</div>
);
}
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
<Route path="/analytics" element={<Analytics />} />
</Routes>
</Suspense>
);
}
Named Export の遅延読み込み
// Named exportを遅延読み込みする場合
const Chart = lazy(() =>
import("./components/Chart").then((module) => ({
default: module.BarChart,
}))
);
// 汎用ヘルパー
function lazyNamed<T extends Record<string, any>>(
factory: () => Promise<T>,
name: keyof T
) {
return lazy(() =>
factory().then((module) => ({ default: module[name] }))
);
}
const PieChart = lazyNamed(
() => import("./components/Chart"),
"PieChart"
);
Next.js の dynamic import
import dynamic from "next/dynamic";
// クライアントサイドのみで読み込み
const RichEditor = dynamic(() => import("./components/RichEditor"), {
ssr: false,
loading: () => <p>エディタを読み込み中...</p>,
});
// 条件付き読み込み
const AdminPanel = dynamic(() => import("./components/AdminPanel"), {
ssr: false,
});
function Page({ isAdmin }: { isAdmin: boolean }) {
return (
<div>
<h1>メインコンテンツ</h1>
{isAdmin && <AdminPanel />}
</div>
);
}
ルートベースの分割
import { lazy, Suspense } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
// ルートごとに分割
const routes = [
{ path: "/", component: lazy(() => import("./pages/Home")) },
{ path: "/about", component: lazy(() => import("./pages/About")) },
{ path: "/blog/*", component: lazy(() => import("./pages/Blog")) },
{
path: "/admin/*",
component: lazy(() => import("./pages/Admin")),
},
];
function AppRouter() {
return (
<BrowserRouter>
<Suspense fallback={<LoadingSpinner />}>
<Routes>
{routes.map(({ path, component: Component }) => (
<Route key={path} path={path} element={<Component />} />
))}
</Routes>
</Suspense>
</BrowserRouter>
);
}
プリフェッチ戦略
// マウスオーバーでプリフェッチ
function PrefetchLink({
to,
factory,
children,
}: {
to: string;
factory: () => Promise<any>;
children: React.ReactNode;
}) {
const handleMouseEnter = () => {
factory(); // プリフェッチ開始
};
return (
<Link to={to} onMouseEnter={handleMouseEnter}>
{children}
</Link>
);
}
// ルートのプリフェッチ
const dashboardFactory = () => import("./pages/Dashboard");
const DashboardPage = lazy(dashboardFactory);
// ナビゲーションで使用
<PrefetchLink to="/dashboard" factory={dashboardFactory}>
ダッシュボード
</PrefetchLink>
バンドル分析
// webpack-bundle-analyzer の設定
// next.config.js
const withBundleAnalyzer = require("@next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
module.exports = withBundleAnalyzer({
// Next.js の設定
});
# バンドル分析の実行
ANALYZE=true npm run build
Claude Codeでの活用
コード分割の導入をClaude Codeに依頼するプロンプトです。パフォーマンス改善の全体的なアプローチはSSR vs SSG比較、開発効率化は生産性を3倍にする10のTipsも参照してください。
バンドルサイズを最適化して。
- ルートベースのコード分割を導入
- 重いライブラリ(chart.js、moment等)を遅延読み込みに
- Suspenseでローディング状態を統一
- バンドル分析して改善レポートを出して
コード分割の詳細はReact公式ドキュメントを参照してください。Claude Codeの活用法は公式ドキュメントを確認しましょう。
Summary
コード分割はユーザー体験に直結するパフォーマンス最適化です。Claude Codeにバンドル分析から実装まで一貫して依頼すれば、効果的な分割ポイントを見つけて最適化できます。
Related Posts
10 Tips to Triple Your Productivity with Claude Code
Learn about 10 tips to triple your productivity using Claude Code. Practical tips and code examples included.
Canvas/WebGL Optimization with Claude Code
Learn about canvas/webgl optimization using Claude Code. Practical tips and code examples included.
Markdown Implementation with Claude Code
Learn about markdown implementation using Claude Code. Practical tips and code examples included.