Introduction to CommonJS
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:
1 | 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:
1 | exports.uppercase = (str) => str.toUpperCase() |
Any JavaScript file can import and use this module as follows:
1 | const uppercaseModule = require('uppercase.js') |
You can export multiple values from a module:
1 | exports.a = 1 |
To import these values individually, you can use the destructuring assignment feature:
1 | 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:
1 | module.exports = value |
And then import it like this:
1 | const value = require('./file.js') |
Tags: CommonJS, Node.js, modules, JavaScript, libraries, npm, ES Modules, module exports, module imports