01
Overview
ESM: static import/export, tree-shakeable, async loading. CommonJS: dynamic require, synchronous, Node.js default (legacy). ESM is the standard. Use import/export in new code. Dynamic import() for lazy loading. package.json type:module enables ESM.
bash
// ESM
export const add=(a,b)=>a+b;
import {add} from "./math.js";
// Dynamic import
const mod=await import("./heavy.js");
// CommonJS (legacy)
const fs=require("fs");
module.exports={add};02
Best Practices
Prefer ESM (import/export) for new code. Use dynamic import() for lazy loading. ESM is async, CJS is sync (cannot mix). Use .mjs extension or type:module. Named exports over default exports. Use import maps for bare specifiers in browsers.
Ready to try ES Modules vs CommonJS?
Visit the official site for the latest version and full documentation.
Visit ES Modules vs CommonJS