Sobes.tech
Middle

What is the difference between ES modules and CommonJS?

sobes.tech AI

Answer from AI

ES modules (ESM) and CommonJS are two standards of module systems in JavaScript.

Main differences:

  • Syntax:

    • ES modules use import and export.
    • CommonJS uses require() and module.exports.
  • Execution:

    • ES modules are loaded statically, allowing tools to perform optimizations (tree shaking).
    • CommonJS is loaded dynamically at runtime.
  • Asynchronous:

    • ES modules support asynchronous loading.
    • CommonJS is synchronous.
  • Support:

    • ES modules are the standard in modern browsers and Node.js.
    • CommonJS is the traditional standard for Node.js.

Example of an ES module:

// math.js
export function sum(a, b) {
  return a + b;
}

// main.js
import { sum } from './math.js';
console.log(sum(2, 3));

Example of CommonJS:

// math.js
function sum(a, b) {
  return a + b;
}
module.exports = { sum };

// main.js
const { sum } = require('./math');
console.log(sum(2, 3));