Intro to Node CJS vs ESM Modules

Learning Objective: By the end of this lesson, students will understand the key differences between CommonJS (CJS) modules and ECMAScript modules (ESM) in JavaScript and when to use each type.

CommonJS vs ECMAScript modules

JavaScript modules come in two main flavors: CommonJS (CJS) and ECMAScript modules (ESM). Understanding their differences is important for writing code across environments and tooling ecosystems.

CommonJS (CJS) modules

CJS modules were created to address the lack of a native module system in JavaScript for server-side environments. Before ESM was introduced, JavaScript did not have a built-in module standard, which made code organization and reuse more challenging in large-scale applications.

CJS modules filled this gap by providing a way to define encapsulated modules of code, which could then be used in other parts of a Node application.

Characteristics

Example

To require:

const myModule = require('myModule');

To export:

const myFunction = () => {
  console.log("Send me anywhere, I'm ready!");
};

module.exports = myFunction;

🧠 Explore Node’s CJS module documentation for more on CJS.

ECMAScript modules (ESM)

ESM is the modern, official standard for module management in JavaScript. They were created to provide a standard, built-in module system that could be used across different environments, including the browser and server-side (Node) contexts.

Before the introduction of ESM, JavaScript lacked a native module system, leading to the development of various non-standard module formats like CJS.

Characteristics

Example

To import:

import myModule from 'myModule';

To export:

const myFunction = () => {
  console.log("Send me anywhere, I'm ready!");
};

export default myFunction;

🧠 Explore Node’s ESM documentation for more on ESM.

When to use CJS

When to use ESM