What are CommonJS Modules?

Share this video with your friends

Send Tweet
Published 9 years ago
Updated 4 years ago

CommonJS modules provide a clean way to import dependencies in JavaScript.

Man: [00:00] The state of the art and [inaudible] web development has undergone some pretty radical changes over the last several years, not the least of which was how you manage multiple source files when you're doing frame development with JavaScript.

[00:15] We started out years ago and had tag soup where we had lots and lots of script tags. They all had to be kept in the right order. It was really hard to debug if a dependency was loaded out of order. After that we got things like the AMD module format that came along and with it tools like RequireJS.

[00:38] Those require you to have some configuration that looks something like this. Generally that's going to be a lot bigger than this. Then your actual files that are written in AMD tend to have a lot of boiler plate along the lines of this where you've got your dependencies listed here and then your actual code is inside of another function. Then you're going to return an object or maybe another function.

[01:05] It's a lot more mental overhead than is really, I think, ideal or necessarily. Thankfully node JS came along and gave us the CommonJS module format. Whereas AMD stands for Asynchronous Module Definition, CommonJS is a synchronous system. Since it started in node where you're working directly off of the file system rather than serving files over a network, it can just specifically refer to a file on the file system and immediately have the results.

[01:42] What we have in this module format is a much cleaner system with basically no mental overhead and no boiler plate. You simply say, "I need this other file. This is its name. This is what I want to call the variable that its value is going to be put into," then in that file you just explicitly say, "I want to expose a property named foo. I want to expose a property named bar."

[02:10] Or alternatively you could just expose a single function. It's extremely straightforward, what your module is exposing and what your module is getting back, how it's being assigned. There's no positional matching that has to happen.

[02:28] In this AMD example, we've got cart and then inventory. We have to make sure to keep these arguments in the same order. There are alternative RequireJS syntaxes that make it a little easier and make it so you don't have to worry about this sort of thing as much, but the default is generally going to be like this.

[02:51] Once you get above two or three arguments, it gets pretty messy and hard to maintain. In future videos, we'll look at how you can use the CommonJS module format for frontend development using a tool called Browserify.