Home Web Front-end JS Tutorial Node.js: A brief history of cjs, bundlers, and esm

Node.js: A brief history of cjs, bundlers, and esm

Dec 15, 2024 am 05:36 AM

Node.js: A brief history of cjs, bundlers, and esm

Introduction

If you're a Node.js developer, you've probably heard of cjs and esm modules but may be unsure why there's two and how do these coexist in Node.js applications. This blogpost will briefly walk you through the history of JavaScript modules in Node.js (with examples ?) so you can feel more confident when dealing with these concepts.

The global scope

Initially JavaScript only had a global scope were all members were declared. This was problematic when sharing code because two independent files may use the same name for a member. For example:

greet-1.js

function greet(name) {
  return `Hello ${name}!`;
}
Copy after login
Copy after login

greet-2.js

var greet = "...";
Copy after login
Copy after login

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Collision example</title>
  </head>
  <body>
    <!-- After this script, `greet` is a function -->
    <script src="greet-1.js"></script>

    <!-- After this script, `greet` is a string -->
    <script src="greet-2.js"></script>

    <script>
        // TypeError: "greet" is not a function
        greet();
    </script>
  </body>
</html>
Copy after login
Copy after login

CommonJS modules

Node.js formally introduced the concept of JavaScript modules with CommonJS (also known as cjs). This solved the collision problem of shared global scopes since developers could decide what to export (via module.exports) and import (via require()). For example:

src/greet.js

// this remains "private"
const GREETING_PREFIX = "Hello";

// this will be exported
function greet(name) {
  return `${GREETING_PREFIX} ${name}!`;
}

// `exports` is a shortcut to `module.exports`
exports.greet = greet;
Copy after login
Copy after login

src/main.js

// notice the `.js` suffix is missing
const { greet } = require("./greet");

// logs: Hello Alice!
console.log(greet("Alice"));
Copy after login
Copy after login

npm packages

Node.js development exploded in popularity thanks to npm packages which allowed developers to publish and consume re-usable JavaScript code. npm packages get installed in a node_modules folder by default. The package.json file present in all npm packages is especially important because it can indicate Node.js which file is the entry point via the "main" property. For example:

node_modules/greeter/package.json

{
  "name": "greeter",
  "main": "./entry-point.js"
  // ...
}
Copy after login
Copy after login

node_modules/greeter/entry-point.js

module.exports = {
  greet(name) {
    return `Hello ${name}!`;
  }
};
Copy after login
Copy after login

src/main.js

// notice there's no relative path (e.g. `./`)
const { greet } = require("greeter");

// logs: Hello Bob!
console.log(greet("Bob"));
Copy after login
Copy after login

Bundlers

npm packages dramatically sped up the productivity of developers by being able to leverage other developers' work. However, it had a major disadvantage: cjs was not compatible with web browsers. To solve this problem, the concept of bundlers was born. browserify was the first bundler which essentially worked by traversing an entry point and "bundling" all the require()-ed code into a single .js file compatible with web browsers. As time went on, other bundlers with additional features and differentiators were introduced. Most notably webpack, parcel, rollup, esbuild and vite (in chronological order).

ECMAScript modules

As Node.js and cjs modules became mainstream, the ECMAScript specification maintainers decided to include the module concept. This is why native JavaScript modules are also known as ESModules or esm (short for ECMAScript modules).

esm defines new keywords and syntax for exporting and importing members as well as introduces new concepts like default export. Over time, esm modules gained new capabilities like dynamic import() and top-level await. For example:

src/greet.js

function greet(name) {
  return `Hello ${name}!`;
}
Copy after login
Copy after login

src/part.js

var greet = "...";
Copy after login
Copy after login

src/main.js

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Collision example</title>
  </head>
  <body>
    <!-- After this script, `greet` is a function -->
    <script src="greet-1.js"></script>

    <!-- After this script, `greet` is a string -->
    <script src="greet-2.js"></script>

    <script>
        // TypeError: "greet" is not a function
        greet();
    </script>
  </body>
</html>
Copy after login
Copy after login

Over time, esm became widely adopted by developers thanks to bundlers and languages like TypeScript since they are capable of transforming esm syntax into cjs.

Node.js cjs/esm interoperability

Due to growing demand, Node.js officially added support for esm in version 12.x. Backwards compatibility with cjs was achieved as follows:

  • Node.js interprets .js files as cjs modules unless the package.json sets the "type" property to "module".
  • Node.js interprets .cjs files as cjs modules.
  • Node.js interprets .mjs files as esm modules.

When it comes to npm package compatibility, esm modules can import npm packages with cjs and esm entry points. However, the opposite comes with some caveats. Take the following example:

node_modules/cjs/package.json

// this remains "private"
const GREETING_PREFIX = "Hello";

// this will be exported
function greet(name) {
  return `${GREETING_PREFIX} ${name}!`;
}

// `exports` is a shortcut to `module.exports`
exports.greet = greet;
Copy after login
Copy after login

node_modules/cjs/entry.js

// notice the `.js` suffix is missing
const { greet } = require("./greet");

// logs: Hello Alice!
console.log(greet("Alice"));
Copy after login
Copy after login

node_modules/esm/package.json

{
  "name": "greeter",
  "main": "./entry-point.js"
  // ...
}
Copy after login
Copy after login

node_modules/esm/entry.js

module.exports = {
  greet(name) {
    return `Hello ${name}!`;
  }
};
Copy after login
Copy after login

The following runs just fine:

src/main.mjs

// notice there's no relative path (e.g. `./`)
const { greet } = require("greeter");

// logs: Hello Bob!
console.log(greet("Bob"));
Copy after login
Copy after login

However, the following fails to run:

src/main.cjs

// this remains "private"
const GREETING_PREFIX = "Hello";

// this will be exported
export function greet(name) {
  return `${GREETING_PREFIX} ${name}!`;
}
Copy after login

The reason why this is not allowed is because esm modules allow top-level await whereas the require() function is synchronous. The code could be re-written to use dynamic import(), but since it returns a Promise it forces to have something like the following:

src/main.cjs

// default export: new concept
export default function part(name) {
  return `Goodbye ${name}!`;
}
Copy after login

To mitigate this compatibility problem, some npm packages expose both cjs and mjs entry points by leveraging package.json's "exports" property with conditional exports. For example:

node_modules/esm/entry.cjs:

// notice the `.js` suffix is required
import part from "./part.js";

// dynamic import: new capability
// top-level await: new capability
const { greet } = await import("./greet.js");

// logs: Hello Alice!
console.log(greet("Alice"));

// logs: Bye Bob!
console.log(part("Bob"));
Copy after login

node_modules/esm/package.json:

{
  "name": "cjs",
  "main": "./entry.js"
}
Copy after login

Notice how "main" points to the cjs version for backwards compatibility with Node.js versions that do not support the "exports" property.

Conclusion

That's (almost) all you need to know about cjs and esm modules (as of Dec/2024 ?). Let me know your thoughts below!

The above is the detailed content of Node.js: A brief history of cjs, bundlers, and esm. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles