Lesson 52 of 55
javascriptModules – CommonJS vs ES Modules
12 mins
Course progress95%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 52 of 55
javascript12 mins
Keep these ideas in mind as you work through the lesson.
JavaScript now supports native ES Modules (import/export). Historically Node used CommonJS (require). Understanding both helps you work across environments.
// math.cjs
function mul(a,b){ return a*b; }
module.exports = { mul };
// app.cjs
const { mul } = require('./math.cjs');
console.log(mul(3,4));
// 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));
\"type\": \"module\" to package.json, or use .mjs extension.// Import a CJS module from ESM
import pkg from './cjs-lib.cjs'; // `pkg` is the `module.exports` value.
(async () => {
const {default: greet} = await import('./greet.mjs');
greet();
})();
type=\"module\").main for CJS, module for ESM) to maximise compatibility.Understanding both systems prevents unexpected undefined imports and makes your build pipeline smoother.