Mid #performance#bundle#code-splitting
next/dynamic và phân tích bundle: giảm JavaScript gửi tới client thế nào?
⚡ Trả lời nhanh
`next/dynamic` lazy-load Client Component (code-splitting, tùy chọn `ssr: false`, `loading`). Đo bằng `@next/bundle-analyzer` để tìm thư viện nặng, rồi giữ logic ở Server Component, import theo module con và chỉ load khi cần.
"use client";
import dynamic from "next/dynamic";
const Chart = dynamic(() => import("./Chart"), {
loading: () => <p>Đang tải biểu đồ...</p>,
ssr: false, // thư viện đụng window
});
Quy trình tối ưu:
- Bật analyzer:
withBundleAnalyzer({ enabled: process.env.ANALYZE === "true" })(nextConfig), chạyANALYZE=true next build. (Turbopack có analyzer riêng ở bản mới.) - Tìm chunk lớn, như moment, lodash toàn bộ, thư viện chart, editor.
- Xử lý: import theo hàm (
lodash/debouncehoặclodash-es), thay thư viện nhẹ hơn, dynamic import phần dưới fold/modal. - Chuyển phần không tương tác sang Server Component, vì thư viện chỉ dùng ở server không vào bundle client.
optimizePackageImportstrongnext.configgiúp tree-shake thư viện barrel.React.lazy+ Suspense cũng dùng được;next/dynamicbổ sungssr: false.