What is code splitting and bundle optimization?

Answer

Code splitting divides JavaScript bundles into smaller chunks loaded on demand, reducing initial page load time. Types: Route-based splitting: each page/route gets its own JavaScript bundle. This is automatic in Next.js, Remix, and SvelteKit. Component-based splitting: dynamically import heavy components: const Modal = dynamic(() => import("./Modal")) in Next.js. Library splitting: separate vendor bundles for libraries that change less frequently — better long-term caching. Vite configuration: build.rollupOptions.output.manualChunks for custom splitting. Bundle analysis: webpack-bundle-analyzer: visual treemap of bundle contents. Bundlephobia: check library sizes before adding them. source-map-explorer: analyze bundle from source maps. Common optimization targets: moment.js (replace with date-fns or Day.js), lodash (use lodash-es + tree shaking), heavy chart libraries (lazy-load). Tree shaking: removes dead code. Requires ES modules (import/export, not require) and production builds. Effective tree shaking can reduce bundle by 30-50% for common libraries.