ماژول‌ها در جاوا اسکریپت: CommonJS، AMD، و ES Modules






ماژول‌ها در جاوا اسکریپت: CommonJS، AMD، و ES Modules

ماژول‌ها در جاوا اسکریپت: CommonJS، AMD، و ES Modules

CommonJS

CommonJS is a module system used in Node.js for server-side JavaScript development. It allows developers to define modules using the module.exports syntax and import them using the require function.

AMD

AMD (Asynchronous Module Definition) is another module system for JavaScript that is primarily used in browser-based applications. It allows for the asynchronous loading of modules and defines modules using the define function.

ES Modules

ES Modules (ECMAScript Modules) are the official standard for JavaScript modules, introduced in ECMAScript 6 (ES6). They use the import and export keywords to define dependencies between modules.

Key Differences

  • CommonJS is synchronous, while AMD and ES Modules support asynchronous loading.
  • CommonJS is primarily used in Node.js, while AMD and ES Modules are used in browser-based applications.
  • ES Modules are the official standard for JavaScript modules and offer better support for static analysis and tree shaking.

Example


// CommonJS module
// math.js
module.exports = {
  add: function(a, b) {
    return a + b;
  },
  subtract: function(a, b) {
    return a - b;
  }
};

// app.js
const math = require('./math');
console.log(math.add(2, 3)); // Output: 5

// AMD module
// math.js
define(function() {
  return {
    add: function(a, b) {
      return a + b;
    },
    subtract: function(a, b) {
      return a - b;
    }
  };
});

// app.js
require(['math'], function(math) {
  console.log(math.add(2, 3)); // Output: 5
});

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

export function subtract(a, b) {
  return a - b;
}

// app.js
import { add } from './math';
console.log(add(2, 3)); // Output: 5