Sitemap
Hamzah

Hamzah

Modules: What Are They?

--

This article will discusses modules in Node.js, looking at CommonJs (CJS) & ES Modules (ESM)

What Are Modules?

Think of modules like lego blocks, each is different in its own way, each has a specific purpose/responsibility. We then use them together to build amazing things, modules are the same.

  • Modules split code into reusable files (math.js, database.js, etc…)
  • Each module has a specific responsibility
  • Modules help improve organization and maintainability

What is CommonJS (CJS)?

CommonJS (CJS) is the original module system for Node.js, as it was introduced before JavaScript had an official module system.

  • Uses require() to import modules
  • Uses module.exports to export modules
  • Used mainly in older Node projects (good to learn, not use)

What are ES Modules (ESM)?

ES Modules (ESM) are JavaScript’s official module system, and was introduced as part of the JavaScript standard.

    Get Hamzah’s stories in your inbox

    Join Medium for free to get updates from this writer.

  • Uses import to import modules
  • Uses export to export them
  • Is the standard for modern JS applications, supported by Node.js & browsers

CommonJS Module Usage

function add(a, b) {
return a + b;
}

module.exports = add;

This our math.js file, which we are exporting from

const add = require('./math');

console.log(add(2, 3));

This is our index.js file, where we are importing from math.js

ES Modules Usage

export function add(a, b) {
return a + b;
}

This is our new math.js file, where we directly export functions

import { add } from './math.js';

console.log(add(2, 3));

This is the new index.js, where we use the ESM import method

CommonJS vs ES Modules

| Feature | CommonJS (CJS)                  | ES Modules (ESM)                        |
|---------|---------------------------------|-----------------------------------------|
| Origin | Node.js' original module system | JavaScript's official module system |
| Import | `require()` | `import` |
| Export | `module.exports` | `export` |
| Usage | Older Node.js projects | Modern JavaScript applications |
| Support | Node.js | Node.js and browsers |
Press enter or click to view image in full size

--

--