search
HomeWeb Front-endJS TutorialIntroduction to CommonJS, AMD and CMD of JavaScript module specifications

This article brings you an introduction to CommonJS, AMD and CMD about JavaScript module specifications. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This article comes from the article "JS Modular Programming: Completely Understand CommonJS and AMD/CMD!" Most of the summary of the article is excerpted from the original words of the article. I just took notes for the convenience of study. I will add them in time when I have new experiences in the future. If there is any infringement, the contact will be deleted. Pay tribute to the seniors!

Before I start, answer me: Why are modules important?

Answer: Because of the modules, we can use other people's code more conveniently, and load whatever modules we want for whatever functions we want. However, there is a prerequisite for this, that is, everyone must write the module in the same way, otherwise you have your way of writing, and I have my way of writing, wouldn't it be a mess!

So the following three module specifications came out, and this article also came out. Let me explain in advance that the implementation of the CommonJS specification is node.js, the implementation of the AMD (Asynchronous Module Definition) specification is require.js and curl.js, and the implementation of the CMD specification is Sea.js.

Module specifications in JS (CommonJS, AMD, CMD), if you have heard of js modularization, then you should have heard of CommonJS or AMD or even CMD. I I’ve heard it too, but I really just listened to it before. Let’s take a look now to see what these specifications are and what they do. This article includes the sources of these three specifications and the principles of their corresponding products.

1. CommonJS Specification

1. At first, everyone thought that JS was a piece of cake and of no use. The officially defined API can only build browser-based applications. It’s funny to me. This It's too narrow (I used a high-end word, quack), and CommonJS can't stand it anymore. CommonJS API defines many APIs used by ordinary applications (mainly non-browser applications), thus filling this gap. Its ultimate goal is to provide a standard library similar to Python, Ruby and Java. In this case, developers can use the CommonJS API to write applications, and then these applications can run in different JavaScript interpreters and different host environments.

In systems compatible with CommonJS, you can use JavaScript to develop the following programs:

(1). Server-side JavaScript applications
(2). Command line tools
( 3). Graphical interface applications
(4).Hybrid applications (such as Titanium or Adobe AIR)

In 2009, American programmer Ryan Dahl created the node.js project, which will JavaScript language is used for server-side programming. This marks the official birth of "Javascript modular programming". Because to be honest, in a browser environment, not having modules is not a particularly big problem. After all, the complexity of web programs is limited; But on the server side, there must be modules to interact with the operating system and other applications, otherwise There is no way to program at all. NodeJS is the implementation of the CommonJS specification, and webpack is also written in the form of CommonJS.

The module system of node.js is implemented with reference to the CommonJS specification. In CommonJS, there is a global method require(), which is used to load modules. Assuming there is a math module math.js, it can be loaded as follows.

var math = require('math');

Then, you can call the method provided by the module:

var math = require('math');

  math.add(2,3); // 5

The modules defined by CommonJS are divided into: {module reference (require)} {module definition (exports)} {module identification (module)}

require() is used to introduce external modules; exports object Used to export methods or variables of the current module, the only export port; the module object represents the module itself.

Although Node follows the specifications of CommonJS, it has made some trade-offs and added some new things.

However, after talking about CommonJS and also talking about Node, I think we need to understand NPM first. As the package manager of Node, NPM is not to help Node solve the installation problem of dependent packages. Then it must also follow the CommonJS specification. It follows the package specification (or theory). CommonJS WIKI talks about its history, and also introduces modules, packages, etc.

Let’s talk about the principle and simple implementation of commonJS:

1. Principle
The fundamental reason why browsers are not compatible with CommonJS is the lack of four Node.js environment variables.

module
exports
require
global

As long as these four variables can be provided, the browser can load the CommonJS module.

The following is a simple example.

var module = {
  exports: {}
};

(function(module, exports) {
  exports.multiply = function (n) { return n * 1000 };
}(module, module.exports))

var f = module.exports.multiply;
f(5) // 5000

The above code provides two external variables, module and exports, to an immediate execution function, and the module is placed in this immediate execution function. The output value of the module is placed in module.exports, thus realizing the loading of the module.

2. AMD specification

After nodeJS based on the commonJS specification came out, the concept of server-side modules has been formed. Naturally, everyone wants client-side modules. And it is best if the two are compatible, so that a module can run on both the server and the browser without modification. However, due to a major limitation, the CommonJS specification is not suitable for browser environments. Or the above code, if run in the browser, there will be a big problem, can you see it?

var math = require('math');
math.add(2, 3);

第二行math.add(2, 3),在第一行require('math')之后运行,因此必须等math.js加载完成。也就是说,如果加载时间很长,整个应用就会停在那里等。您会注意到 require 是同步的。

这对服务器端不是一个问题,因为所有的模块都存放在本地硬盘,可以同步加载完成,等待时间就是硬盘的读取时间。但是,对于浏览器,这却是一个大问题,因为模块都放在服务器端,等待时间取决于网速的快慢,可能要等很长时间,浏览器处于"假死"状态。

因此,浏览器端的模块,不能采用"同步加载"(synchronous),只能采用"异步加载"(asynchronous)。这就是AMD规范诞生的背景。

CommonJS是主要为了JS在后端的表现制定的,他是不适合前端的,AMD(异步模块定义)出现了,它就主要为前端JS的表现制定规范。

AMD是"Asynchronous Module Definition"的缩写,意思就是"异步模块定义"。它采用异步方式加载模块,模块的加载不影响它后面语句的运行。所有依赖这个模块的语句,都定义在一个回调函数中,等到加载完成之后,这个回调函数才会运行。

AMD也采用require()语句加载模块,但是不同于CommonJS,它要求两个参数:

require([module], callback);

第一个参数[module],是一个数组,里面的成员就是要加载的模块;第二个参数callback,则是加载成功之后的回调函数。如果将前面的代码改写成AMD形式,就是下面这样:

require(['math'], function (math) {
    math.add(2, 3);
});

math.add()与math模块加载不是同步的,浏览器不会发生假死。所以很显然,AMD比较适合浏览器环境。目前,主要有两个Javascript库实现了AMD规范:require.js和curl.js。

Require.js主要提供define和require两个方法来进行模块化编程,前者用来定义模块,后者用来调用模块。RequireJS就是实现了AMD规范的呢。

三、CMD规范

大名远扬的玉伯写了seajs,就是遵循他提出的CMD规范,与AMD蛮相近的,不过用起来感觉更加方便些,最重要的是中文版,应有尽有:seajs官方doc

define(function(require,exports,module){...});

前面说AMD,说RequireJS实现了AMD,CMD看起来与AMD好像呀,那RequireJS与SeaJS像不像呢?虽然CMD与AMD蛮像的,但区别还是挺明显的,官方非官方都有阐述和理解,我觉得吧,说的都挺好


The above is the detailed content of Introduction to CommonJS, AMD and CMD of JavaScript module specifications. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 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: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 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.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 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 Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function