Table of Contents

Javascript - CommonJs

About

CommonJs 1) 2) is a Module format definition

They have defined:

The CommonJS module proposal specifies a simple API for declaring modules server-side (and unlike AMD) attempts to cover the server side with io, filesystem, promises and more. Due to its history and implementation 3) , using CommonJS modules in the most common of JS environments, the browser, is non-optimal today.

The commonJS format is the default format used by Node.js. Therefore a CommonJS module will run on node.

Syntax

The CommonJS (CJS) list participants 4) have worked out the module format.

The CJS mechanisms contain two primary parts:

A CJS module does not use any function wrappers such as the AMD define to specify an id or dependencies.

require

Import is done via the require function

// require will import code from another module
var MyDependency = require('my-dependency');

Export

The module exposes its public api via the exports property

// module.exports will make its property public 
exports = ...;

Loader

Server

Browser

There is not so much adoption of CJS in the browser because:

There was loader but most of them are now no more supported