Code Splitting
Alih-alih mengirim seluruh JavaScript aplikasi dalam satu bundle besar, code splitting memecahnya menjadi chunk yang lebih kecil dan hanya load yang dibutuhkan.
Dynamic Import
// TANPA code splitting — semuanya di-bundle
import { heavyChart } from "./chart";
// DENGAN code splitting — di-load saat dibutuhkan
const loadChart = async () => {
const { heavyChart } = await import("./chart");
heavyChart.render(data);
};
Route-based Splitting
Paling umum — setiap halaman/route menjadi chunk terpisah:
// React lazy loading
const Dashboard = React.lazy(() => import("./Dashboard"));
const Settings = React.lazy(() => import("./Settings"));
// Vue async component
const Dashboard = defineAsyncComponent(() => import("./Dashboard.vue"));
Component-based Splitting
Komponen besar yang jarang digunakan (modal, chart, editor):
// Hanya load ketika user klik "Show Chart"
button.onclick = async () => {
const { Chart } = await import("./chart-library");
new Chart(canvas, config);
};
Tips
- Target: chunk < 100KB gzipped untuk fast 3G
- Gunakan bundler analyzer (webpack-bundle-analyzer, rollup-plugin-visualizer) untuk identifikasi chunk besar
- Prefetch chunk yang mungkin dibutuhkan:
<link rel="prefetch" href="chart.js">
Bundle Analysis Tools
Sebelum code splitting, kita perlu tahu apa yang membuat bundle besar. Tools berikut memvisualisasikan komposisi bundle:
- webpack-bundle-analyzer — treemap interaktif untuk Webpack. Ukuran kotak = ukuran modul. Wajib untuk project Webpack.
- source-map-explorer — bundler-agnostic, butuh source map saja. Cocok untuk CRA dan project production yang sudah di-build.
- vite-plugin-visualizer (alias rollup-plugin-visualizer) — treemap/sunburst/network diagram untuk Vite dan Rollup.
- esbuild-visualizer — untuk project esbuild/tsup.
- bundlephobia.com — cek ukuran npm package sebelum install.
Apa yang Dicari
- Library besar yang tidak ter-tree-shake —
moment(~290KB) bisa digantidate-fnsataudayjs(~6KB). - Barrel import accidental —
import { debounce } from "lodash"mengimport seluruh lodash (~70KB). Gunakanimport debounce from "lodash/debounce"ataulodash-esdengan tree-shaking. - Duplicate dependency — dua versi library yang sama karena semver mismatch. Cek dengan
npm ls <package>. - Polyfill tidak perlu —
core-jspolyfill untuk target browser modern membuang byte. SettargetsBrowserslist dengan benar. - Source map ikut production — pastikan
sourcemap: falseatau serve source map ke error monitoring saja (Sentry, Bugsnag).