Javascript Modules Lanjut Dynamic Import Tree Shaking Reexport
Definisi
ES Modules lanjut: import() dinamis (lazy load), tree-shaking (bundler buang kode tak terpakai), dan re-export (export ... from) untuk merangkum API.
Kanan dipakai
- Dynamic import: load chunk besar (chart, editor) saat butuh, bukan saat awal.
- Tree-shaking: pastikan bundler (Vite/Webpack/Rollup) bisa buang kode mati.
- Re-export: buat barrel file (
index.js) agar impor rapi.
Cara kerja
Dynamic import
button.onclick = async () => {
const { chart } = await import('./chart.js');
chart.render();
};Re-export
// utils/index.js
export { debounce } from './debounce.js';
export { throttle } from './throttle.js';Tree-shaking friendly
// hindari side-effect global di top-level
export function pureHelper() {}Struktur alur
Loading diagram...
Catatan implementasi
import()mengembalikan Promise; cocok denganReact.lazy/Suspense.- Tree-shaking butuh
sideEffects: falsedi package.json dan ESM (bukan CommonJS). - Re-export barrel bisa memicu bundler include lebih banyak; gunakan selective re-export.
- Nama file
index.jssebagai barrel umum, tapi hati-hati circular import.
Kesalahan umum
- Dynamic import tanpa await/catch: Promise tak ditangani, error terlewat.
- Side-effect di modul: tree-shaking gagal buang kode.
- Barrel import berlebih: bundle jadi besar karena ikut import tak perlu.
- Circular dependency: nilai undefined saat init — hindari import mutal.