CommonJS modules
As we’ve already mentioned throughout this chapter, CommonJS is gradually being replaced by ES modules, and it’s now recommended to use ES modules for new projects and libraries. However, CommonJS is not officially deprecated, and given its long-standing role in the JavaScript ecosystem, it’s still important to have a basic understanding of it. This knowledge will enable you to work confidently with older code bases and libraries.
Let’s have a look at the basic syntax of CommonJS.
Two of the main concepts of the CommonJS specification are as follows:
require
, which is a function that allows you to import a module from the local filesystem.exports
andmodule.exports
, which are special variables that can be used to export public functionality from the current module.
A simple CommonJS module might look like this:
// math.cjs
'use strict'
function add(a, b) {
return a + b
}
module.exports...