This is a small write-up which only touch bases and hovers around only theory, theory and theory of CommonJS. Do not worry we have a surprise at the end of this small write-up which will give more inner learning of the CommonJS topic to the reader.
CommonJS is a specification which helps to load modules from one file to other file.
Before moving ahead let’s have a shallow-dive in understanding CommonJS. Below we move on for the same.
"CommonJS" initiative was started back in January 2009 by Kevin Dangoorwhen he was working at Mozilla with name "ServerJS"and later renamed it to "CommonJS"in the same year 2009 in the month of August.
The two important and used keywords in CommonJS are "exports" and "require". The keyword "exports" will be used in the file which wants to get exposed to the external world. So with that it will get enabled to be readily available to the file who wants it.
Whereas the file who will be consuming those exposed file has to mention "require" keyword in order to make it usable. Below image is such an example where "Module Y" will be used by "Module X" i.e. in other words "Module X" will be consuming "Module Y". Within "Module Y" file we have to mention "exports" keywords while "Module X" has to implement the keyword "require" within "Module X" file.
Unless the "exports" keyword is used consumer or the file which is trying to use or consume it cannot get it.With the use of keywords we can define dependencies between modules.
Please Note: "exports" and "require" are not keyword they are more of CommonJS specification.
So for it sequence would be, whenever compiler goes through the file and if "require" keyword is found. Thenthe compiler understands that exiting file is having dependencies on other file and in order to complete that dependency it will start locating the file in whichit gets corresponding "exports" keyword using the same path which is mentioned next to "require" specification keyword in order to get its job done.
As promised do not forget to click on the following video link to learn CommonJS with practical code explanation in complete depth :-