ECMAScript and CommonJS are both JavaScript standards, but they focus on different aspects of the language.
ECMAScript
ECMAScript (ES) is a specification standard that defines the core features of JavaScript. Versions like ES5, ES6 (also known as ES2015), and later define syntax and functionality such as variables, functions, classes, promises, and more.
ECMAScript introduced native module support in ES6 (2015) with the import/export syntax.
// file: arithmetic.js
export const add = (a, b) => a + b;
// file: app.js
import { add } from './arithmetic.js';
console.log(add(2, 3)); // Output: 5
CommonJS
CommonJS is a module standard used primarily in server-side JavaScript environments like Node.js. It predates ES6 modules and defines how modules and their dependencies should be structured.
CommonJS uses require() to import modules and module.exports or exports to export them.
// file: arithmetic.js
const add = (a, b) => a + b;
module.exports = { add };
// file: app.js
const { add } = require('./arithmetic');
console.log(add(2, 3)); // Output: 5
Node.js supports both module systems. CommonJS is the default in older Node versions, but you can use ECMAScript modules by enabling "type": "module" in package.json.
No comments:
Post a Comment