CommonJS …what, why and how

Constance Crutchfield
3 min readOct 22, 2018

What is CommonJS? CommonJS is a module formatting system. It is a standard for structuring and organizing JavaScript code. CJS assists in the server-side development of apps and it’s format has heavily influenced NodeJS’s module management.

Ok… So, what is a module? A module is just a bit of code encapsulated in a file, and exported to another file. Modules focus on a single part of functionality and remain loosely coupled with other filed in an application. This is because there are no global or shared variables between modules, as they only communicate via the module.exports object. Any code that you want to be accessible in another file can be a module!

“boy wearing gray vest and pink dress shirt holding book” by Ben White on Unsplash

How can I use CommonJS? CommonJS wraps each module in a function called ‘require’, and includes an object called ‘module.exports’, which exports code for availability to be required by other modules. All you have to do is add whatever you want accessible to other files onto the ‘exports’ object and require the module in the dependent file. the syntax for the require function is “var VariableName = require(‘moduleId_or_pathToModule’);”. Here’s an example…

Why would I need CommonJS?? CommonJS allows for code encapsulation, as modules with no global variables won’t conflict with each other when your application is run. CommonJS aids in dependancy-injection management. Modules are loaded synchronously, so modules that are dependent on other modules must be read further down in the code. The separation of functionality makes for much easier testing and debugging of code. Without module systems like CommonJS, dependancies had to be loaded in <script> tags in the header of an HTML file, OR all code had to be lumped together which is incredibly slow and inefficient for file loading. Not to mention, your app would completely crash if there was a bug in any part of the code! See the difference in managing dependencies here..

In conclusion, CJS modules are reusable code made available for dependent files. CommonJS is an easy-to-understand way to implement dependency management, separation of concerns, and effective testing of a single part of your application.

--

--