
Using CommonJS to Implement Modules in JavaScript

This Article is Over Ten Years Old...
Things can and do move very quickly in tech, which means that tech-related articles go out of date almost as soon as they have been written and published. If you are looking for up-to-date technical advice or opinion, it is unlikely that you will find it on this page.
You may find that my recent articles are more relevant, and you are always welcome to drop me a line if you have a specific technical problem you are trying to solve.
JavaScript has been a popular programming language for years, with a lot of developers using it for building web applications, mobile applications, and desktop applications. As the complexity of these applications increases, the need for modularizing and encapsulating the code becomes necessary. Here, I'll discuss one of the ways of achieving modularity in JavaScript: CommonJS.
CommonJS is a standard for creating modular code in JavaScript. It is a module system used by Node.js, and it allows developers to create modules that can be imported and exported from, and into, other modules. CommonJS is designed to work with server‑side JavaScript but it can also be used in client‑side JavaScript using tools like Browserify or webpack.
One of the benefits of using CommonJS is that it allows developers to write modular code that can be tested and reused easily, without having to rely on patchy native browser support for modules. CommonJS provides a way to define modules, import them into other modules, and export them for use in other modules.
A Basic Example
Let's jump into a couple of basic CommonJS code examples:
// module.jsconst greeting = 'Hello, world!';function greet() { console.log(greeting);}// this is the commonjs export syntaxmodule.exports = { greet };And to bring it into another module:
// index.jsconst { greet } = require('./module.js');greet(); //=> "Hello, world!"
In the first example, we have a module (module.js) which exports a function called greet. The greet function logs a greeting to the console. Below that, we import the greet function from the module.js file and call it.
The require function is used to import modules in CommonJS. When we call require("./module.js"), CommonJS looks for a file named module.js in the current directory and loads it. The module.exports object is used to export the greet function from the module.js file.
A More Complex Example
Now, let's take a look at a more advanced CommonJS code example:
// file1.jsconst { logMessage } = require('./logger.js');function doSomething() { logMessage('doing something');}module.exports = { doSomething };// file2.jsconst { doSomething } = require('./file1.js');doSomething();// logger.jsfunction logMessage(message) { console.log(`[logger] ${message}`);}module.exports = { logMessage };Here we have three files:
file1.jsexports a function calleddoSomethingthat logs a message to the console using thelogMessagefunction fromlogger.jsfile2.jsimports thedoSomethingfunction fromfile1.jsand calls itlogger.jsdefines and exports thelogMessagefunction.
When we run file2.js, it calls the doSomething function from file1.js, which logs the message using the logMessage function from logger.js. In this way, we can chain together modules to create more complex and encapsulated applications.
Compared Against Other Strategies
As you might imagine, when compared to other strategies for modularizing JavaScript code, CommonJS has some advantages and disadvantages.
Advantages
One advantage of CommonJS is that it is simple and easy to use. The syntax is straightforward, and it is easy to understand how modules are imported and exported. This makes it a great choice for smaller projects or for developers who are new to JavaScript.
Another advantage of CommonJS is that it works well with Node.js. If you are building a server‑side application with Node.js, CommonJS is the de facto standard for modularizing your code.
Disadvantages
However, there are some potential issues that developers may come across when using CommonJS. One issue is that CommonJS is synchronous, which means that modules are loaded and executed in a blocking manner. This can cause performance issues if you have a lot of modules that need to be loaded or rely on asynchronous behaviours within your modules.
Another issue is that CommonJS is not compatible with the upcoming ES6 module syntax, which will eventually become the new standard for JavaScript modules. This means that if you want to use the ES6 module syntax in the future, you may find that you need to refactor a lot of code, or otherwise use a module bundler like webpack or rollup to convert your code to CommonJS.
The Wrap‑Up
At this point, native support for modularisation in JavaScript is patchy at best. CommonJS is a simple and effective way to modularise JavaScript code and is especially useful for server‑side JavaScript with Node.js. However, as the web development landscape continues to evolve, developers may want to explore other modularization strategies like ES6 modules or AMD modules.
Categories:
Related Articles

Five Tips for Transitioning from Permanent to Freelancing. 
String to Integer (atoi): Decoding Strings in JavaScript. String to Integer (atoi): Decoding Strings in JavaScript

Replace Inline Styles in Gatsby with an External CSS File. Replace Inline Styles in Gatsby with an External CSS File

Asynchronous Module Definition (AMD) in JavaScript. Asynchronous Module Definition (AMD) in JavaScript

Vue's provide/inject API: When and How to Use It. Vue's
provide/injectAPI: When and How to Use It
Add Two Numbers in TypeScript: Linked Lists Without the Hand‑Waving. Add Two Numbers in TypeScript: Linked Lists Without the Hand‑Waving

Understanding Media Queries in CSS. Understanding Media Queries in CSS

Exploring the Liquid Templating Language. Exploring the Liquid Templating Language

Commenting in Front‑End Languages. Commenting in Front‑End Languages

Check If a String Contains Only Whitespace with JavaScript. Check If a String Contains Only Whitespace with JavaScript

The Role of Dependency Injection in Angular. The Role of Dependency Injection in Angular

Rendering Contentful Rich Code Snippets in Gatsby. Rendering Contentful Rich Code Snippets in Gatsby