Home > Article > Web Front-end > What is the difference between front-end modular AMD and CMD?
Difference: AMD and CMD handle the execution timing of dependent modules differently. AMD advocates pre-dependency, and declares the modules it depends on when defining a module; CMD advocates nearby dependencies, only when a certain Then go to require when you install the module.
In the early days of the development of JavaScript, it was to implement simple page interaction logic in just a few words; now CPU and browser performance have been greatly improved. Many page logic has been migrated to the client (form validation, etc.). With the advent of the web2.0 era, Ajax technology has been widely used, jQuery and other front-end libraries have emerged in endlessly, and the front-end code has become increasingly expanded. At this time, JavaScript is used as an embedded The positioning of the scripting language has been shaken, but JavaScript does not provide any obvious help for organizing code. It does not even have the concept of classes, let alone modules. JavaScript’s extremely simple code organization specifications are not enough to manage such a huge scale of code.
ModuleSince JavaScript cannot handle such a large-scale code, we can learn from how other languages handle large-scale programming. There is an important concept in Java -
package. Logically related codes are organized into the same package. The package is a relatively independent kingdom. There is no need to worry about naming conflicts. What if it is used externally? ? Just import
the corresponding package<pre class="brush:php;toolbar:false">import java.util.ArrayList;</pre>
Unfortunately, JavaScript does not provide similar functions because of its positioning during design. Developers need to simulate similar functions to isolate and organize complex JavaScript code is called modularity.
A module is a file that implements a specific function. With a module, we can use other people's code more conveniently, and load whatever module we want for whatever function we want. Module development needs to follow certain norms, and everyone will get messed up if they do their own thing
The process of forming specifications is painful. The pioneers of the front-end started in the stage of slash-and-burn farming and drinking blood, and the development has begun to take shape now. Let’s briefly understand this paragraph Extraordinary journey
Function encapsulationWhen we talked about functions, we mentioned that one function of a function is to package a set of statements to implement specific logic, and the scope of JavaScript It is based on functions, so it is natural to use functions as the first step in modularization. Writing several related functions in a file is the first module.
function fn1(){ statement } function fn2(){ statement }
This way, when needed, it can be Just call the function in the file where the function is located.
The disadvantages of this approach are obvious: it pollutes global variables, there is no guarantee that variable names will not conflict with other modules, and there is no relationship between module members.
ObjectIn order to solve the above problem, the object writing method came into being, which can encapsulate all module members in an object
var myModule = { var1: 1, var2: 2, fn1: function(){ }, fn2: function(){ } }
This way We reference the corresponding file when we want to call the module, and then
myModule.fn2();
This avoids variable pollution, as long as the module name is unique, and members in the same module are also related
It seems A good solution, but it also has flaws. External members can modify internal members at will
myModel.var1 = 100;
This will cause unexpected security problems
Execute the function immediatelyYou can achieve the purpose of hiding details by executing the function immediately
var myModule = (function(){ var var1 = 1; var var2 = 2; function fn1(){ } function fn2(){ } return { fn1: fn1, fn2: fn2 }; })();
In this way, variables and functions that we have not exposed cannot be modified outside the module
The above approach is the basis of our modularization. Currently , there are two main types of popular JavaScript module specifications:
CommonJS and AMD
Let’s talk about CommonJS first Since there is no modular programming on the web page, only the page JavaScript logic is complex, but it can still work, but there must be modules on the server side. Therefore, although JavaScript has been developed on the web side for so many years, the first popular modular specification has Brought by server-side JavaScript applications, the CommonJS specification is carried forward by NodeJS, which marks the official stage of JavaScript modular programming.
module.exports
object, we need to put the content that the module wants to output into this object
require
method, which reads a file and executes it, returning the module.exports
object inside the file
//模块定义 myModel.js var name = 'Byron'; function printName(){ console.log(name); } function printFullName(firstName){ console.log(firstName + name); } module.exports = { printName: printName, printFullName: printFullName } //加载模块 var nameModule = require('./myModel.js'); nameModule.printName();
js
extension, use a relative path, or use an absolute path, or even omit the path directly. Use the module name (provided that the module is a built-in system module)仔细看上面的代码,会发现 这在服务器端实现很简单,也很自然,然而, 想在浏览器端实现问题却很多。 浏览器端,加载JavaScript最佳、最容易的方式是在document中插入 解决思路之一是,开发一个服务器端组件,对模块代码作静态分析,将模块与它的依赖列表一起返回给浏览器端。 这很好使,但需要服务器安装额外的组件,并因此要调整一系列底层架构。 另一种解决思路是,用一套标准模板来封装模块定义,但是对于模块应该怎么定义和怎么加载,又产生的分歧: AMD AMD 即 由于不是JavaScript原生支持,使用AMD规范进行页面开发需要用到对应的库函数,也就是大名鼎鼎 requireJS主要解决两个问题 看一个使用requireJS的例子 语法 requireJS定义了一个函数 define,它是全局变量,用来定义模块 在页面上使用 require()函数接受两个参数 require()函数在加载依赖的函数的时候是异步加载的,这样浏览器不会失去响应,它指定的回调函数,只有前面的模块都加载成功后,才会运行,解决了依赖性的问题。 CMD CMD 即 语法 Sea.js 推崇一个模块一个文件,遵循统一的写法 define 因为CMD推崇 factory有三个参数 require require 是 factory 函数的第一个参数 require 是一个方法,接受 模块标识 作为唯一参数,用来获取其他模块提供的接口 exports exports 是一个对象,用来向外提供模块接口 module module 是一个对象,上面存储了与当前模块相关联的一些属性和方法 demo AMD与CMD区别 关于这两个的区别网上可以搜出一堆文章,简单总结一下 最明显的区别就是在模块定义时对依赖的处理不同 AMD推崇依赖前置,在定义模块的时候就要声明其依赖的模块 CMD推崇就近依赖,只有在用到某个模块的时候再去require 这种区别各有优劣,只是语法上的差距,而且requireJS和SeaJS都支持对方的写法 AMD和CMD最大的区别是对依赖模块的执行时机处理不同,注意不是加载的时机或者方式不同 Many people say that requireJS is an asynchronous loading module, and SeaJS is a synchronous loading module. This understanding is actually inaccurate. In fact, loading modules are all asynchronous, but AMD relies on front-end, and js can easily know who the dependent module is. , loads immediately, and CMD relies on nearby dependencies. You need to use the module to be converted into a string and parse it again to know which modules are dependent on it. This is also a point that many people criticize CMD. It sacrifices performance to bring development convenience. In fact, parsing modules uses The time is short enough to be ignored Why do we say that the difference between the two is the different execution timing of dependent modules? Why do many people think that ADM is asynchronous and CMD is synchronous (except for the name...) The modules are also loaded asynchronously. AMD will execute the modified module after loading the module. After all modules are loaded and executed, it will enter the require callback function and execute the main logic. This effect depends on the execution order of the modules. It may not be consistent with the writing order. Depending on the network speed, which one is downloaded first and which one is executed first, but the main logic must be executed after all dependencies are loaded. CMD will not be executed after loading a certain dependent module. It's just downloading. After all dependent modules are loaded, it enters the main logic. The corresponding module is executed only when the require statement is encountered. In this way, the execution order and writing order of the modules are completely consistent. This is also what many people say AMD user experience is good because there is no delay and dependent modules are executed in advance. CMD performance is good because it is only executed when the user needs it For more programming-related knowledge, please visit: Programming Video! ! require
是同步的。模块系统需要同步读取模块文件内容,并编译执行以得到模块接口。script
标签。但脚本标签天生异步,传统CommonJS模块在浏览器环境中无法正常加载。Asynchronous Module Definition
,中文名是异步模块定义的意思。它是一个在浏览器端模块化开发的规范RequireJS
,实际上AMD 是 RequireJS 在推广过程中对模块定义的规范化的产出
// 定义模块 myModule.js
define(['dependency'], function(){
var name = 'Byron';
function printName(){
console.log(name);
}
return {
printName: printName
};
});
// 加载模块
require(['myModule'], function (my){
my.printName();
});
define(id?, dependencies?, factory);
require
函数加载模块require([dependencies], function(){});
Common Module Definition
通用模块定义,CMD规范是国内发展出来的,就像AMD有个requireJS,CMD有个浏览器的实现SeaJS,SeaJS要解决的问题和requireJS一样,只不过在模块定义方式和模块加载(可以说运行、解析)时机上有所不同define(id?, deps?, factory)
function(require, exports, module)
require(id)
// 定义模块 myModule.js
define(function(require, exports, module) {
var $ = require('jquery.js')
$('p').addClass('active');
});
// 加载模块
seajs.use(['myModule.js'], function(my){
});
The above is the detailed content of What is the difference between front-end modular AMD and CMD?. For more information, please follow other related articles on the PHP Chinese website!