Table of Contents
1. CommonJS Specification
2. AMD specification
三、CMD规范
Home Web Front-end JS Tutorial Introduction to CommonJS, AMD and CMD of JavaScript module specifications

Introduction to CommonJS, AMD and CMD of JavaScript module specifications

Nov 20, 2018 pm 03:35 PM
javascript

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
Copy after login

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
Copy after login

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
Copy after login

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);
Copy after login

第二行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);
Copy after login

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

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

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){...});
Copy after login

前面说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 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 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles