Node.js Module System

Table of contents

No heading

No headings in the article.

Node.js has two module systems:

  1. CommonJS Modules:

  2. ECMAScript Modules (ESM):

CommonJS Modules:

  • This is the traditional module system in Node.js.

  • Files with .cjs extension are treated as CommonJS modules.

  • Files with .js extension are treated as CommonJS modules unless the nearest package.json file has "type": "module".

  • You use require() to import modules and module.exports to export functionality.

    example -

      // math.js
      function add(a, b) {
        return a + b;
      }
    
      module.exports = { add }; 
    
      // app.js
      const math = require('./math');
      console.log(math.add(2, 3)); // 5
    

    ECMAScript Modules (ESM):

    • This is the modern module system, aligned with the browser's module system.

    • Files with .mjs extension are treated as ES modules.

    • Files with .js extension are treated as ES modules if the nearest package.json file has "type": "module".

    • You use import to import modules and export to export functionality.

  •   // math.mjs
      export function add(a, b) {
        return a + b;
      }
    
      // app.mjs
      import { add } from './math.mjs';
      console.log(add(2, 3)); // 5
    

    Key Differences:

  • Syntax: ESM uses import and export, while CommonJS uses require and module.exports.

  • Asynchronous: ESM is asynchronous by nature, allowing for better performance.

  • Compatibility: ESM is the future standard, while CommonJS is still widely used.

    Choosing the Right Module System:

  • For new projects, ESM is recommended.

  • For existing projects using CommonJS, you can gradually migrate to ESM.

  • If you need to support older Node.js versions, CommonJS is your only option.

Thank you !