» Glossary » CommonJS

Before the JavaScript language introduced modules in the ES2016 standard, authors created their own module systems. The CommonJS module system grew out of the JavaScript in the server community with the goal of creating a standard for code reuse between system, and became one of the most popular module system for JavaScript thanks to its adoption in the node.js and npm ecosystems.

The standard says that CommonJS modules:

  • Import other modules through the require keyword.
  • Export their contents through the exports keyword. 
// contents of math-module.js file
exports.add = function( a, b ) {
  return a + b;
// contents of utils.js file
var math = require( 'math-module.js' );
exports increment = function( a ) {
  returns math.add( a, 1 );
// contents of app.js file
var utils = require( 'utils' );
var newValue = utils.increment( 2 );
console.log( newValue );

Environments such as Node.js made require and module.exports available in the global scope, and wrap every JavaScript file with a function similar to

(function (exports, require, module, __filename, __dirname) { 
// Code injected here

so it can be run by the JavaScript interpreted.