Chapter 8 of 12
8.1 ES Modules (ESM) vs CommonJS (CJS)
CommonJS (require / module.exports) is synchronous and dynamic (Node.js legacy standard). ES Modules (import / export) are static, asynchronous, and natively supported across modern browsers and runtimes.
ES Module Imports & Dynamic Importjavascript
// Static Export & Import
export const calculateTax = (amount) => amount * 0.2;
import { calculateTax } from './tax.js';
// Dynamic Import (Code Splitting / Lazy Loading)
async function loadChartModule() {
const { renderChart } = await import('./analytics.js');
renderChart();
}What is Tree Shaking?
Tree shaking is a dead-code elimination technique used by modern bundlers (Vite, Rollup, Rspack). Because ES Modules have a static structure (imports cannot change at runtime), bundlers can statically analyze your dependency graph and exclude unused exports from the production bundle!