< / >
Published on

Modules

CommonJS, synchronous and prevalent in Node.js, uses module.exports for exporting and require() for importing. ES6 Modules, asynchronous and native to modern browsers, employ export for exporting and import for importing, offering better performance and flexibility for web development.

Table of Contents

CommonJS

  • Synchronous: CommonJS modules are loaded synchronously. This means that when a module is required, the entire contents of the module are loaded and executed before continuing with the rest of the code.
  • Used in Node.js: CommonJS is the module format used in Node.js by default.
  • Dynamic Loading: Modules can be loaded dynamically using require() function.
  • Exports: Modules can export values by assigning them to module.exports or exports object.
  • Single Export: Each module can only have one default export.

Example:

 // Exporting
module.exports = {
    key: value,
    func: function() { ... }
}

// Importing
const myModule = require('./myModule');
  • Exporting: In CommonJS, you assign the object or function you want to export to module.exports or exports.
  • Importing: To import a module, you use the require() function, passing the path to the module file.

ES6 Modules

  • Asynchronous: ES6 modules are loaded asynchronously. This means that the browser can start fetching the module while the rest of the page continues to load and execute.
  • Native Support in Browsers: ES6 modules are natively supported in modern browsers without requiring a transpiler like Babel.
  • Static Analysis: The structure of ES6 modules is analyzed statically, allowing for optimizations like tree-shaking (removal of unused code).
  • Named Exports: Modules can export multiple values using named exports.
  • Default and Named Exports: A module can have both a default export and named exports.

Example:

// Exporting
export const key = value;
export function func() { ... }
export default something;

// Importing
import { key, func } from './myModule';
import something from './myModule';
  • Exporting: In ES6 modules, you use the export keyword to export values. You can export constants, functions, classes, etc. You can also export a default value using export default.
  • Importing: You use the import keyword to import values from a module. You can import specific named exports or the default export.

Key Differences

  • Syntax: The syntax for exporting and importing in CommonJS and ES6 modules is different.
  • Browser Support: ES6 modules are supported natively in modern browsers, while CommonJS is primarily used in Node.js environments.
  • Synchronous vs. Asynchronous: CommonJS modules are synchronous, whereas ES6 modules are asynchronous, allowing for better performance in browser environments.
  • Default Export: ES6 modules support default exports, while CommonJS does not have built-in support for default exports.