What is Common Js

  • CommonJS (Common JavaScript) is a module system for JavaScript that was designed to standardize the way JavaScript code is structured for server-side development. It was not originally a part of the ECMAScript specification but was widely adopted and used in environments like Node.js for server-side JavaScript development.
  • Key Features of CommonJS:
  • Module Definition: CommonJS introduces a module format that allows JavaScript code to be organized into modules. Each module encapsulates its functionality, exposing only what is explicitly exported.
  • require Function: The `require` function is a central part of CommonJS and is used to import other modules. It takes a module identifier (usually a path) and returns the exports of that module.


    // Example of requiring a module in CommonJS
    const myModule = require('./myModule');

  • exports Object: Modules in CommonJS use the `exports` object to define what should be exposed to other modules. Any variable or function assigned to `exports` becomes accessible to other modules when they require the module.


    // Example of exporting in CommonJS
    exports.myFunction = function () {
        // code here
    };

  • Synchronous Loading: CommonJS modules are loaded synchronously. When a module is required, the `require` function loads the module and waits for it to be fully executed before moving on to the next statements.
Example of CommonJS Modules:
  • File: `math.js`

    // math.js - CommonJS module

    const add = (a, b) => a + b;

    const subtract = (a, b) => a - b;

    // Exporting functions
    exports.add = add;
    exports.subtract = subtract;

  • File: `app.js`

    // app.js - CommonJS module

    // Requiring the math module
    const math = require('./math');

    // Using functions from the math module
    console.log(math.add(5, 3));       // Outputs: 8
    console.log(math.subtract(8, 3));  // Outputs: 5

  • In this example, `math.js` is a CommonJS module that exports two functions (`add` and `subtract`). `app.js` requires the `math` module using `require` and then uses the exported functions.
CommonJS in Node.js:
  • Node.js embraced the CommonJS module system, making it the standard way to structure code in Node.js applications. When you create a file in a Node.js project, it's treated as a CommonJS module by default.
  • While CommonJS has been a successful and widely adopted module system for server-side JavaScript, the ECMAScript standard has also introduced its own module system (ESM), which uses the `import` and `export` statements. As of Node.js version 13.2.0, Node.js also supports ECMAScript modules alongside CommonJS, providing developers with flexibility in choosing the module system that best fits their needs.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...