CommonJS Modules

Learn how to make custom loaders, define modules, and distinguish module.exports and exports using CommonJS.

CommonJS is the first module system originally built into Node.js. Node.js’ CommonJS implementation respects the CommonJS specification, with the addition of some custom extensions.

Let’s summarize two of the main concepts of the CommonJS specification:

• require() is a function that allows us to import a module from the local filesystem.

• exports and module.exports are special variables that can be used to export public functionality from the current module.

A homemade module loader

To understand how CommonJS works in Node.js, let’s build a similar system from scratch. The following code creates a function that mimics a subset of the functionality of the original require() function of Node.js.

Let’s start by creating a function that loads the content of a module, wraps it into a private scope, and evaluates it:

Get hands-on with 1400+ tech skills courses.