Modules (ESM vs CommonJS)Advanced
1Question 1 of 1
javascriptWhat is the difference between ES Modules (ESM) and CommonJS (CJS)?
Explanation & Concept
• CommonJS (`require` / `module.exports`): The original Node.js module system. Modules are loaded **synchronously** at runtime. Dynamic imports (`require(path)`) are supported anywhere, but static analysis for tree-shaking is difficult. • ES Modules (`import` / `export`): The official ECMAScript standard. Modules are parsed and loaded **asynchronously** before execution. Static module declarations enable bundlers (Webpack, Vite) to perform dead code elimination (tree-shaking).
Code Example
javascript
// 1. ES Module (ESM) syntax (Recommended)
import { readFile } from "node:fs/promises";
export async function getFileData(path) {
return await readFile(path, "utf-8");
}
// 2. CommonJS (CJS) syntax (Legacy)
// const fs = require("node:fs");
// module.exports = { getFileData };How It Works & Key Takeaways
Modern Node.js and browser environments prefer ESM. Use `"type": "module"` in `package.json` to enable ESM project-wide.
Mock Test · 1 Questions · Optional
Ready for Web APIs & Fetch?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions