Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Modules – CommonJS vs ES Modules | JavaScript Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. JavaScript Course

Lesson 52 of 55

·javascript

Modules – CommonJS vs ES Modules

12 mins

Course progress95%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • CommonJS uses `require`/`module.exports`; ES Modules use `import`/`export`.
  • ES Modules are statically analyzable, enabling tree‑shaking and better tooling.
  • Node can run ES Modules when `"type":"module"` is set or `.mjs` files are used.
  • Dynamic `import()` returns a Promise and works in both environments.

Modules – CommonJS vs ES Modules

JavaScript now supports native ES Modules (import/export). Historically Node used CommonJS (require). Understanding both helps you work across environments.

1️⃣ CommonJS (Node)

// math.cjs
function mul(a,b){ return a*b; }
module.exports = { mul };
// app.cjs
const { mul } = require('./math.cjs');
console.log(mul(3,4));
  • Synchronous, loaded at runtime.
  • Exports an object.

2️⃣ ES Modules (Browser & Node)

// utils.js
export const sub = (a,b) => a-b;
export default function add(a,b){ return a+b; }
// app.js (type=\"module\")
import add, { sub } from './utils.js';
console.log(add(5,2), sub(5,2));
  • Static analysis – imports are hoisted.
  • Supports named and default exports.

3️⃣ Using ES Modules in Node

  • Add \"type\": \"module\" to package.json, or use .mjs extension.
  • Interop:
// Import a CJS module from ESM
import pkg from './cjs-lib.cjs'; // `pkg` is the `module.exports` value.
  • Dynamic import in CJS:
(async () => {
  const {default: greet} = await import('./greet.mjs');
  greet();
})();

4️⃣ When to choose which?

  • Browser‑only code: use ES Modules (type=\"module\").
  • Existing Node projects: stay with CommonJS unless you need tree‑shaking or native ESM features.
  • New libraries: ship both (main for CJS, module for ESM) to maximise compatibility.

Understanding both systems prevents unexpected undefined imports and makes your build pipeline smoother.

Make it stickPractice what you've learned1 quiz · 7 practical tests · Optional activities from JavaScript CourseBrowse activities
Previous lessonNode.js Fundamentals & npmContinue to lesson 53Express.js FundamentalsBack to JavaScript Course curriculum