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}!`; }
greet-2.js
var greet = "...";
index.html
<meta charset="utf-8"> <title>Collision example</title> <!-- 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>
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;
src/main.js
// notice the `.js` suffix is missing const { greet } = require("./greet"); // logs: Hello Alice! console.log(greet("Alice"));
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" // ... }
node_modules/greeter/entry-point.js
module.exports = { greet(name) { return `Hello ${name}!`; } };
src/main.js
// notice there's no relative path (e.g. `./`) const { greet } = require("greeter"); // logs: Hello Bob! console.log(greet("Bob"));
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}!`; }
src/part.js
var greet = "...";
src/main.js
<meta charset="utf-8"> <title>Collision example</title> <!-- 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>
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;
node_modules/cjs/entry.js
// notice the `.js` suffix is missing const { greet } = require("./greet"); // logs: Hello Alice! console.log(greet("Alice"));
node_modules/esm/package.json
{ "name": "greeter", "main": "./entry-point.js" // ... }
node_modules/esm/entry.js
module.exports = { greet(name) { return `Hello ${name}!`; } };
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"));
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}!`; }
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}!`; }
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"));
node_modules/esm/package.json:
{ "name": "cjs", "main": "./entry.js" }
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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
