🔰CommonJS

the standard used in Node.js for working with modules.

JSmodule ⟩ CommonJS

a module format defined by the CommonJS group to solve JavaScript scope issues by executing each module in its namespace.

// import
const M = require('./module.js');        // import whole module as an object
const {a, b} = require('./module.js');   // import part of the module
// export
module.exports = { a, b };    // export individual bindings
module.exports = f;           // export a single object/function.

CommonJS module system was created for server-side JavaScript (Node.js) and is not supported by default in browsers.

ES module allows you to have both default export and named exports in one module, unlike CommonJS.

  • loaded synchronously and processed in the order the JS runtime finds them.

  • was invented keeping server-side JS in mind.

  • is not suitable (❓) for the client-side.

  • the npm ecosystem is based on the CommonJS module system.

CommonJS modules behave as singleton instances, no matter how many times you require(..) the same module, you just get additional references to the single shared module instance.

In Node.js require("student") statements, non-absolute paths ("student") assume a ".js" file extension and search "node_modules".

Last updated