Skip to main content

Command Palette

Search for a command to run...

4) Module System

Updated
•View as Markdown
  1. Node Module
    The module system in Node.js is how you organize code into reusable, maintainable pieces. Instead of writing everything in one file, you split functionality into modules and connect them.
    There are two module systems in Node.js
    i) CommonJS (CJS) → older, default in Node.js
    ii) ES Modules (ESM) → modern JavaScript standard
    A module is simply a file containing code (functions, variables, objects) that you can reuse in other files.

    // math.js
    const add = (a, b) => {
        return a + b;
    }
    
    module.exports = add;
    
  2. CommonJS (CJS)
    This is the traditional Node.js module system.
    i) module.exports
    Used to export data/functions from a file

    // math.js
    const add = (a, b) => a + b;
    const sub = (a, b) => a - b;
    
    module.exports = { add, sub };
    

    You can export: Functions, Objects, Variables, Classes.
    ii) require()
    Used to import modules

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

    Key Characteristics of CommonJS
    i) Synchronous loading
    ii) Used by default in Node.js
    iii) Works well on the server
    iv) Uses require() and module.exports

  3. ES Modules (ESM)
    This is the modern JavaScript module system.
    To use it in Node.js: Add "type": "module" in package.json OR Use .mjs extension.
    i) Export
    Used to export values

    // Named export
    // math.js
    export const add = (a, b) => a + b;
    export const sub = (a, b) => a - b;
    
    // Default export
    // math.js
    const add = (a, b) => a + b;
    export default add;
    

    ii) Import
    Used to import values

    // Named import
    import { add, sub } from './math.js';
    
    // Default import 
    import add from './math.js';
    
  4. Key Differences
    i) Import Timing
    require() → runtime (dynamic)
    import → compile time (static)
    ii) Conditional Imports

    if (true) {
      const module = require('./math'); 
      // ✅ allowed
    }
    
    if (true) {
      import('./math.js'); 
      // ❌ static import not allowed like this
    }
    

    iii) Default vs Named Exports

    // ES Modules
    export default function() {}
    export const x = 10;
    
    // CommonJS
    module.exports = function() {};
    
  5. When to Use What?
    Use CommonJS
    i) Legacy Node.js projects
    ii) Quick scripts
    Use ES Modules
    i) Modern applications
    ii) Frontend + backend consistency
    iii) Better tooling & tree-shaking

    Node.js has two module systems: CommonJS and ES Modules
    require() → imports modules (CJS)
    module.exports → exports modules (CJS)
    import → imports modules (ESM)
    export → exports modules (ESM)
    ES Modules are modern, static, and preferred today