CommonJs

Commonjs

The CommonJS group defined a module format to solve JavaScript scope issues by making sure each module is executed in its own namespace.

This is achieved by forcing modules to explicitly export those variables it wants to expose to the “universe”, and also by defining those other modules required to properly work.

To achieve this CommonJS gives you two tools:

  1. the require() function, which allows to import a given module into the current scope.
  2. the module object, which allows you to export something from the current scope.

The mandatory hello world example:

Plain Simple JavaScript

Here is an example without CommonJS:

We will define a value in a script file named salute.js. This script will contain just a value that will be used in other scripts:

// salute.js
var MySalute = "Hel