The CommonJS module specification is the standard used in Node.js for working with modules. Modules allow you to encapsulate functionality and make it available to other JavaScript files as libraries.
In contrast, client-side JavaScript in the browser uses a different standard called ES Modules.
Modules are incredibly useful because they enable you to create reusable snippets of functionality that can be tested independently. The CommonJS format is the foundation of the extensive npm ecosystem.
To import a module in CommonJS, you can use the following syntax:
const package = require('module-name')
In CommonJS, modules are loaded synchronously and processed in the order in which the JavaScript runtime encounters them. However, this system was originally designed for server-side JavaScript and is not suitable for the client-side, which is why ES Modules were introduced.
A JavaScript file becomes a module when it exports one or more symbols, such as variables, functions, or objects. For example, the “uppercase.js” module might look like this:
exports.uppercase = (str) => str.toUpperCase()
Any JavaScript file can import and use this module as follows:
const uppercaseModule = require('uppercase.js')
uppercaseModule.uppercase('test')
You can export multiple values from a module:
exports.a = 1
exports.b = 2
exports.c = 3
To import these values individually, you can use the destructuring assignment feature:
const { a, b, c } = require('./uppercase.js')
Alternatively, if you only want to export one value, you can use the following syntax in the “file.js” module:
module.exports = value
And then import it like this:
const value = require('./file.js')
Tags: CommonJS, Node.js, modules, JavaScript, libraries, npm, ES Modules, module exports, module imports